<template>
  <basic-container>
    <Card class="cardTitle">
      <p>
        <el-button type="primary" @click="backPage" style="width: 80px; margin-left: 25px">返回</el-button>
        <el-tooltip class="item" effect="dark" content="请在批量审核前务必已查看各个服务详情，并确认服务完成情况符合服务要求。" placement="top" v-if="showBtn == 'approval'">
          <el-button type="primary" @click="moreApproval" style=" width: 80px">批量审批</el-button>
        </el-tooltip>

        <el-button v-if="showBtn == 'approval'" type="primary" @click="exportWord" style="width: 100px; float:right; margin-left: 20px;">导出</el-button>

        <!-- v-if="showBtn == 'approval'" -->
        <el-button v-if="showBtn == 'approval'" type="primary" @click="quickAuditClick" style="float:right;">快捷审核模式</el-button>
      </p>
    </Card>

    <avue-crud
      :data="tableData"
      :option="option"
      :page.sync="page"
      :table-loading="tableLoading"
      @on-load="getList"
      @size-change="sizeChange"
      @current-change="currentChange"
      @selection-change="selectionChange"
      @search-change="searchVal"
      @search-reset="searchReset"
      style="width:100%"
    >
      <template slot="menu" slot-scope="scope">
        <!-- :disabled="scope.row.reportApprovalOpinion != null" -->
        <el-button type="text" size="small" icon="el-icon-tickets" v-if="getShowBtn(scope.row)" @click="approvalBtn(scope.row.id, scope.row)">审批 </el-button>

        <el-button type="text" size="small" icon="el-icon-tickets" @click="showTaskInfo(scope.row, scope.index)">服务详情 </el-button>
      </template>
      <template slot="taskStatus" slot-scope="scope">
        <div style="line-height: 16px;">
          <span>{{ getTaskStatusVal(scope.row.taskStatus) }}</span>
          <el-tooltip
            class="item"
            effect="dark"
            :content="'拒绝原因：' + (scope.row.reportApprovalInfo || (scope.row.checkState && scope.row.checkState.checkMsg) || '无')"
            placement="top-start"
          >
            <i v-if="scope.row.taskStatus === '4'" class="el-icon-question f16 ml2"></i>
          </el-tooltip>
        </div>
      </template>
      <template slot="tip">
        <span class="ml20"
          >总服务积分：<span class="fwb f16">{{ totalScore }}</span></span
        >
      </template>
      <template slot="taskTypeIdSearch">
        <el-select v-model="taskTypeId" placeholder="服务类型">
          <el-option :label="item.taskTypeName" :value="item.id" v-for="item in taskList" :key="item.id"></el-option>
        </el-select>
      </template>
      <template slot="taskTypeId" slot-scope="scope">
        {{ getName && getName(scope.row) }}
      </template>
    </avue-crud>

    <el-dialog :title="showTitle" :visible.sync="showDig" top="12vh" width="40%" center :before-close="handleClose" class="review-dialog">
      <el-form :model="approvalLookform" :rules="rules" ref="approvalLookform" label-width="100px" class="demo-ruleForm">
        <div v-show="oneData">
          <p v-if="atypismData.length" class="teskDetailsty">不一致信息</p>
          <el-table v-if="atypismData.length" :data="atypismData" border style="width: 100%; margin-bottom:20px;">
            <el-table-column prop="name" label="信息项" width="180" align="center"> </el-table-column>
            <el-table-column prop="oldData" label="系统数据" width="180" align="center"> </el-table-column>
            <el-table-column prop="newData" label="调研数据" align="center"> </el-table-column>
          </el-table>
          <p class="missionSty">服务详情</p>
          <!--         <p class="missionContsty">-->
          <!--           <iframe class="iframe" :src="taskDetail" width="100%" height="100%" scrolling="auto" frameborder="0" />-->
          <!--         </p>-->
          <div v-if="oneData && showDig">
            <task-detail :id="singleVal" @getSurveyTaskInfoById="getSurveyTaskInfoById" />
          </div>
        </div>

        <p class="missionSty">审批意见</p>
        <el-form-item label="审批意见：" prop="resource">
          <el-radio-group v-model="approvalLookform.resource">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          label="说明："
          prop="explain"
          :rules="[
            {
              required: approvalLookform.resource == 1 ? false : true,
              message: '请输入审批说明',
              trigger: 'blur'
            }
          ]"
        >
          <el-input type="textarea" v-model="approvalLookform.explain"></el-input>
        </el-form-item>
        <refuseReason v-if="approvalLookform.resource === '2' && oneData" @selectRefuseReason="selectRefuseReason" />
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('approvalLookform')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导出弹窗 -->
    <el-dialog title="导出" :visible.sync="exportDig" width="30%" :close-on-click-modal="false" center>
      <template>
        <div class="down-item">
          <span>word格式：</span>
          <template v-if="wordStatus && wordStatus.status === 'NOT_GENERATE'">
            <el-button class="first" @click="taskExport('word')" :loading="wordLoading">生成报告</el-button>
          </template>
          <template v-else-if="wordStatus && wordStatus.status === 'GENERATING'">
            <el-button class="first" :loading="true">报告生成中...</el-button>
          </template>
          <template v-else-if="wordStatus && (wordStatus.status === 'GENERATED' || wordStatus.status === 'ERROR')">
            <el-button @click="taskExport('word')">重新导出</el-button>
            <el-button @click="downloadTask('word')" v-if="wordStatus.status === 'GENERATED'">下载报告</el-button>
            <el-button disabled :title="wordStatus.errorMsg" v-else-if="wordStatus.status === 'ERROR'">导出失败</el-button>
          </template>
          <div class="title-msg">
            <p v-if="wordStatus && wordStatus.status === 'GENERATED'">下载截止日期：{{ wordStatus.ttl }}</p>
            <p v-if="wordStatus && wordStatus.status === 'ERROR'">本次导出失败：{{ wordStatus.errorMsg }}</p>
          </div>
        </div>
        <div class="down-item">
          <span>excel格式：</span>
          <template v-if="excelStatus && excelStatus.status === 'NOT_GENERATE'">
            <el-button class="first" @click="taskExport('excel')" :loading="excelLoading">生成报告</el-button>
          </template>
          <template v-if="excelStatus && excelStatus.status === 'GENERATING'">
            <el-button class="first" :loading="true">报告生成中...</el-button>
          </template>
          <template v-else-if="excelStatus && (excelStatus.status === 'GENERATED' || excelStatus.status === 'ERROR')">
            <el-button @click="taskExport('excel')">重新导出</el-button>
            <el-button @click="downloadTask('excel')" v-if="excelStatus.status === 'GENERATED'">下载报告</el-button>
            <el-button disabled :title="excelStatus.errorMsg" v-else-if="excelStatus.status === 'ERROR'">导出失败</el-button>
          </template>
          <div class="title-msg">
            <p v-if="excelStatus && excelStatus.status === 'GENERATED'">下载截止日期：{{ excelStatus.ttl }}</p>
            <p v-if="excelStatus && excelStatus.status === 'ERROR'">本次导出失败：{{ excelStatus.errorMsg }}</p>
          </div>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        注意： 1.报告将于24小时之内生成完毕，请注意下载。<br />
        <i style="margin-left:62px"></i>2.报告汇总为封面+服务数据汇总+服务列表明细。
        <br />
        <i style="margin-left:10px"></i>3.报告详情为每条服务的服务详情+图片。
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import {teskReportapprovalLookdata} from '@/const/crud/teskReportapproval';
import {getTaskListPage, approvalReport, reviewTask, nodeHistoryCreateApi} from '@/api/taskManagement/teskReportapproval';
import {approvalTask} from '@/api/assignPoints/currency/taskAudit';
import Config from '@/settings';
import taskDetail from '@/components/taskDetail';
import taskApi from '@/api/taskDetail/task';
import refuseReason from '@/components/refuseReason';
import {getDictType} from '@/api/common';
import {mapGetters} from 'vuex';

