<template>
  <basic-container>
    <div class="search-content">
      <el-form :model="searchFrom" label-width="140px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="执行包年度">
              <el-date-picker clearable class="w100" v-model="searchFrom.year" type="year" placeholder="请选择执行包年度" format="yyyy" value-format="yyyy"> </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执行包季度">
              <el-select v-model="searchFrom.quarter" placeholder="请选择服务季度" class="w100" clearable>
                <el-option label="第一季度" :value="1"></el-option>
                <el-option label="第二季度" :value="2"></el-option>
                <el-option label="第三季度" :value="3"></el-option>
                <el-option label="第四季度" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务提交时间">
              <el-date-picker class="w100" clearable v-model="searchFrom.createTime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="服务类型">
              <el-select v-model="searchFrom.taskTypeId" placeholder="请选择服务类型" class="w100" clearable>
                <el-option :label="item.name" :value="item.id" v-for="item in taskTypeAvailArr" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="服务提供商">
              <el-select v-model="searchFrom.vendorId" placeholder="请选择服务提供商" class="w100" clearable filterable>
                <el-option v-for="item in deptListArr" :key="item.entId" :label="item.name" :value="item.entId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="代表姓名">
              <el-select v-model="searchFrom.salesId" placeholder="请选择代表姓名" class="w100" clearable filterable>
                <el-option v-for="item in userListArr" :key="item.userId" :label="item.realName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品所属生产企业">
              <el-select v-model="searchFrom.mahName" @change="mahNameChange" placeholder="请选择产品所属生产企业" class="w100" clearable>
                <el-option v-for="item in mahNameArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关联产品名称">
              <el-select v-model="searchFrom.skuId" placeholder="请选择关联产品名称" class="w100" :disabled="drugDisabled" clearable filterable>
                <el-option v-for="item in currDrugList" :key="item.id" :label="item.drugNameTy" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="执行包所属省份">
              <el-select v-model="searchFrom.provAbbr" placeholder="请选择省份" class="w100" clearable>
                <el-option v-for="province in abbreviationsProvincesList" :key="province" :label="province" :value="province" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上游服务包名称">
              <el-select v-model="searchFrom.pkgIds" placeholder="请选择上游服务包名称" class="w100" clearable filterable>
                <el-option v-for="(item, index) in relPkgNameArr" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div class="search-btns">
              <el-button type="success" class="btn-style" @click="clickBtn">搜索</el-button>
              <el-button @click="clearSearch">清空</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="check-btns">
      <el-button type="primary" @click="allClick">批量审核</el-button>
      <el-button type="primary" @click="quickAuditClick">快捷审核</el-button>
    </div>
    <div class="tips">当前表格已选择{{ totalNum }}项，总积分：{{ totalScore }}</div>

    <div class="table">
      <vxe-table
        ref="tableRef"
        border
        allAlign="center"
        show-overflow
        highlight-hover-row
        height="auto"
        empty-text="暂无匹配数据"
        v-loading="tableLoading"
        :data="tableData"
        :scroll-y="{ enabled: false }"
        :scroll-x="{ enabled: true }"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @checkbox-all="selectAllChangeEvent"
        @checkbox-change="selectChangeEvent"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-table-column type="seq" title="序号" width="100"></vxe-table-column>
        <vxe-table-column field="taskNumber" title="服务编号" width="200"></vxe-table-column>
        <vxe-table-column field="cycle" title="服务包周期" width="200"> </vxe-table-column>
        <vxe-table-column field="relPkgName" title="上游服务包名称" width="250"> </vxe-table-column>
        <vxe-table-column field="pkgName" title="服务包名称" width="200"></vxe-table-column>
        <vxe-table-column field="taskTypeName" title="服务类型" width="200"></vxe-table-column>
        <vxe-table-column field="taskScore" title="服务分值" width="100"></vxe-table-column>
        <vxe-table-column field="salesName" title="代表姓名" width="150"></vxe-table-column>
        <vxe-table-column field="createTime" title="服务提交时间" width="200"></vxe-table-column>
        <!-- <vxe-table-column field="checkResultName" title="服务当前状态" width="120"></vxe-table-column> -->
        <vxe-table-column field="entName" title="服务提供商" width="200"></vxe-table-column>
        <vxe-table-column field="mahName" title="产品所属生产企业" width="200"></vxe-table-column>
        <vxe-table-column field="skuName" title="关联产品名称" width="200"></vxe-table-column>
        <vxe-table-column field="provAbbr" title="执行包所属省份" width="130"></vxe-table-column>
        <vxe-table-column title="操作" fixed="right" width="130">
          <template slot-scope="scope">
            <div class="btns">
              <el-button type="text" @click="reviewBtn(scope.row)">审核</el-button>
              <el-button type="text" @click="serviceDetail(scope.row)">服务详情</el-button>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>

    <vxe-pager
      :current-page.sync="page.currentPage"
      :page-size.sync="page.pageSize"
      :total="page.total"
      :page-sizes="page.pageSizes"
      @page-change="pageChange"
      :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>

    <!-- 审核弹窗 -->
    <el-dialog title="审核" :close-on-click-modal="false" :visible.sync="reviewDialog" top="12vh" width="50%" :before-close="handleClose" center>
      <div class="reviewContent" v-loading="loading">
        <div class="check-tips">审核令牌有效期为3分钟，请在【{{ expireTime }}】前完成审核操作，如果失效，请重新打开弹窗。</div>
        <div class="review-detail" v-if="singleFlag">
          <div class="teskDetailsty">服务详情</div>
          <TaskDetail ref="taskDetailRef" :id="currentTaskId" />
        </div>
        <div class="teskDetailsty">审批意见</div>
        <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="100px">
          <el-form-item label="审批意见:" prop="checkResult" class="formitem-box">
            <el-radio-group v-model="taskForm.checkResult">
              <el-radio :label="true">通过</el-radio>
              <el-radio :label="false">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="意见说明:"
            prop="checkMessage"
            class="formitem-box"
            :rules="[
              {
                required: !taskForm.checkResult,
                message: '请输入审批说明',
                trigger: 'blur'
              }
            ]"
          >
            <el-input type="textarea" v-model="taskForm.checkMessage"></el-input>
          </el-form-item>
          <refuseReason @selectRefuseReason="selectRefuseReason" />
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="checkForm" v-loading="loading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="批量审核预处理结果" :visible.sync="lockedDialog" top="12vh" width="50%" :before-close="lockedDialogClose" center :show-close="false">
      <div>
        <div class="check-tips">
          本次批量审核，拟处理服务 【{{ pretreatmentInfo?.total?.length }}】 个, 成功预留【{{ pretreatmentInfo?.available?.length }}】个，忽略【{{
            pretreatmentInfo?.locked?.length
          }}】个, 继续审核请点击“确定”，放弃请点击“取消”（有效期三分钟）。
        </div>
        <el-table
          :data="pretreatmentInfo?.total"
          border
          style="width: 100%"
          max-height="500"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column prop="taskId" label="任务ID"> </el-table-column>
          <el-table-column prop="status" label="预留结果">
            <template slot-scope="scope">
              <span :class="scope.row.status === '成功' ? 'status-success' : 'status-fail'">{{ scope.row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="lockInfo" label="结果说明"> </el-table-column>
          <el-table-column prop="expireAt" label="锁定至"> </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="lockedDialogClose">取 消</el-button>
        <el-button type="primary" @click="lockedBtn">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getTaskV2PageApi,
  getTaskTypeAvailApi,
  getDeptv2Avail,
  getDrug2Avail,
  getUserV2Avail,
  getTaskV2TokenApi,
  checkSingleApi,
  taskV2CheckBatchApi,
  getPkgV2Api,
  getPretreatmentApi,
  pretreatmentClearApi
} from '@/api/serviceManagement/servicesToBeReviewed/index.js';
import { tableOptin } from './index.js';
import { getDictType } from '@/api/common';
import abbreviationsProvinces from '@/const/abbreviationsProvinces.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
import TaskDetail from './components/TaskDetail.vue';
import refuseReason from '@/components/refuseReason';
import Config from '@/settings';
import color from '@/mixins/color';

export default {
  components: { refuseReason, TaskDetail },
  data() {
    return {
      tableOptin,
      tableData: [],
      tableLoading: false,
      checkResultArr: [],
      taskTypeAvailArr: [],
      mahNameArr: [],
      deptListArr: [],
      drugListArr: [],
      userListArr: [],
      currDrugList: [],
      relPkgNameArr: {},
      searchLoading: false,
      drugDisabled: true,
      abbreviationsProvincesList: abbreviationsProvinces,
      nodeId: '',
      searchFrom: {
        year: '',
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: 3
      },
      totalNum: 0,
      totalScore: 0,
      page: {
        pageSizes: [10, 20, 50, 100, 300, 500],
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      reviewDialog: false,
      taskForm: {
        checkResult: '',
        checkMessage: ''
      },
      rules: {
        checkResult: [{ required: true, message: '请选择审批意见', trigger: 'change' }]
      },
      singleFlag: false,
      checkIds: [],
      loading: false,
      currentTaskId: '',
      reviewToken: '',
      expireTime: '',
      pretreatmentInfo: {},
      lockedInfo: [],
      lockedDialog: false,
      checkNodeId: ''
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getDict();

    let nodeId = '';
    const roles = this.userInfo.roles;

    switch (true) {
      // 43	地市管理员
      case roles.includes(43):
        nodeId = 2;
        break;
      // 4	区域管理员
      case roles.includes(4):
        nodeId = 3;
        break;
      // 42	市场管理员
      case roles.includes(42):
        nodeId = 8;
        break;
      // 40	商务管理员
      case roles.includes(40):
        nodeId = 9;
        break;
      // 39	事业部总经理
      case roles.includes(39):
        nodeId = 6;
        break;
      // 41	事业部分管领导
      case roles.includes(41):
        nodeId = 5;
        break;
      default:
        nodeId = 1;
    }
    this.checkNodeId = nodeId;
  },
  mounted() {
    const roles = this.userInfo.roles;

    let nodeId = '';
    switch (true) {
      // 43	地市管理员
      case roles.includes(43):
        nodeId = 1;
        break;
      // 4	区域管理员
      case roles.includes(4):
        nodeId = 2;
        break;
      // 42	市场管理员： 获取审核节点为3和9   nodeid为12
      case roles.includes(42):
        nodeId = 12;
        break;

      // 40	商务管理员： 获取审核节点为3和8   nodeid为11
      case roles.includes(40):
        nodeId = 11;
        break;
      case roles.includes(41) && roles.includes(39):
        nodeId = 24;
        break;
      // 41	事业部分管领导
      case roles.includes(41):
        nodeId = 9;
        break;
      // 39	事业部总经理
      case roles.includes(39):
        nodeId = 15;
        break;
      default:
        nodeId = 1;
    }

    const lastYear = dayjs().subtract(1, 'year').format('YYYY');

    this.searchFrom.year = lastYear;
    this.nodeId = nodeId;
    this.searchFrom.nodeId = nodeId;
    this.getList();
  },

  methods: {
    getDict() {
      getDictType({ type: 'task_status' }).then((res) => {
        this.checkResultArr = res.data.data;
      });
      getDictType({ type: 'mah_name' }).then((res) => {
        this.mahNameArr = res.data.data;
      });
      getTaskTypeAvailApi().then((res) => {
        this.taskTypeAvailArr = res.data.data;
      });
      getDeptv2Avail().then((res) => {
        this.deptListArr = res.data.data;
      });
      getUserV2Avail().then((res) => {
        this.userListArr = res.data.data;
      });
      getDrug2Avail().then((res) => {
        this.drugListArr = res.data.data;
      });
      getPkgV2Api().then((res) => {
        let arr = [];
        let data = res.data.data;
        for (let key in data) {
          let obj = {
            label: key,
            value: data[key]
          };
          arr.push(obj);
        }

        this.relPkgNameArr = arr;
      });
    },
    async getList() {
      this.totalNum = 0;
      this.totalScore = 0;
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize
        },
        this.searchFrom
      );
      const res = await getTaskV2PageApi(obj);
      this.tableLoading = false;
      if (res.data.code === 0) {
        this.tableData = res.data.data.records;
        this.tableData.forEach((item) => {
          const currA = this.taskTypeAvailArr.find((itn) => itn.id === item.taskTypeId);
          const currB = this.checkResultArr.find((itn) => itn.value === item.taskStatus);
          item.taskTypeName = currA?.name ?? '';
          item.checkResultName = currB?.label ?? '';
          item.cycle = item.pkgStartTime + '~' + item.pkgEndTime;
        });
        this.page.total = res.data.data.total;
      }
    },
    clickBtn() {
      this.tableData = [];
      this.page.currentPage = 1;
      this.getList();
    },
    clearSearch() {
      this.searchFrom = {
        year: dayjs().subtract(1, 'year').format('YYYY'),
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: 3
      };
      this.searchFrom.nodeId = this.nodeId;
    },
    pageChange(obj) {
      this.page.currentPage = obj.currentPage;
      this.page.pageSize = obj.pageSize;
      this.getList();
    },
    mahNameChange(e) {
      if (e) {
        const curr = this.drugListArr[e];
        this.currDrugList = curr;

        this.drugDisabled = false;
      } else {
        this.searchFrom.skuId = '';
        this.currDrugList = [];
        this.drugDisabled = true;
      }
    },
    selectAllChangeEvent(obj) {
      const records = obj.selection;
      this.checkIds = records.map((item) => item.taskId);
      this.totalNum = records.length;
      this.totalScore = records.reduce((pre, cur) => {
        return pre + (Number(cur.taskScore) || 0);
      }, 0);
    },
    selectChangeEvent(obj) {
      const records = obj.selection;
      this.checkIds = records.map((item) => item.taskId);
      this.totalNum = records.length;
      this.totalScore = records.reduce((pre, cur) => {
        return pre + (Number(cur.taskScore) || 0);
      }, 0);
    },

    selectRefuseReason(refuseReason) {
      let info;
      if (this.taskForm.checkMessage) {
        info = this.taskForm.checkMessage + refuseReason + '；';
      } else {
        info = refuseReason + '；';
      }

      this.$set(this.taskForm, 'checkMessage', info);
    },
    async reviewBtn(row) {
      this.currentTaskId = row.taskId;
      await this.getToken([row.taskId]);
      this.reviewDialog = true;
      this.singleFlag = true;
      this.$nextTick(() => {
        this.$refs.taskDetailRef.getInfo(row.taskId);
      });
    },
    async handleClose() {
      let taskIds = [];
      let token = '';
      if (this.singleFlag) {
        token = this.reviewToken;
        taskIds = [this.currentTaskId];
      } else {
        taskIds = this.pretreatmentInfo.available.map((item) => item.taskId);
        token = this.pretreatmentInfo?.token?.token;
      }

      if (token) {
        const obj = {
          taskIds: taskIds,
          token: token,
          nodeId: this.checkNodeId
        };
        await pretreatmentClearApi(obj);
        this.pretreatmentInfo = {};
      }
      this.reviewDialog = false;
      this.taskForm = {
        checkResult: '',
        checkMessage: ''
      };
      this.checkIds = [];
      this.currentTaskId = '';
      this.getList();
    },
    serviceDetail(row) {
      window.open(
        Config.outsideUrl + '/h5/#/pages/task/task-detail/index?id=' + row.taskId,
        'newwindow',
        'height=500, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
      );
    },

    checkForm() {
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          this.checkBtn();
        }
      });
    },

    async getToken(taskIds) {
      const tokenRes = await getTaskV2TokenApi({ taskIds: taskIds });
      if (tokenRes.data.code !== 0 || !tokenRes.data.data?.token) {
        return this.$message.error('获取token失败');
      }
      this.reviewToken = tokenRes.data.data.token;
      this.expireTime = tokenRes.data.data.expireTime;
    },

    async allClick() {
      if (!this.checkIds.length) {
        return this.$message.error('请选择待审核数据');
      }
      this.getPretreatment();

      this.singleFlag = false;
    },
    async getPretreatment() {
      const res = await getPretreatmentApi({ taskIds: this.checkIds, nodeId: this.checkNodeId });
      if (res.data.code === 0) {
        this.pretreatmentInfo = res.data.data;
        this.lockedInfo = res.data.data.locked;
        this.lockedDialog = true;
      }
    },
    async lockedBtn() {
      if (this.pretreatmentInfo.available.length) {
        this.lockedDialog = false;
        this.lockedInfo = [];
        this.reviewDialog = true;
        await this.getToken(this.checkIds);
      } else {
        this.$message.info('当前无可审核数据！');
        this.lockedDialogClose();
      }
    },
    async lockedDialogClose() {
      const taskIds = this.pretreatmentInfo.available.map((item) => item.taskId);
      if (this.pretreatmentInfo?.token?.token) {
        const obj = {
          taskIds: taskIds,
          token: this.pretreatmentInfo.token.token,
          nodeId: this.checkNodeId
        };
        await pretreatmentClearApi(obj);
        this.pretreatmentInfo = {};
      }
      this.getList();
      this.lockedDialog = false;
      this.lockedInfo = [];
    },
    // 快捷审核
    quickAuditClick() {
      this.$router.push({
        path: '/serviceManagement/quickReview/index'
      });
    },
    async checkBtn() {
      let nodeId = '';
      const roles = this.userInfo.roles;

      switch (true) {
        // 43	地市管理员
        case roles.includes(43):
          nodeId = 2;
          break;
        // 4	区域管理员
        case roles.includes(4):
          nodeId = 3;
          break;
        // 42	市场管理员
        case roles.includes(42):
          nodeId = 8;
          break;
        // 40	商务管理员
        case roles.includes(40):
          nodeId = 9;
          break;
        // 39	事业部总经理
        case roles.includes(39):
          nodeId = 6;
          break;
        // 41	事业部分管领导
        case roles.includes(41):
          nodeId = 5;
          break;
        default:
          nodeId = 1;
      }
      console.log('nodeId', nodeId);

      let res;
      // 单条审核
      if (this.singleFlag) {
        let obj = {
          token: this.reviewToken,
          taskId: this.currentTaskId,
          checkResult: this.taskForm.checkResult,
          checkMessage: this.taskForm.checkMessage,
          nodeId: nodeId
        };
        res = await checkSingleApi(obj);
      } else {
        const ids = this.pretreatmentInfo?.available.map((item) => item.taskId);
        this.loading = true;
        let obj = {
          token: this.pretreatmentInfo?.token?.token,
          taskIds: ids,
          checkResult: this.taskForm.checkResult,
          checkMessage: this.taskForm.checkMessage,
          nodeId: nodeId
        };
        try {
          res = await taskV2CheckBatchApi(obj);
          this.loading = false;
        } catch (err) {
          this.loading = false;
        }
      }

      if (res.data.code === 0 && res.data.data) {
        this.$message.success('审核成功！');
        this.reviewDialog = false;
        this.taskForm = {
          checkResult: '',
          checkMessage: ''
        };
        this.checkIds = [];
        this.currentTaskId = '';
        this.getList();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.search-btns {
  margin-left: 50px;
  display: flex;

  .btn-style {
    margin-right: 15px;
  }
}

.tips {
  display: inline-block;
  padding: 0 5px;
  color: #85ce61;
  border-radius: 3px;
  line-height: 14px;
  font-size: 14px;
}

.table {
  min-height: 1000px;
  max-height: 1500px;
}
.teskDetailsty {
  width: 100%;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  font-weight: 600;
  color: #333333;
  border-bottom: 1px solid #d7d6d5;
  margin: 0 0 10px 0;
}
.check-btns {
  width: 150px;
  display: flex;
  justify-content: space-between;
}

.check-tips {
  margin-bottom: 5px;
  font-size: 16px;
  color: rgb(233 77 77);
  text-align: center;
  font-weight: 600;
}
.status-success {
  color: #85ce61;
}
.status-fail {
  color: rgb(233 77 77);
}
</style>
