<template>
  <div v-loading="loading" class="operatorGroup-wrap">
    <div class="self-hint">
      <i class="el-icon-message-solid" />
      <div>
        <p>许可续期仅可为购买过许可的客服续期</p>
        <p>在系统提交续期任务后,仍然需要通过购买许可流程发送申请邮件以及付款</p>
        <p>取消任务仅可取消还未支付的订单，已经支付的不可以取消，只能走退款流程</p>
      </div>
    </div>
    <div class="screenBox">
      <div class="filter-wrap">
        <!-- 任务名称 -->
        <selfInputV2 style=""  :labelWidth="true" v-model="filter.title" label_name="任务名称" placeholder="请输入" @change="onChangeTitle" />
        <!-- 任务状态 -->
        <selfChannelV2 style="margin-right: 10px;" v-model="filter.status" type='licenseTaskStatus' title="任务状态" :labelWidth="true" @change="onChangeStatus" />
      </div>
      <el-button type="primary" size="mini" @click="onClickCreateBtn">新建续期任务</el-button>
    </div>
    <el-table :height="height" :data="list" tooltip-effect="dark" style="width: 100%;margin-top:10px">
      <el-table-column label="任务名称" prop="title" min-width="200" align="center" fixed="left" />
      <el-table-column label="客服数量" prop="user_num" min-width="100" align="center">
        <template slot-scope="{ row }">
          <span class="btn c-00b38a" @click="onClickUserNum(row)">{{ row.user_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" min-width="160" show-overflow-tooltip align="center" />
      <el-table-column label="任务状态" prop="status" min-width="120" align="center">
        <template slot-scope="{ row }">
          <span :class="{
            'c-F03F5C': row.status == licenseTaskStatusCode.FAILED,
            'c-00B38A': row.status == licenseTaskStatusCode.COMPLETED,
          }">{{ licenseTaskStatusMap.get(row.status) || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="异常信息" prop="err_msg" min-width="240" show-overflow-tooltip align="center">
        <template slot-scope="{ row }">
          <div v-if="row.err_msg && row.err_msg.length">
            <div v-for="(err, idx) in row.err_msg" :key="idx">{{ err }}</div>
          </div>
          <div v-else> - </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160" align="center" fixed="right">
        <template slot-scope="{ row }">
          <span v-if="isShowCancelTaskBtn(row.status)" class="btn c-00b38a" @click="onClickCancelTask(row)">关闭任务</span>
          <span v-else> - </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination" v-show="pagination.total > 0">
      <el-pagination background :current-page="pagination.page" @current-change="handleCurrentChange" layout="prev, pager, next" :page-count="Number(pagination.pages)" />
    </div>

    <!-- S 创建续期任务 -->
    <createTaskDrawer
      v-model="createTaskDrawerVisible"
      :rule_id="currentTaskId"
      @confirm="onConfirmCreateTask"
      @cancel="onCancelCreateTask"
    />
    <!-- E 创建续期任务 -->

    <!-- S 取消失败信息 -->
    <errListDialog
      :dialogVisible="errListDialogVisible"
      :list="currentErrList"
      @close="onCloseErrList"
    />
    <!-- E 取消失败信息 -->
  </div>
</template>

<script>
import selfChannelV2 from '@/components/assembly/screen/channelV2.vue'
import selfInputV2 from '@/components/assembly/screen/inputV2.vue'
import createTaskDrawer from './createTaskDrawer.vue'
import errListDialog from './errListDialog.vue'
import { licenseTaskStatusMap, licenseTaskStatusCode } from '@/assets/js/staticTypes'

export default {
  name: 'license',
  components: {
    selfChannelV2,
    selfInputV2,
    createTaskDrawer,
    errListDialog,
  },
  data () {
    return {
      licenseTaskStatusMap,
      licenseTaskStatusCode,
      height: '',
      loading: false,
      pagination: {
        page: 1,
        page_size: 20,
        pages: 0,
        total: 0,
      },
      filter: {
        title: '',
        status: '',
      },
      list: [],

      createTaskDrawerVisible: false,
      currentTaskId: '',

      errListDialogVisible: false,
      currentErrList: [],
    }
  },
  created () {
    this.height = document.documentElement.clientHeight - 200
    this.handleGetList()
  },
  methods: {
    // 获取列表数据
    async handleGetList() {
      try {
        this.loading = true
        const url = `${this.URL.BASEURL}${this.URL.license_renewalJobList}`
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.page_size,
          title: this.filter.title,
          status: this.filter.status,
        }
        const { data: res = {} } = await this.$axios.get(url, { params })
        if (res && res.errno == 0 && Array.isArray(res.rst.data)) {
          this.list = res.rst.data;
          this.pagination.total = res.rst.pageInfo.total;
          this.pagination.pages = res.rst.pageInfo.pages;
        } else if (res.errno != 4002) {
          this.$message.warning(res.err)
          this.list = [];
          this.pagination.total = 0;
          this.pagination.pages = 0;
        }
      } catch (error) {
        console.log(error)
        this.list = [];
        this.pagination.total = 0;
        this.pagination.pages = 0;
      } finally {
        this.loading = false
      }
    },
    // 监听"任务标题"变化
    onChangeTitle(val) {
      this.filter.title = val
      this.pagination.page = 1
      this.handleGetList()
    },
    // 监听"任务状态"变化
    onChangeStatus(val) {
      this.filter.status = (val || val === 0) ? val : ''
      this.pagination.page = 1
      this.handleGetList()
    },
    // 监听当前页数变化
    handleCurrentChange(currentPage) {
      this.pagination.page = currentPage
      this.handleGetList()
    },
    // 监听点击“关闭任务”
    async onClickCancelTask({ title, rule_id }) {
      try {
        await this.$confirm(`确定关闭【${title}】任务吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.handleCancelTask(rule_id)
      } catch (error) {
        console.log(error)
      }
    },
    // 执行“关闭任务”
    async handleCancelTask(rule_id) {
      try {
        this.loading = true
        const url = `${this.URL.BASEURL}${this.URL.license_cancelRenewalJob}`
        const params = { rule_id }
        const { data: res = {} } = await this.$axios.post(url, params)
        if (res && res.errno == 0) {
          this.$message.success('操作成功')
        } else if (res.errno == 2708 && Array.isArray(res.rst) && res.rst.length) {
          this.handleShowErrList(res.rst)
        } else if (res.errno != 4002) {
          this.$message.warning(res.err)
        }
        this.handleGetList()
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    isShowCancelTaskBtn(status) {
      const allowedStatus = [licenseTaskStatusCode.NOT_EXECUTED, licenseTaskStatusCode.EXECUTED]
      return allowedStatus.includes(status)
    },

    // 监听点击“客服数量”
    onClickUserNum(row) {
      this.currentTaskId = row.rule_id
      this.createTaskDrawerVisible = true
    },
    // 监听点击“新建续期任务”
    onClickCreateBtn() {
      this.currentTaskId = ''
      this.createTaskDrawerVisible = true
    },
    onConfirmCreateTask() {
      this.createTaskDrawerVisible = false
      this.pagination.page = 1
      this.handleGetList()
    },
    onCancelCreateTask() {
      this.createTaskDrawerVisible = false
    },

    handleShowErrList(list) {
      this.currentErrList = [...list]
      this.errListDialogVisible = true
    },
    onCloseErrList() {
      this.errListDialogVisible = false
      this.currentErrList = []
    },
  },
}
</script>

<style lang="scss" scoped>
@import "@/style/list.scss";
.operatorGroup-wrap {
  .screenBox {
    background: #fff;
    padding: 5px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .filter-wrap {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
    }
  }
  .btn {
    cursor: pointer;
    margin-right: 4px;
    &:last-child {
      margin-right: 0;
    }
  }
  .lableBox_dad {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;

    .lableBox {
      font-size: 12px;
      background-color: #f0f0f0;
      padding: 4px 8px;
      margin-top: 5px;
      margin-right: 4px;
      border-radius: 4px;
    }
  }
}
</style>
