<template>
  <div class="app-container">
    <!-- 任务详情 -->
    <el-card>
      <div slot="header" class="clearfix">
        <span>任务详情</span>
      </div>
      <div style="margin-left: 10px; margin-right: 10px">
        <el-row :gutter="20">
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">任务类型：</span>
              <span class="desc" v-if="task.type==10">目标制定</span>
              <span class="desc" v-else>日常监督</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">年份：</span>
              <span class="desc"> {{ task.year }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">周期：</span>
              <span class="desc"> {{ cycleOptions[task.cycle] }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">截止日期：</span>
              <span class="desc"> {{ task.end_date }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">任务状态</span>
              <span class="desc">
                <el-tag
                  effect="plain"
                  v-if="task.state == 10"
                  type="warning"
                  >创建中
                </el-tag>
                <el-tag
                  effect="plain"
                  v-else-if="task.state == 20"
                  type="primary"
                  >执行中
                </el-tag>
                <el-tag effect="plain" v-else type="success">已关闭</el-tag>
              </span>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="margin-bottom: 6px">
              <span class="term">创建人：</span>
              <span class="desc">{{ task.create_by_name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <!-- 功能按钮 -->
            <div style="margin-top: 4px">
              <el-button
                type="primary"
                @click="startTask()"
                v-if="task.state != 30"
                size="small"
              >发布任务</el-button>
              <el-button
                type="primary"
                @click="append()"
                v-if="task.state ==10 || task.state == 20"
                size="small"
                >添加执行部门</el-button>
                <el-button
                type="primary"
                @click="handleExportAll()"
                v-loading="isSaving"
                size="small"
                >导出记录</el-button>
            </div>
          </el-col>
        </el-row>
        
      </div>
    </el-card>
    <!-- 执行组织 -->
    <el-card style="margin-top: 2px">
      <div slot="header" class="clearfix">
        <span>执行组织</span>
      </div>
      <el-table
        v-loading="listLoading"
        :data="taskdeptall"
        border
        fit
        stripe
        highlight-current-row
        max-height="300px"
        @row-click="clickRow"
      >
        <el-table-column label="序号" type="index" align="center" width="55" />
        <el-table-column label="公司名称">
          <template slot-scope="scope" v-if="scope.row.belong_dept_">
            <span style="color:darkblue">{{scope.row.belong_dept_.type_name}}</span>-
            {{scope.row.belong_dept_.name}}
          </template>
        </el-table-column>
         <el-table-column label="执行进度">
          <template slot-scope="scope">
            {{ scope.row.pross }}%
          </template>
        </el-table-column>
        <el-table-column label="是否完成">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.count_up<scope.row.count_all " type="danger" effect="plain">否</el-tag>
            <el-tag v-else effect="plain">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="240px"
          fixed="right"
        >
          <template slot-scope="scope">
            <!-- 
             <el-link
            v-if="
             scope.row.confirm_rate == 100  &&
                checkPermission(['task_update'])
              "
             type="primary"
              size="small"
              @click="handleConfirmFK(scope)"
              >反馈</el-link
            > -->
            <el-link
              type="primary"
              size="small"
              @click.stop="handleExport(scope.row)"
              >导出报表</el-link>
            <el-link
              v-if="
                checkPermission(['task2'])
              "
              type="danger"
              size="small"
              @click="handleDeleteDept(scope)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :visible.sync="dialogVisibles"    
      >
        <el-form
          ref="Forms"
          :model="Taskdept"
          label-width="80px"
          label-position="right"
        >
          <el-form-item label="反馈文件" prop="template" v-if="dialogVisibles">
            <el-upload
            ref="upload"
            :action="upUrl"
            :on-preview="handlePreview"
            :on-success="handleUpSuccess"
            :on-remove="handleRemove"
            :headers="upHeaders"
            :file-list="fileList"
            :limit="1"
            accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx"
          >
            <el-button size="small" type="primary">上传文件</el-button>
          </el-upload>
          </el-form-item>
        </el-form>
        <div style="text-align: right">
          <el-button type="danger" @click="dialogVisibles = false">取消</el-button>
          <el-button type="primary" @click="confirmfk('Forms')">确认</el-button>
        </div>
      </el-dialog>
    </el-card>
    <!-- 执行详情 -->
    <el-card style="margin-top: 2px" v-if="task.type==10">
      <div slot="header" class="clearfix">
        <span>执行详情</span>
      </div>
      <el-table
        v-loading="listLoading2"
        :data="recordList"
        border
        fit
        stripe
        highlight-current-row
        max-height="400px"
        style="margin-top:2px"
        id="tableGoal"
        @selection-change="handleSelectRecords"
      >
        <!-- <el-table-column type="selection" align="center" width="55" /> -->
        <el-table-column label="序号" type="index" align="center" width="55" />
        <el-table-column label="名称">
          <template slot-scope="scope">{{ scope.row.goal_name }}</template>
        </el-table-column>
        <el-table-column label="基础值">
          <template slot-scope="scope">{{ scope.row.goal_value_a }}</template>
        </el-table-column>
        <el-table-column label="目标值">
          <template slot-scope="scope">{{ scope.row.goal_value_b }}</template>
        </el-table-column>
        <el-table-column label="文件">
          <template slot-scope="scope" v-if="scope.row.goal_file_">
            <el-link :href="scope.row.goal_file_.path" target="_blank" type="primary">
            {{scope.row.goal_file_.name}}</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="margin-top: 2px" v-else>
      <el-card>
        <div>
          <span>执行详情</span>
        </div>
        <p>
          <el-col :span="4">
            <p>重大事故：{{ task2doItem.num_acc }} </p>
            <p>风险识别：{{ task2doItem.num_risk }} </p>
          </el-col>
          <el-col :span="4">
            <p>应发报告：{{ task2doItem.num_expect }} </p>
            <p>已发报告：{{ task2doItem.num_issue }} </p>
          </el-col>
          <el-col :span="4">
            <p>不准确报告：{{ task2doItem.num_error }} </p>
            <p>超期报告：{{ task2doItem.num_overdue }} </p>
          </el-col>
          <el-col :span="4">
            <p>能力验证结果：{{ task2doItem.num_pt }} </p>
            <p>验证结果满意：{{ task2doItem.num_pt_10 }} </p>
          </el-col>
          <el-col :span="4">
            <p>客户投诉：{{ task2doItem.num_complaint }} </p>
            <p>投诉结果满意：{{ task2doItem.num_complaint_10 }} </p>
          </el-col>
          <el-col :span="4">
            <p>外部监督检查：{{ task2doItem.num_oinspect }} </p>
          </el-col>
        </p>
        
      </el-card>
      <el-row :gutter="5">
        <el-col :span="12" style="margin-top: 5px;">
          <el-card >
              <div class="cardHead">
                <span class="cardTitle">不准确报告</span>
              </div>
              <el-table
                :data="rcList"
                fit
                stripe
                highlight-current-row
                height="250px"
                id="table1"
              >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="报告/证书编号" prop="number"></el-table-column>
                <el-table-column label="更改后报告/证书编号" prop="number_correct"></el-table-column>
                <el-table-column label="出错原因" prop="reason_error"></el-table-column>
                <el-table-column label="更改报告/证书发放日期" prop="date_issue"></el-table-column>
              </el-table>
            </el-card>
        </el-col>
        <el-col :span="12" style="margin-top: 5px;">
          <el-card>
              <div class="cardHead">
                <span class="cardTitle">超期报告</span>
              </div>
              <el-table
                  :data="rc2List.results"
                  fit
                  stripe
                  highlight-current-row
                  height="219px"
                  id="table2"
                >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="超期报告/证书编号" prop="number"></el-table-column>
                <el-table-column label="业务受理日期" prop="date_accept"></el-table-column>
                <el-table-column label="报告/证书应发日期" prop="date_expect"></el-table-column>
                <el-table-column label="报告/证书实际发放日期" prop="date_issue"></el-table-column>
              </el-table>
              <pagination
                  :total="rc2List.count"
                  :page-sizes="pageSizes"
                  :page.sync="rc2ListQuery.page"
                  :limit.sync="rc2ListQuery.page_size"
                  @pagination="getRc2List"
              />
          </el-card>
        </el-col>
        <el-col :span="12" style="margin-top: 5px;">
          <el-card>
             <div class="cardHead">
                <span class="cardTitle">能力验证结果</span>
              </div>
              <el-table
                  :data="ptList"
                  fit
                  stripe
                  highlight-current-row
                  height="250px"
                  id="table3"
                >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="能力验证名称" prop="name"></el-table-column>
                <el-table-column label="项目编号" prop="number"></el-table-column>
                <el-table-column label="组织方" prop="organizer"></el-table-column>
                <el-table-column label="参加参数名称" prop="params"></el-table-column>
                <el-table-column label="结果">
                  <template slot-scope="scope">
                      <span>{{ resultsOptions[scope.row.result] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="处理结果">
                  <template slot-scope="scope">
                      <span>{{ handleOptions[scope.row.handle_result] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="证书日期" prop="certificate_date"></el-table-column>
                <el-table-column label="领域">
                  <template slot-scope="scope">
                      <span>{{ fileOptions[scope.row.field] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="是否A类">
                  <template slot-scope="scope">
                        <el-tag v-if="scope.row.a_class" type="primary">是</el-tag>
                        <el-tag v-else type="warning">否</el-tag>
                    </template>
                </el-table-column>
              </el-table>
          </el-card>
        </el-col>
        <el-col :span="12" style="margin-top: 5px;">
          <el-card>
             <div class="cardHead">
                <span class="cardTitle">客户投诉</span>
              </div>
              <el-table
                  :data="complaintList"
                  fit
                  stripe
                  highlight-current-row
                  height="250px"
                  id="table4"
                >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="投诉人/机构" prop="complainant"></el-table-column>
                <el-table-column label="投诉内容" prop="content"></el-table-column>
                <el-table-column label="投诉日期" prop="date_occurrence"></el-table-column>
                <el-table-column label="处理结果反馈日期" prop="date_feedback"></el-table-column>
                <el-table-column label="客户是否满意">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.is_satisfied" type="primary">满意</el-tag>
                        <el-tag v-else type="warning">不满意</el-tag>
                    </template>
                </el-table-column>
                
              </el-table>
          </el-card>
        </el-col>
        <el-col :span="12" style="margin-top: 5px;">
          <el-card>
            <div class="cardHead">
                <span class="cardTitle">风险识别</span>
              </div>
              <el-table
                  :data="riskList"
                  fit
                  stripe
                  highlight-current-row
                  height="250px"
                  id="table5"
                >
                <el-table-column label="序号" type="index" width="50" />
                <el-table-column label="风险事实描述" prop="content"></el-table-column>
                <el-table-column label="风险类别">
                  <template slot-scope="scope">
                      <span>{{ levelOptions[scope.row.level] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="风险代码" prop="code"></el-table-column>
                <el-table-column label="整改情况">
                  <template slot-scope="scope">
                      <span>{{ codeOptions[scope.row.state] }}</span>
                    </template>
                </el-table-column>
              </el-table>
          </el-card>
        </el-col>
        <el-col :span="12" style="margin-top: 5px;">
          <el-card>
            <div class="cardHead">
                <span class="cardTitle">外部监督检查</span>
              </div>
              <el-table
                  :data="oinspectList"
                  fit
                  stripe
                  highlight-current-row
                  height="250px"
                  id="table6"
                >
                <el-table-column label="序号" type="index" width="50" />
                
                <el-table-column label="检查分类">
                  <template slot-scope="scope">
                      <span>{{ cateOptions[scope.row.cate] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="检查机构" prop="checker"></el-table-column>
                <el-table-column label="检查日期" prop="date_inspect"></el-table-column>
                <el-table-column label="检查结果" prop="result"></el-table-column>
                <el-table-column label="结果日期" prop="result_date"></el-table-column>
                <el-table-column label="检查通知单" prop="notification_form"></el-table-column>
                <el-table-column label="检查结果告知单" prop="result_form"></el-table-column>
              </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!-- 添加执行组织 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dgaction.name"
      :close-on-click-modal="false"
      width="1100px"
    >
      <el-transfer
        v-model="depts"
        :data="deptOptions"
        :titles="['单位列表', '选择的单位']"
        :props="{ key : 'id' , label: 'name' }"
      >
      <span slot-scope="{ option }">{{ option.sort }} - {{ option.name }}</span>
      </el-transfer>
      <div style="text-align: right">
      <el-button type="primary" @click="confirm()">确认</el-button>
    </div>
    </el-dialog>
    <!-- 记录 -->
    <el-drawer
      title="记录"
      :visible.sync="drawer"
      :with-header="false"
      size="40%"
    >
      <recorddo
        ref="recorddo"
        :data="data"
        @handleDo="handleDo"
        v-if="drawer"
      ></recorddo>
    </el-drawer>
  </div>
</template>
<style >
.term {
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
  font-size: 16px;
}
.desc {
  color: rgba(0, 0, 0, 0.65);
  font-weight: bold;
  font-size: 16px;
}
.litem {
  margin-bottom: 4px;
  margin-left: 2px;
  cursor: pointer;
  color: #409eff;
}
</style>
<script>
import { getOrgList } from "@/api/org";
import { getTask2, addDeptsTask2, getTask2Do, startTask2, confirmTaskdept ,deleteTask2Do,
  getPgoalDeptList,getRcList,getPtList,getRiskList,getComplaintList,getOinspectList} from "@/api/task";
import Pagination from "@/components/Pagination";
import checkPermission from "@/utils/permission";
import recorddo from "@/views/supervision/recorddo";
import { upUrl, upHeaders } from "@/api/file";
import FileSaver from "file-saver";
  import * as XLSX from "xlsx";
export default {
  components: { Pagination, recorddo },
  data() {
    return {
      task: { id: 0 },
      dialogVisible: false,
      dialogVisibles: false,
      dialogType: "new",
      activeName: "contenttab",
      contents: [],
      depts: [],
      isSaving:false,
      listLoading: false,
      listLoading2: false,
      recordList: [],
      nowcontent: {},
      nowdept: {},
      drawer: false,
      data: {},
      taskdeptall: [],
      listQuery:{},
      selectRecords:[],
      dgaction:{
        action:'start',
        name:'开始任务'
      }
      ,
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      fileList:[],
      Taskdept:{is_yes:true},
      statusOptios:{
        10:'创建中',
        20:'进行中',
        30:'已关闭',
      },
      cycleOptions:{
        0:'年',
        1:'1-2月',
        2:'3-4月',
        3:'5-6月',
        4:'7-8月',
        5:'9-10月',
        6:'11-12月',
      },
      resultsOptions:{
        10:'满意',
        20:'有问题',
        30:'不满意'
      },
      fileOptions:{
        0:'建工',
        10:'建材',
        20:'环境',
        30:'食农',
      },
      handleOptions:{
        0:'/',
        10:'已整改',
        20:'被暂停',
        30:'已被撤销认可资格',
      },
      levelOptions:{
        10:'主要风险',
        20:'严重风险',
        30:'重大风险'
      },
      codeOptions:{
        10:'未整改',
        20:'整改中',
        30:'整改完成'
      },
      cateOptions:{
        10:'市场监管部门检查',
        20:'行业主管部门检查',
        30:'其他检查'
      },
      task2do:'',
      depts: [],
      deptOptions: [],
      task2doItem:{},
      rcList:[],//报告证书{应发/超期}
      rc2List:{},
      ptList:[],//能力验证
      riskList:[],//风险
      complaintList:[],//投诉
      oinspectList:[],//外部监查
      rc2ListQuery:{
          page: 1,
          page_size: 20,
      },
    };
  },
  created() {
    this.task.id = this.$route.params.id;
    this.gettask();
  },
  mounted(){
    this.gettaskdeptall();
  },
  methods: {
    checkPermission,
    gettask() {
      getTask2(this.task.id).then((res) => {
        this.task = res.data;
        if (this.task.state == "创建中") {
          this.dialogVisible = true;
        }
      });
    },
    getOrgList() {
      getOrgList({can_supervision:true}).then((res) => {
        this.deptOptions = res.data;
      });
    },
    gettaskdeptall() {
      this.listLoading = true;
      getTask2Do({task2:this.task.id,page:0})
        .then((res) => {
          this.listLoading = false;
          this.taskdeptall = [];
          let taskdept = res.data;
          taskdept.forEach(item=>{
            let obj = item;
            let pross = Number((item.count_up/item.count_all).toFixed(4))
            obj.pross = parseFloat((pross*100).toPrecision(12));
            this.taskdeptall.push(obj);
          })
        })
        .catch((e) => {
          this.listLoading = false;
        });
    },
    append() {
      this.dgaction ={
        action:'append',
        name:'追加执行组织'
      }
      this.getOrgList();
      this.dialogVisible = true;
    },
    startTask() {
      this.$confirm("确认发布任务吗?", "提示")
        .then(async () => {
          await startTask2(this.task.id);
          location.reload();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleRecord(data) {
      this.data = data;
      this.drawer = true;
    },
    handleDo(data) {
      this.drawer = false;
      this.gettask();
      this.gettaskdeptall();
      this.getRecordList();
    },
    getRecordList() {
      getPgoalDeptList(this.listQuery)
        .then((res) => {
          this.listLoading2 = false;
          let data = res.data.results;
          for(let i=0;i<data.length;i++){
            if(data[i].goal_key!=="pgoal_1"){
              let value_a = data[i].goal_value_a+'';
              let value_b = data[i].goal_value_b+'';
              if(value_a!=='null'){
                data[i].goal_value_a=value_a.indexOf('.')>-1?value_a:value_a+'.0';
              }else{
                data[i].goal_value_a=''
              }
              if(value_b!='null'){
                data[i].goal_value_b=value_b.indexOf('.')>-1?value_b:value_b+'.0';
              }else{
                data[i].goal_value_b='';
              }
              
            }
          }
          this.recordList = data;
        })
        .catch((e) => {
          this.listLoading2 = false;
        });
    },
    clickRow(row) {
      this.listLoading2 = true;
      this.listQuery = { task2do: row.id };
      if(this.task.type==10){
        this.getRecordList();
      }else if(this.task.type==20){
        this.task2doItem = row;
        this.task2do = row.id;
        this.getPtList();
        this.getRcList();
        this.getRc2List();
        this.getRiskList();
        this.getComplaintList();
        this.getOinspectList();
        
      } 
    },
    handleExport(row){
      let name = row.belong_dept_.name;
      let filename = name+'.xlsx';
      this.listQuery = { task2do: row.id };
      if(this.task.type==10){
        getPgoalDeptList(this.listQuery).then((res) => {
          this.recordList = res.data.results;
          setTimeout(function(){
            let wb = XLSX.utils.table_to_book(document.getElementById('tableGoal'),{row:true})
            XLSX.writeFile(wb, filename)
          },100)
        }).catch((e) => {});
      }else if(this.task.type==20){
        this.task2doItem = row;
        this.task2do = row.id;
        this.getPtList();
        this.getRcList();
        this.getRc2List();
        this.getRiskList();
        this.getComplaintList();
        this.getOinspectList();
        setTimeout(function(){
        
        let str = `重大事故,风险识别,应发报告,已发报告,不准确报告,超期报告,能力验证结果,验证结果满意,客户投诉,投诉结果满意,外部监督检查\n`;
        str+=row.num_acc+'\t,';
        str+=row.num_risk+'\t,';
        str+=row.num_expect+'\t,';
        str+=row.num_issue+'\t,';
        str+=row.num_error+'\t,';
        str+=row.num_overdue+'\t,';
        str+=row.num_pt+'\t,';
        str+=row.num_pt_10+'\t,';
        str+=row.num_complaint+'\t,';
        str+=row.num_complaint_10+'\t,';
        str+=row.num_oinspect+'\t';
        let uri = 'data:application/vnd.ms-excel;charset=utf-8,\ufeff' + encodeURIComponent(str);
        const link = document.createElement("a");
        link.href = uri;
         // 对下载的文件命名
        link.download =  row.belong_dept_.name+"统计.xls";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        let wb = XLSX.utils.book_new();
        let sheet = XLSX.utils.table_to_sheet(document.getElementById('table1'), {row:true});
        let sheet2 = XLSX.utils.table_to_sheet(document.getElementById('table2'), {row:true});
        let sheet3 = XLSX.utils.table_to_sheet(document.getElementById('table3'), {row:true});
        let sheet4 = XLSX.utils.table_to_sheet(document.getElementById('table4'), {row:true});
        let sheet5 = XLSX.utils.table_to_sheet(document.getElementById('table5'), {row:true});
        let sheet6 = XLSX.utils.table_to_sheet(document.getElementById('table6'), {row:true});
        XLSX.utils.book_append_sheet(wb, sheet,'不准确报告')
        XLSX.utils.book_append_sheet(wb, sheet2,'超期报告')
        XLSX.utils.book_append_sheet(wb, sheet3,'能力验证结果')
        XLSX.utils.book_append_sheet(wb, sheet4,'客户投诉')
        XLSX.utils.book_append_sheet(wb, sheet5,'风险识别')
        XLSX.utils.book_append_sheet(wb, sheet6,'外部监督检查')
        let wbout = XLSX.write(wb, {  bookType: 'xlsx', bookSST: true, type: 'array' })
        try {
          FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${filename}`)
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        }
        return wbout
      },500)
      }
      
    },
    handleExportAll(){
      let that = this;
      that.isSaving = true;
      let filename = '任务统计.xlsx';
      let wb = XLSX.utils.book_new();
      getRcList({task2do__task2:that.task.id,etype:10,page:0}).then((res) => {
        let rcList =res.data;
        let sheetObject1 = [{
                  '序号': '',
                  '报告/证书编号': '',
                  '更改后报告/证书编号': '',
                  '出错原因': '',
                  '更改报告/证书发放日期': '',
                  '单位名称': '',
              }];
        if (rcList.length > 0) {
          sheetObject1 = rcList.map((item1, index1) => {
            return {
                  '序号': index1 + 1,
                  '报告/证书编号': item1.number,
                  '更改后报告/证书编号': item1.number_correct,
                  '出错原因': item1.reason_error,
                  '更改报告/证书发放日期': item1.date_issue,
                  '单位名称': item1.belong_dept_name,
              };
          });
        }
        let sheet1 = XLSX.utils.json_to_sheet(sheetObject1);
        XLSX.utils.book_append_sheet(wb, sheet1, "不准确报告");
        getRcList({task2do__task2:that.task.id,etype:20,page:0}).then((res) => {
          let rc2List =res.data;
          let sheetObject2 = [{
                  '序号': '',
                  '超期报告/证书编号': '',
                  '业务受理日期': '',
                  '报告/证书应发日期': '',
                  '报告/证书实际发放日期': '',
                  '单位名称': '',
          }];
          if (rc2List.length > 0) {
            sheetObject2 = rc2List.map((item2, index2) => {
              return {
                    '序号': index2 + 1,
                    '超期报告/证书编号': item2.number,
                    '业务受理日期': item2.date_accept,
                    '报告/证书应发日期': item2.date_expect,
                    '报告/证书实际发放日期': item2.date_issue,
                    '单位名称': item2.belong_dept_name,
                };
            });
          }
          let sheet2 = XLSX.utils.json_to_sheet(sheetObject2);
          XLSX.utils.book_append_sheet(wb, sheet2, "超期报告");
          getPtList({task2do__task2:that.task.id,page:0}).then((res) => { //能力验证结果
            let ptList =res.data;
            let sheetObject3 = [{
                  '序号': '',
                  '能力验证名称': '',
                  '项目编号': '',
                  '组织方': '',
                  '参加参数名称': '',
                  '结果': '',
                  '处理结果': '',
                  '单位名称': '',
                  '证书日期': '',
                  '领域': '',
                  '是否A类': '',
            }];
            if (ptList.length > 0) {
              sheetObject3 = ptList.map((item3, iindex3) => {
                let result = item3.result==10?'满意':item3.result==20?'有问题':'不满意';
                let handle_result = item3.result==0?'/':item3.result==10?'已整改':item3.result==20?'被暂停':'已被撤销认可资格';
                return {
                    '序号': iindex3 + 1,
                    '能力验证名称': item3.name,
                    '项目编号': item3.number,
                    '组织方': item3.organizer,
                    '参加参数名称': item3.params,
                    '结果': result,
                    '处理结果': handle_result,
                    '单位名称': item3.belong_dept_name,
                    '证书日期': item3.certificate_date,
                    '领域': item3.field,
                    '是否A类': item3.a_class
                };
              });
            }
            let sheet3 = XLSX.utils.json_to_sheet(sheetObject3);
            XLSX.utils.book_append_sheet(wb, sheet3, "能力验证结果");
            getComplaintList({task2do__task2:that.task.id,page:0}).then((res) => {
              let complaintList =res.data;
              let sheetObject4 = [{
                      '序号': '',
                      '投诉人/机构': '',
                      '投诉内容': '',
                      '投诉日期': '',
                      '处理结果反馈日期': '',
                      '客户是否满意': '',
                      '单位名称': '',
              }];
              if (complaintList.length > 0) {
                sheetObject4 = complaintList.map((item4, index4) => {
                  let is_satisfied = item4.is_satisfied?'满意':'不满意';
                  return {
                        '序号': index4 + 1,
                        '投诉人/机构': item4.complainant,
                        '投诉内容': item4.content,
                        '投诉日期': item4.date_occurrence,
                        '处理结果反馈日期': item4.date_feedback,
                        '客户是否满意':is_satisfied,
                        '单位名称': item4.belong_dept_name,
                    };
                });
              }
              let sheet4 = XLSX.utils.json_to_sheet(sheetObject4);
              XLSX.utils.book_append_sheet(wb, sheet4, "客户投诉");
              getRiskList({task2do__task2:that.task.id,page:0}).then((res) => {
                let riskList =res.data;
                let sheetObject5 = [{
                        '序号': '',
                        '风险事实描述': '',
                        '风险类别': '',
                        '风险代码': '',
                        '整改情况': '',
                        '单位名称': '',
                }];
                if (riskList.length > 0) {
                  sheetObject5 = riskList.map((item5, index5) => {
                    let level = item5.level==10?'主要风险':item5.level==20?'严重风险':'重大风险';
                    let state = item5.state==10?'未整改':item5.level==20?'整改中':'整改完成';
                    return {
                          '序号': index5 + 1,
                          '风险事实描述': item5.content,
                          '风险类别': level,
                          '风险代码': item5.code,
                          '整改情况': state,
                          '单位名称': item5.belong_dept_name,
                      };
                  });
                }
                let sheet5 = XLSX.utils.json_to_sheet(sheetObject5);
                XLSX.utils.book_append_sheet(wb, sheet5, "风险识别");
                getOinspectList({task2do:that.task2do,page:0}).then((res) => {
                  let oinspectList =res.data;
                    let sheetObject6 = [{
                            '序号': '',
                            '检查分类': '',
                            '检查机构': '',
                            '检查日期': '',
                            '检查结果': '',
                            '检查日期': '',
                            '单位名称': '',
                    }];
                    if (oinspectList.length > 0) {
                      sheetObject6 = oinspectList.map((item6, index6) => {
                        let cate = item6.cate==10?'市场监管部门检查':item6.cate==20?'行业主管部门检查':'其他检查';
                        return {
                              '序号': index6 + 1,
                              '检查分类': cate,
                              '检查机构': item6.checker,
                              '检查日期': item6.date_inspect,
                              '检查结果': item6.result,
                              '结果日期': item6.result_date,
                              '单位名称': item6.belong_dept_name,
                          };
                      });
                    }
                    let sheet6 = XLSX.utils.json_to_sheet(sheetObject6);
                    XLSX.utils.book_append_sheet(wb, sheet6, "外部监督检查");
                    let wbout = XLSX.write(wb, {  bookType: 'xlsx', bookSST: true, type: 'array' })
                    try {
                      FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${filename}`)
                      that.isSaving = false;
                    } catch (e) {
                      if (typeof console !== 'undefined') {
                        console.log(e, wbout)
                        
                      }
                    }
                    return wbout
                });
              });
            });
          });
        });
      });
    },
    getRcList(){
      let that = this;
      getRcList({task2do:that.task2do,etype:10,page:0}).then((res) => {
        that.rcList =res.data;
      });
    },
    getRc2List(){
          let that = this;
          let obj = {};
          obj.task2do = that.task2do;
          obj.etype = 20;
          obj.page = that.rc2ListQuery.page;
          obj.page_size = that.rc2ListQuery.page_size;
          getRcList(obj).then((res) => {
            if (res.code >= 200) {
              that.rc2List =res.data;
            }
          });
        },
    getPtList(){
      let that = this;
      getPtList({task2do:that.task2do,page:0}).then((res) => {
        if (res.code >= 200) {
          that.ptList=res.data;
        }
      });
    },
    getRiskList(){
      let that = this;
      getRiskList({task2do:that.task2do,page:0}).then((res) => {
        if (res.code >= 200) {
          that.riskList = res.data;
        }
      });
    },
    getComplaintList(){
      let that = this;
      getComplaintList({task2do:that.task2do,page:0}).then((res) => {
        if (res.code >= 200) {
          that.complaintList = res.data;
        }
      });
    },
    getOinspectList(){
      let that = this;
      getOinspectList({task2do:that.task2do,page:0}).then((res) => {
        if (res.code >= 200) {
          that.oinspectList=res.data;
        }
      });
    },
    handleSelectRecords(val){
      let selects = [];
      for (var i = 0; i < val.length; i++) {
        selects.push(val[i].id);
      }
      this.selectRecords = selects;
    },
    // handleConfirmDept(scope){
    //   confirmTaskdept(scope.row.id).then(res=>{
    //     this.getRecordList()
    //     this.gettaskdeptall()
    //   })
    // },
    //反馈意见
     handlePreview(file) {
      if ("url" in file) {
        window.open(file.url);
      } else {
        window.open(file.response.data.path);
      }
    },
    handleUpSuccess(res, file, filelist) {
      this.Taskdept.file = res.data.path;
       this.filename = res.data.name;
    },
    handleRemove(file, filelist){
      this.Taskdept.file = null;
    },
    handleConfirmFK(scope){
      this.Taskdept = Object.assign({}, scope.row); // copy obj
      this.dialogVisibles = true;
      if (this.Taskdept.file) {
        this.fileList = [
          {
            name:"反馈文件",
            url: this.Taskdept.file,
          },
        ];
      }
      this.$nextTick(() => {
        this.$refs["Forms"].clearValidate();
      });
    },

   async confirmfk(form) {
      this.$refs[form].validate((valid) => {
        console.log(this.Taskdept)
        this.Taskdept.is_yes=true;
          updateTaskdept(this.Taskdept.id,this.Taskdept).then((res) => {
          if (res.code >= 200) {
              this.gettaskdeptall()
            this.dialogVisibles = false;
            this.$message.success("成功");
          }
        });
      });
    },

    handleDeleteDept(scope){
      this.$confirm("确认删除该部门吗?", "提示")
        .then(async () => {
          deleteTask2Do(scope.row.id).then(res=>{
            this.gettaskdeptall();
            this.$message.success("成功");
          })
          
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleUp2(){
      if (this.selectRecords.length) {
        this.$prompt('请输入备注内容', '提示').then(({ value }) => {
          updateRecords({note:value, ids:this.selectRecords}).then(res=>{
            this.$message.success('成功')
            this.getRecordList();
          })
        }).catch(() => {      
        });
      } else {
        this.$message({
          message: "请先选择",
          type: "warning",
        });
      }
    },
    confirm(){
        if(this.depts.length>0){
          let data = {ids:this.depts}
          // this.task.depts = this.depts;
          this.chooseComplete(data)
        }else{
            this.$message.error('请选择清单和单位!')
        }
    },
    chooseComplete(data) {
      this.dialogVisible = false;
      const rLoading = this.openLoading("正在添加执行组织,请稍等...");
      addDeptsTask2(this.task.id, data).then((res) => {
        rLoading.close();
        this.$message.success("成功");
        this.$router.go(0);
      }).catch(e=>{rLoading.close();});
    },
  },
};
</script>