export default {
  name: 'teskReportapprovalLook',
  components: {
    taskDetail,
    refuseReason
  },
  data() {
    return {
      form: {},
      taskList: [],
      taskTypeId: '',
      showBtn: '',
      isApprovalPage: 1, // 1审批 0查看
      showData: '',
      tableLoading: false,
      tableData: [],
      option: teskReportapprovalLookdata,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      approvalLookform: {
        resource: '',
        explain: ''
      },
      rules: {
        resource: [{required: true, message: '请选择审批意见', trigger: 'change'}]
      },

      showTitle: '',
      showDig: false,
      oneData: false,
      searchForm: {},
      singleVal: '',
      packageIds: '',
      taskDetail: '',
      moreDisabled: false,
      selectionVal: [],
      atypismData: [],
      selection: [],
      exportDig: false,
      wordStatus: {},
      excelStatus: {},
      wordLoading: false,
      excelLoading: false,
      task_status_dict: [],
      currentRow: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'roles']),
    totalScore() {
      return this.selection.reduce((pre, cur) => {
        return pre + (cur.score || 0);
      }, 0);
    },
    getTaskStatusVal() {
      return taskStatusId => {
        taskStatusId = String(taskStatusId).trim();
        const curr = this.task_status_dict.find(ele => ele.value === taskStatusId);
        if (curr) return curr.label;
      };
    }
  },
  mounted() {
    console.log('userInfo', this.userInfo);
  },
  created() {
    this.showBtn = this.$route.query.type;
    this.isApprovalPage = this.$route.query.type === 'approval' ? 1 : 0;
    this.getTakList();
    this.getStatus();
    this.getTaskStatusDict();
  },
  methods: {
    getShowBtn(row) {
      let flag = false;
      // 当是审核的时候
      if (this.showBtn === 'approval') {
        // 当checkState的roleId是当前角色id说明可以审核
        if (this.userInfo.roles.includes(row.checkState.roleId)) {
          flag = true;
        }
        // 市场管理员与商务管理员并且roleId为-1的时候展示
        if ((this.userInfo.roles.includes(40) || this.userInfo.roles.includes(42)) && row.checkState.roleId == -1) {
          flag = true;
        }
        if (this.userInfo.roles.includes(39) && row.checkState.nextNodeId == -1) {
          flag = false;
        }
      }
      return flag;
    },
    getTaskStatusDict() {
      getDictType({type: 'task_status'}).then(res => {
        this.task_status_dict = res.data.data;
      });
    },
    selectRefuseReason(refuseReason) {
      this.$set(this.approvalLookform, 'explain', refuseReason);
    },
    getStatus() {
      taskApi.wordNBStatus(this.$route.query.id).then(res => {
        this.wordStatus = res.data.data;
      });
      taskApi.excelNBStatus(this.$route.query.id).then(res => {
        this.excelStatus = res.data.data;
      });
    },
    exportWord() {
      this.exportDig = true;
    },
    async taskExport(type) {
      if (type === 'word') {
        this.wordLoading = true;
        let res = await taskApi.wordNBReport(this.$route.query.id, this.$route.query.scoreId);
        if (res.data.code != 0) {
          this.$message.error('导出失败');
          return false;
        }
        this.$message.success(res.data.data);
        this.exportDig = false;
        this.getStatus();
        this.wordLoading = false;
      }
      if (type === 'excel') {
        this.excelLoading = true;
        let res = await taskApi.excelNBReport(this.$route.query.id, this.$route.query.scoreId);
        if (res.data.code != 0) {
          this.$message.error('导出失败');
          return false;
        }
        this.$message.success(res.data.data);
        this.exportDig = false;
        this.getStatus();
        this.excelLoading = false;
      }
    },
    downloadTask(type) {
      let latestUrl;
      if (type === 'word') {
        latestUrl = this.wordStatus.latestUrl;
      } else if (type === 'excel') {
        latestUrl = this.excelStatus.latestUrl;
      }
      let a = document.createElement('a');
      a.href = latestUrl;
      a.click();
      this.$message.success('导出汇总报告成功');
      this.exportDig = false;
    },
    quickAuditClick() {
      let id = this.$route.query.id;
      this.$router.push({
        path: '/admin/assignPoints/quota/quickAudit?id=' + id + '&type=2'
      });
    },
    async getTakList() {
      const res = await taskApi.getTaskList(this.$route.query.id, this.$route.query.type === 'approval' ? 1 : 0);
      this.taskList = res.data.data;
      console.log('res', this.taskList);
    },
    getName(row) {
      let id = row.taskTypeId;
      let curr = this.taskList.find(item => item.id == id);
      if (curr) return curr.taskTypeName;
    },
    searchVal(form, done) {
      this.searchForm.taskTypeId = this.taskTypeId;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    searchReset() {
      this.taskTypeId = '';
    },
    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      let obj = Object.assign(
        {
          isApprovalPage: this.isApprovalPage,
          id: this.$route.query.id,
          current: page.currentPage,
          size: page.pageSize
        },
        params,
        this.searchForm
      );
      console.log('obj', obj);

      getTaskListPage(obj)
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 单条审批
    approvalBtn(row, data) {
      this.currentRow = data;
      this.singleVal = row;
      this.showTitle = '审批';
      this.showDig = true;
      this.oneData = true;
      this.taskDetail = Config.outsideUrl + '/h5/#/pages/task/task-detail/index?id=' + row;
    },
    reviewBtn(row, index) {
      this.singleVal = row;
      this.showTitle = '审批';
      this.showDig = true;
      this.oneData = true;
    },

    // 批量审批按钮
    moreApproval() {
      if (this.selectionVal.length == 0) {
        this.$message.error('请选择需要审批的列');
        return false;
      } else {
        this.showTitle = '批量审批';
        this.showDig = true;
        this.oneData = false;
      }
    },

    // 返回按钮
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.push({path: '/admin/taskManagement/teskReportapproval'});
    },

    // 分页查询
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },

    // 确定按钮
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.showBtn == 'approval') {
            let id = '';
            if (this.showTitle === '审批') {
              id = this.singleVal;
            } else {
              (id = this.packageIds), (this.currentRow = this.tableData[0]);
            }

            let res;
            const obj = {
              id: this.$route.query.id,
              taskIds: id,
              approvalOpinion: this.approvalLookform.resource,
              approvalInfo: this.approvalLookform.explain,
              taskStatusInfo: this.approvalLookform.explain,
              nodeId: this.currentRow.checkState.nextNodeId
            };
            if (this.userInfo.roles.includes(42)) {
              obj.nodeId = 8;
            }
            // 40 商务组
            if (this.userInfo.roles.includes(40)) {
              obj.nodeId = 9;
            }
            res = await approvalReport(obj);
            if (res.data.code === 0) {
              this.getList(this.page);
              this.showDig = false;
              this.tableLoading = false;
              this.$message.success('审批成功');
              this.approvalLookform.resource = '';
            }
            this.handleClose();
          }

          return;

          // 当审核方式通过 并且不是当前审核id不是39  审核提交走 nodeHistoryCreateApi 接口
          if (this.approvalLookform.resource == 1 && !this.userInfo.roles.includes(39)) {
            const obj = {
              id: this.singleVal,
              approvalOpinion: this.approvalLookform.resource,
              taskStatusInfo: this.approvalLookform.explain,
              nodeId: this.currentRow.checkState.nextNodeId
            };
            // 针对市场组和商务组做特殊处理
            //   市场组

            res = await nodeHistoryCreateApi(obj);
          } else {
            // let args = {
            //   id: this.$route.query.id,
            //   taskIds: this.packageIds,
            //   approvalOpinion: this.approvalLookform.resource,
            //   approvalInfo: this.approvalLookform.explain
            // };
            // 拒绝接口 approvalReport
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 多选
    selectionChange(selection, row) {
      this.selection = selection;
      this.selectionVal = selection;
      this.packageIds = '';

      if (undefined != selection) {
        for (var i = 0; i < selection.length; i++) {
          // if(selection[i].reportApprovalOpinion != null){
          //   return false;
          // }else{
          //   return true;
          // }
          this.packageIds += selection[i].id;
          if (i < selection.length - 1) {
            this.packageIds += ',';
          }
        }
      }
    },
    // 弹窗取消
    cancelBtn() {
      this.showDig = false;
    },
    handleClose() {
      this.$refs.approvalLookform.resetFields();
      this.showDig = false;
      this.atypismData = [];
    },

    // 服务详情
    showTaskInfo(row, index) {
      window.open(
        Config.outsideUrl + '/h5/#/pages/task/task-detail/index?id=' + row.id,
        'newwindow',
        'height=500, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no'
      );
    },
    // 获取不一致信息
    getSurveyTaskInfoById(id) {
      taskApi.getSurveyTaskInfoById(id).then(res => {
        this.atypismData = res.data.data.compareList;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.review-dialog {
  ::v-deep .el-dialog__body {
    padding: 0 25px 0;
  }
}
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    width: 80px;
    display: inline-block;
    text-align: right;
  }
  .first {
    width: 240px;
  }
}
</style>

<style>
.missionSty {
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #d7d6d5;
  margin-bottom: 10px;
}
.missionContsty {
  height: 350px;
  margin-bottom: 10px;
  border: 1px solid red;
}
.cardTitle {
  margin-bottom: 15px;
}
</style>
