<template>
  <basic-container>
    <avue-crud
      ref="crud"
      :page="page"
      :data="tableData"
      :search.sync="searchForm"
      v-model="form"
      :table-loading="tableLoading"
      :option="tableOption"
      @on-load="getList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @selection-change="selectionChange"
    >
      <!-- 左侧添加按钮 -->
      <template slot="menuLeft">
        <template v-if="isYQGLY">
          <el-button type="primary" size="small" @click="addBtn">新 增</el-button>
          <el-button type="primary" size="small" @click="importBtn">批量创建</el-button>
          <el-button type="primary" size="small" @click="downFile">导出服务计划</el-button>
          <el-button type="primary" size="small" @click="allReviewPlanFn">批量审核服务计划</el-button>
        </template>
        <template v-if="showReviefFlag">
          <el-button type="primary" size="small" @click="downDetailFile">导出拆解详情</el-button>
          <el-button type="primary" size="small" @click="allReviewFn">批量拆解审核</el-button>
        </template>
        <!-- 营销中心批量审核  -->
        <template v-if="isYXZX">
          <el-button type="primary" size="small" @click="YXZX_AllReviewFn">批量审核</el-button>
        </template>
      </template>
      <!-- 操作栏 -->
      <template slot="menu" slot-scope="scope">
        <!-- 展示审批节点 -->
        <template>
          <el-button type="text" size="small" @click="approvalFlowchartFn(scope.row)">审核节点 </el-button>
        </template>
        <!-- 营销中心审核 -->
        <template v-if="isYXZX">
          <el-button type="text" size="small" @click="reviewFn(scope.row)" v-if="scope.row.planState === 'INIT' && scope.row.parentId == 0">审核 </el-button>
        </template>
        <!-- 药企管理员下的操作 -->
        <template v-if="isYQGLY">
          <el-button type="text" v-if="scope.row.planState === 'INIT' && scope.row.parentId != 0" @click="reviewFn(scope.row)">
            分发审核
          </el-button>
        </template>
        <!-- 一级cso 分发  -->
        <template v-else-if="isDLSGLY">
          <el-button type="text" size="small" v-if="scope.row.parentId == 0 && scope.row.availScore > 0" @click="distributeFn(scope.row)">分发 </el-button>
          <el-button v-if="scope.row.planDetails && !scope.row.planDetails.cktRes1" type="text" size="small" @click="dismantleReviewFn(scope.row)">拆解审核 </el-button>
        </template>
        <!-- 商务组 -->
        <template v-if="isSWZ">
          <!-- 有拆解计划并且一级审核通过 平台可以审核 -->
          <el-button v-if="scope.row.planDetails && scope.row.planDetails.cktRes1 && !scope.row.planDetails.cktRes2" type="text" size="small" @click="dismantleReviewFn(scope.row)"
            >拆解审核
          </el-button>
        </template>
        <!-- 事业部分管领导 -->
        <template v-if="isSYB">
          <!-- 有拆解计划并且一级审核通过 二级审核 事业部可以审核 -->
          <el-button
            v-if="scope.row.planDetails && scope.row.planDetails.cktRes1 && scope.row.planDetails.cktRes2 && !scope.row.planDetails.cktRes3"
            type="text"
            size="small"
            @click="dismantleReviewFn(scope.row)"
            >拆解审核
          </el-button>
        </template>
        <!-- 平台管理员 -->
        <template v-else-if="isROLE_SERVICE">
          <el-button v-if="!scope.row.planDetails || scope.row.planDetails.detailsState === 'REJECTED'" type="text" size="small" @click="dismantleFn(scope.row)">拆解 </el-button>
        </template>
        <!-- 数据统计 -->
        <el-button v-if="scope.row.planDetails" type="text" size="small" @click="statisticsFn(scope.row)">
          数据统计
        </el-button>
        <!-- 编辑按钮操作 -->
        <template>
          <!-- 服务商管理员 -->
          <template v-if="isYQGLY && scope.row.parentId == '0'">
            <el-button :disabled="editDisabled(scope.row)" type="text" size="small" @click="editFn(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="archivePlan(scope.row)">终止</el-button>
          </template>
          <template v-if="isDLSGLY && scope.row.parentId != '0'">
            <el-button :disabled="editDisabled(scope.row)" type="text" size="small" @click="editFn(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="archivePlan(scope.row)">终止</el-button>
          </template>
        </template>
      </template>
      <!-- 日期搜索 -->
      <template slot="periodSearch">
        <el-date-picker
          @change="monthrangeChange"
          type="monthrange"
          value-format="timestamp"
          class="w100"
          v-model="monthrangeValue"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
        >
        </el-date-picker>
      </template>
      <!-- 日期搜索 -->
      <template slot="createTimeSearch">
        <el-date-picker
          type="monthrange"
          value-format="timestamp"
          class="w100"
          v-model="createTimeValue"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
        >
        </el-date-picker>
      </template>
    </avue-crud>
    <!-- 新增编辑 -->
    <serviceTargetDistributionDialog ref="dialogRef" @updateList="updateList" />
    <!-- 审核流程展示 -->
    <approvalFlowchartDialog ref="approvalFlowchartDialogRef" />

    <!-- 批量上传 -->
    <el-dialog :title="importType == 'import' ? '批量导入' : '批量审核'" :visible.sync="importDialogVisible" width="60%" :before-close="importClose" center>
      <div class="import-content" v-loading="importLoading">
        <el-upload
          :action="uploadUrl"
          :headers="headers"
          :before-upload="beforeFileUpload"
          :limit="1"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :on-error="handleError"
          accept=".xls,.xlsx"
          :show-file-list="false"
          :on-success="handleSuccess"
          :file-list="fileList"
        >
          <el-button size="small" type="primary">{{ importType == 'import' ? '导入计划' : '批量审核' }}（*.xlsx,*.xls）</el-button>
        </el-upload>
        <el-button v-if="importType === 'import'" type="text" @click="dowmTemplateFn">下载模板</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 导入存在失败 -->
    <el-dialog title="上传失败" width="60%" :close-on-click-modal="false" @close="importErrorDialogShow = false" :visible.sync="importErrorDialogShow" center>
      <div>
        <el-table :data="importErrorTableData" border style="width: 100%">
          <el-table-column prop="idx" label="行号" width="180" />
          <el-table-column prop="errorMsg" label="错误信息" />
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importErrorDialogShow = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="批量审核" width="60%" :close-on-click-modal="false" @close="handleClose" :visible.sync="YXZX_AllReviewDialogShow" center>
      <el-form :model="YXZX_AllReviewForm" :rules="rules" ref="YXZX_AllReviewForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="审批意见:" prop="result" class="formitem-box">
          <el-radio-group v-model="YXZX_AllReviewForm.result">
            <el-radio label="0">通过</el-radio>
            <el-radio label="1">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="意见说明:"
          prop="msg"
          class="formitem-box"
          :rules="[
            {
              required: YXZX_AllReviewForm.result === '1',
              message: '请输入审批说明',
              trigger: 'blur'
            }
          ]"
        >
          <el-input type="textarea" v-model="YXZX_AllReviewForm.msg"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关 闭</el-button>
        <el-button type="primary" @click="YXZX_AllReviewSubmit">提 交</el-button>
      </span>
    </el-dialog>
    <!-- 终止弹窗 -->
    <el-dialog title="终止" :visible.sync="archivePlanDialogVisible" width="60%" center :before-close="archivePlanHandleClose">
      <div class="archive-plan">
        <div class="message">
          请注意：终止操作将按照“归档”方式进行处理，整个业务处理过程，涉及：服务计划、服务计划详情、服务计划拆解、服务执行包、服务执行包兑付通知、服务执行包承接、服务执行包分配数量、服务记录、服务内容、服务审批节点记录、服务监督、服务监督意见等数据。
          <span>且一旦终止数据无法恢复。请认真核实，慎重操作！</span>
        </div>
        <div class="archive-plan-name">拟终止服务目标：{{ archivePlanRow.planName }}</div>
        <el-form :model="archivePlanDialogForm" :rules="archivePlanRules" ref="archivePlanDialogForm" label-width="180px">
          <el-form-item label="确认终止服务目标名称" prop="confirmPlanName">
            <el-input v-model="archivePlanDialogForm.confirmPlanName"></el-input>
          </el-form-item>
          <el-form-item label="终止说明" prop="archiveReason">
            <el-input type="textarea" v-model="archivePlanDialogForm.archiveReason"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="archivePlanHandleClose">取 消</el-button>
        <el-button type="primary" @click="archivePlanHandleConfrim">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 营销中心批量审核 -->
  </basic-container>
