<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">
            <el-form-item label="审核状态">
              <el-select v-model="searchFrom.taskStatus" placeholder="请选择审核状态" class="w100" clearable filterable>
                <el-option label="审核通过" value="3" />
                <el-option label="审核拒绝" value="4" />
              </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="table-btns">
      <el-tooltip class="item" effect="dark" content="导出需要大量计算，请耐心等候，不要频繁点击" placement="top">
        <el-button type="primary" size="small" @click="exportBtnFn" :loading="exportLoading">导 出</el-button>
      </el-tooltip>
    </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' }"
      >
        <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="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 field="taskStatus" title="审核状态" width="130">
          <template slot-scope="scope">
            <div v-if="scope.row.taskStatus === '2'">
              <div>待服务商审核</div>
            </div>
            <div v-else-if="scope.row.taskStatus === '3'">
              <div>审核通过</div>
            </div>
            <div v-else-if="scope.row.taskStatus === '4'">
              <div>审核拒绝</div>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="已审批节点" width="120">
          <template slot-scope="scope">
            <div class="btns">
              <el-popover
                placement="left"
                width="800"
                trigger="hover"
                @hide="hide"
                @show="
                  () => {
                    show(scope.row);
                  }
                "
              >
                <div v-loading="infoLoading" class="info-list">
                  <div v-html="infoContent" class="detail-content"></div>
                </div>
                <div slot="reference" class="check-detail">审核详情</div>
              </el-popover>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" fixed="right" width="130">
          <template slot-scope="scope">
            <div class="btns"><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>
  </basic-container>
</template>

<script>
import {
  getTaskTypeAvailApi,
  getDeptv2Avail,
  getDrug2Avail,
  getUserV2Avail,
  getPkgV2Api,
  getTaskV2PageCheckedApi,
  getTaskV2CheckHisApi,
  pkgCheckExportApi
} 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';

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,
      searchFrom: {
        year: '',
        taskTypeId: '',
        quarter: '',
        createTime: '',
        provAbbr: '',
        mahName: '',
        vendorId: '',
        salesId: '',
        skuId: '',
        pkgIds: '',
        taskStatus: ''
      },

      page: {
        pageSizes: [10, 50, 100, 300, 500],
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 300 // 每页显示多少条
      },

      taskForm: {
        checkResult: '',
        checkMessage: ''
      },
      rules: {
        checkResult: [{ required: true, message: '请选择审批意见', trigger: 'change' }]
      },
      infoLoading: false,
      infoContent: '',
      exportLoading: false
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    this.getDict();
  },
  mounted() {
    const currYear = dayjs().format('YYYY');
    this.searchFrom.year = currYear;
    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.tableLoading = true;
      const obj = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize
        },
        this.searchFrom
      );

      const res = await getTaskV2PageCheckedApi(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
      };
    },
    pageChange(obj) {
      this.page.currentPage = obj.currentPage;
      this.page.pageSize = obj.pageSize;
      this.getList();
    },
    mahNameChange(e) {
      if (e) {
        console.log('e', e);

        const curr = this.drugListArr[e];
        this.currDrugList = curr;
        this.drugDisabled = false;
      } else {
        this.searchFrom.skuId = '';
        this.currDrugList = [];
        this.drugDisabled = true;
      }
    },

    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'
      );
    },
    async show(item) {
      this.infoLoading = true;
      const res = await getTaskV2CheckHisApi({ taskId: item.taskId });
      if (res.data.code === 0 && res.data.data.length > 0) {
        let str = '';
        res.data.data.forEach((item) => {
          str += `<span style='font-weight:700'>审核人：</span>${item.checker}；<span style="font-weight:700">审核时间：</span>${
            item.checkTime
          }；<span style="font-weight:700">审核状态：</span>${item.checkResult}<span style="font-weight:700">；审核原因：</span>${item.checkMessage ?? ''}<br>`;
        });
        this.infoContent = str;
      }
      this.infoLoading = false;
    },
    hide() {
      this.infoContent = '';
      this.infoLoading = false;
    },
    async exportBtnFn() {
      if (!this.searchFrom.year || !this.searchFrom.quarter) {
        return this.$message.error('请选择年和季度');
      }

      try {
        this.exportLoading = true;
        const obj = {
          year: this.searchFrom.year,
          quarter: this.searchFrom.quarter
        };
        const res = await pkgCheckExportApi(obj);
        let url = window.URL.createObjectURL(new Blob([res.data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '执行包审核明细信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.exportLoading = false;
      } catch (err) {
        this.exportLoading = false;
      }
    }
  }
};
</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 {
  height: 1200px;
}
.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-tips {
  margin-bottom: 5px;
  font-size: 16px;
  color: rgb(233 77 77);
  text-align: center;
  font-weight: 600;
}

.info-list {
  margin-bottom: 10px;
  li {
    list-style: none;
  }
}
.check-detail {
  font-size: 12px;
  color: #6e6e6e;
  cursor: pointer;
}
.table-btns {
  margin: 10px 0;
}
</style>