</template>

<script>
import store from '@/store';
import dayjs from 'dayjs';
import {mapGetters} from 'vuex';
import {tableOption} from '@/const/crud/serviceTargetDistribution.js';
import serviceTargetDistributionDialog from './components/serviceTargetDistributionDialog';
import approvalFlowchartDialog from './components/approvalFlowchartDialog';
import {fetchList, planInfoExport, plandetailsExport, planCheckBatchApi, archivePlanApi} from '@/api/wmdeptbudget/plan.js';
import {templateDownload} from '@/api/assignPoints/currency/manList';

export default {
  components: {serviceTargetDistributionDialog, approvalFlowchartDialog},
  data() {
    return {
      headers: {
        Authorization: 'Bearer ' + store.getters.access_token
      },
      importType: '',
      fileList: [],
      uploadUrl: '/admin/plan/batch/create',
      importLoading: false,
      importErrorDialogShow: false,
      importErrorTableData: [],
      fileTypeLimit: [
        // excel
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ], // 支持上传的文件类型
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 100
      },
      importDialogVisible: false,
      monthrangeValue: [],
      createTimeValue: [],
      searchForm: {
        period: [],
        createTime: []
      },
      form: {},
      tableData: [],
      tableLoading: false,
      tableOption: tableOption,
      isYQGLY: false, // 药企管理员
      isSWZ: false,
      isDLSGLY: false, //一级cso
      isROLE_SERVICE: false, // 二级cso
      isYXZX: false,
      isSYB: false,
      showReviefFlag: false,
      selectionPlanIds: [],
      YXZX_AllReviewDialogShow: false,
      YXZX_AllReviewForm: {
        result: '',
        msg: ''
      },
      rules: {
        result: [{required: true, message: '请选择审批意见', trigger: 'change'}]
      },
      archivePlanDialogVisible: false,
      archivePlanDialogForm: {
        planId: '',
        confirmPlanName: '',
        archiveReason: ''
      },
      archivePlanRules: {
        confirmPlanName: [{required: true, message: '请填写终止计划名称', trigger: 'blur'}],
        archiveReason: [{required: true, message: '请填写终止说明', trigger: 'blur'}]
      },
      archivePlanRow: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    const roles = this.userInfo.roles;
    // 拆解审核角色

    if (roles.includes(4) || roles.includes(40) || roles.includes(41)) {
      this.showReviefFlag = true;
    }

    // 营销中心
    if (roles.includes(38)) {
      this.isYXZX = true;
      this.$set(this.tableOption, 'selection', true);
    }
    // 是药企管理员
    if (roles.includes(3)) {
      this.isYQGLY = true;
    }
    // 一级cso | 区域管理员
    if (roles.includes(4)) {
      this.isDLSGLY = true;
    }
    // 一级cso | 区域管理员
    if (roles.includes(37)) {
      this.isROLE_SERVICE = true;
    }

    // 商务组
    if (roles.includes(40)) {
      this.isSWZ = true;
    }

    // 事业部门
    if (roles.includes(41)) {
      this.isSYB = true;
    }
  },
  methods: {
    addBtn() {
      this.$refs.dialogRef.addBtn();
    },
    YXZX_AllReviewFn() {
      if (!this.selectionPlanIds.length) {
        return this.$message.info('请先选择待审核数据');
      } else {
        this.YXZX_AllReviewDialogShow = true;
      }
    },
    selectionChange(selection) {
      this.selectionPlanIds = selection.map(item => item.planId);
    },
    YXZX_AllReviewSubmit() {
      this.$refs.YXZX_AllReviewForm.validate(async valid => {
        if (valid) {
          const obj = {
            planIds: this.selectionPlanIds,
            result: this.YXZX_AllReviewForm.result == '0' ? true : false,
            msg: this.YXZX_AllReviewForm.msg
          };
          const res = await planCheckBatchApi(obj);
          if (res.data.data) {
            this.$message.success('审核提交成功');
            this.getList(this.page);
            this.handleClose();
          }
        }
      });
    },
    handleClose() {
      this.YXZX_AllReviewForm = {
        result: '',
        msg: ''
      };
      this.$refs.YXZX_AllReviewForm.resetFields();
      this.YXZX_AllReviewDialogShow = false;
    },
    dowmTemplateFn() {
      this.importLoading = true;
      templateDownload({
        fileName: 'impl_plan_batch_create_tmpl.xlsx'
      })
        .then(response => {
          this.importLoading = false;
          let url = window.URL.createObjectURL(new Blob([response.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);
        })
        .catch(() => {
          this.importLoading = false;
        });
    },
    beforeFileUpload(file) {
      this.importLoading = true;
      if (!this.fileTypeLimit.includes(file.type)) {
        this.$message.warning('不支持的文件格式');
        return false;
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning('最多上传一个文件');
    },
    handleError(err) {
      this.$message.error('上传失败！');
      this.importLoading = false;
    },
    importClose() {
      this.fileList = [];
      this.importDialogVisible = false;
    },
    handleRemove(file, fileList) {},

    handleSuccess(res, file, fileList) {
      this.fileList = [];
      this.importLoading = false;
      if (res.code == 0) {
        if (res.data.length == 0) {
          this.$message.success('上传成功！');
          this.importClose();
          this.getList(this.page);
        } else {
          this.importErrorTableData = res.data;
          this.importErrorDialogShow = true;
        }
      }
    },

    importBtn() {
      this.uploadUrl = '/admin/plan/batch/create';
      this.importType = 'import';
      this.importDialogVisible = true;
    },
    async downFile() {
      const obj = Object.assign(
        {
          current: this.page.currentPage,
          size: this.page.pageSize
        },
        this.searchForm
      );
      const res = await planInfoExport(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);
    },
    async downDetailFile() {
      const res = await plandetailsExport();
      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);
    },

    allReviewFn() {
      this.uploadUrl = '/admin/plan/details/check/batch';
      this.importType = 'detailsCheck';
      this.importDialogVisible = true;
    },
    allReviewPlanFn() {
      this.uploadUrl = '/admin/plan/info/check/batch';
      this.importType = 'detailsCheck';
      this.importDialogVisible = true;
    },
    async getList(page, params) {
      this.tableLoading = true;
      const obj = Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize
        },
        params,
        this.searchForm
      );

      const res = await fetchList(obj);
      res.data.data.records.forEach((item, index) => {
        if (item.consigneeInfo) {
          item.consigneeName = item.consigneeInfo.consigneeName;
        }
        item.index = index + 1;
        if (item.children) {
          item.children.forEach((iten, indey) => {
            if (iten.consigneeInfo) {
              iten.consigneeName = iten.consigneeInfo.consigneeName;
            }
            iten.index = item.index + '-' + (indey + 1);
          });
        }
      });
      this.tableData = res.data.data.records;
      this.page.total = res.data.data.total;
      this.tableLoading = false;
    },
    updateList() {
      this.getList(this.page);
    },
    monthrangeChange(e) {
      console.log('e', e);

      if (e.length) {
        this.form.planIssue = dayjs(e[0]).format('YYYY-MM-DD');
        this.form.planExpiry = dayjs(e[1]).format('YYYY-MM-DD');
      }
    },
    createTimemonthrangeChange(e) {
      if (e.length) {
        this.form.planIssue = dayjs(e[0]).format('YYYY-MM-DD');
        this.form.planExpiry = dayjs(e[1]).format('YYYY-MM-DD');
      }
    },
    // 展示审批流程图
    approvalFlowchartFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.approvalFlowchartDialogRef.showDialog(info);
    },
    // 审核
    reviewFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.dialogRef.reviewFn(info, '0');
    },
    // 分发
    distributeFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.dialogRef.distributeFn(info, '0');
    },
    dismantleFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.dialogRef.dismantleFn(info, '0');
    },
    // 拆解审核
    dismantleReviewFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      // 区域审核服务供应商数据
      this.$refs.dialogRef.dismantleReviewFn(info, '0');
    },
    // 数据统计
    statisticsFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.dialogRef.statisticsFn(info);
    },
    // 判断编辑状态
    editDisabled(row) {
      // 下发的一级包状态
      if (row.parentId == 0) {
        if (row.planType === 'ANN') {
          let flag = row.planState === 'INIT' || row.planState === 'REJECTED';
          return !flag;
        } else if (row.planType === 'QRT') {
          let flag = row.children && row.children.length > 0;
          return flag;
        }
      } else {
        let flag = row.planState === 'INIT' || row.planState === 'REJECTED';
        return !flag;
      }
    },
    // 编辑按钮
    editFn(row) {
      const info = JSON.parse(JSON.stringify(row));
      this.$refs.dialogRef.editFn(info, 0);
    },
    // 终止
    archivePlan(row) {
      console.log('archivePlan', row);
      this.archivePlanRow = row;
      this.archivePlanDialogForm.planId = row.id;
      this.archivePlanDialogVisible = true;
    },
    archivePlanHandleConfrim() {
      this.$refs.archivePlanDialogForm.validate(async valid => {
        if (valid) {
          const res = await archivePlanApi(this.archivePlanDialogForm);
          if (res.data.code === 0) {
            this.$message.success('终止成功！');
            this.archivePlanHandleClose();
            this.refreshChange();
          }
        }
      });
    },
    archivePlanHandleClose() {
      console.log('archivePlanHandleClose');
      this.archivePlanDialogForm = {
        confirmPlanName: '',
        planId: '',
        archiveReason: ''
      };
      this.archivePlanDialogVisible = false;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchReset() {
      this.monthrangeValue = [];
      this.createTimeValue = [];
    },
    searchChange(form, done) {
      this.searchForm = form;
      if (this.monthrangeValue && this.monthrangeValue.length) {
        const arr = [dayjs(this.monthrangeValue[0]).format('YYYY-MM-DD'), dayjs(this.monthrangeValue[1]).format('YYYY-MM-DD')];
        this.searchForm.period = arr;
      } else {
        this.searchForm.period = [];
      }
      if (this.createTimeValue && this.createTimeValue.length) {
        const arr = [dayjs(this.createTimeValue[0]).format('YYYY-MM-DD HH:mm:ss'), dayjs(this.createTimeValue[1]).format('YYYY-MM-DD HH:mm:ss')];
        this.searchForm.createTime = arr;
      } else {
        this.searchForm.createTime = [];
      }
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    }
  }
};
</script>

<style lang="scss" scoped>
.import-content {
  text-align: center;
}
.archive-plan {
  .message {
    margin-bottom: 20px;
    border-radius: 10px;
    border: 1px solid #ccc;
    line-height: 35px;
    margin-left: 20px;
    padding: 10px 20px;
    color: #f56c6c;
    font-size: 16px;
    font-weight: 600;
    span {
      font-style: italic;
      font-weight: 800;
    }
  }
  .archive-plan-name {
    margin: 15px 30px;
    font-weight: 600;
    color: #000;
    font-size: 15px;
  }
}
</style>
