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

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

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

      <avue-crud
        style="width: 100%; margin-top: 15px"
        :data="tableData"
        :option="option"
        :page.sync="page"
        :table-loading="tableLoading"
        @selection-change="selectionChange"
        @search-change="searchVal"
        @search-reset="searchReset"
        @on-load="getList"
        @size-change="sizeChange"
        @current-change="currentChange"
      >
        <template slot="menu" slot-scope="scope">
          <el-button
            v-if="userInfo.roles.includes(scope.row.checkState.roleId)"
            type="text"
            size="small"
            icon="el-icon-document-checked"
            v-show="examineShow"
            @click="examineBtn(scope.row, scope.index)"
            >审核
          </el-button>

          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="lookBtn(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.taskStatusInfo || '无')"
              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
        v-if="showDialog"
        title="审核"
        :visible.sync="showDialog"
        top="12vh"
        width="50%"
        center
        :before-close="handleClose"
        class="review-dialog"
      >
        <el-form
          :model="taskForm"
          :rules="rules"
          ref="taskForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <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 v-show="singleFlag" class="teskDetailsty">服务详情</p>
          <div v-if="singleFlag && showDialog">
            <task-detail
              :id="examineVal"
              @getSurveyTaskInfoById="getSurveyTaskInfoById"
            />
          </div>
          <p class="teskDetailsty">审批意见</p>
          <el-form-item
            label="审批意见:"
            prop="taskStatus"
            class="formitem-box"
          >
            <el-radio-group v-model="taskForm.taskStatus">
              <el-radio label="3">通过</el-radio>
              <el-radio label="4">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="意见说明:"
            prop="taskStatusInfo"
            class="formitem-box"
            :rules="[
              {
                required: taskForm.taskStatus == 3 ? false : true,
                message: '请输入审批说明',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              type="textarea"
              v-model="taskForm.taskStatusInfo"
            ></el-input>
          </el-form-item>
          <refuseReason
            v-if="taskForm.taskStatus === '4'"
            @selectRefuseReason="selectRefuseReason"
          />
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="sureBtn('taskForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <!-- 导出弹窗 -->
    <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 { taskAuditData } from "@/const/crud/assignPoints/quota/taskAudit";
import {
  getWmTaskList,
  approvalTask,
  getTaskList,
  reviewTask
} 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: "taskAudit",
  components: {
    taskDetail,
    refuseReason
  },
  data() {
    return {
      currentRow: "",
      form: {},
      taskTypeId: "",
      taskList: [],
      singleFlag: false,
      tableData: [],
      option: taskAuditData,
      page: {
        pageSize: 10,
        pagerCount: 5,
        pageSizes: [10, 30, 50, 100, 150, 200]
      },
      isHasAudit: false,
      packageIds: null,
      showDialog: false,
      taskForm: {
        taskStatusInfo: ""
      },
      taskDetail: "",
      examineShow: false,
      showReview: true,
      scorePackageStatus: null,
      rules: {
        taskStatus: [
          { required: true, message: "请选择审批意见", trigger: "change" }
        ]
        // taskStatusInfo: [
        //   { required: true, message: "请输入审批说明", trigger: "blur" }
        // ]
      },
      tableLoading: false,
      searchForm: {},
      examineVal: "",
      jfbID: "",
      atypismData: [],
      selection: [],
      exportDig: false,
      wordStatus: {},
      wordLoading: false,
      excelStatus: {},
      excelLoading: false,

      task_status_dict: []
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    totalScore() {
      return this.selection.reduce((pre, cur) => {
        return pre + (cur.score || 0);
      }, 0);
    }
    // getTaskStatusVal() {
    //   return taskStatusId => {
    //     console.log("taskStatusId", taskStatusId);
    //     console.log("task_status_dict", this.task_status_dict);
    //     const curr = this.task_status_dict.find(
    //       ele => ele.value == taskStatusId
    //     );
    //     console.log("curr", curr);
    //     if (curr) return curr.label;
    //   };
    // }
  },
  created() {
    this.getTaskStatusDict();
    this.getTaskList();
    this.getStatus();
  },
  mounted() {
    if (this.$route.query.type == "taskAudit") {
      this.examineShow = true;
    } else {
      this.examineShow = false;
    }
    if (this.$route.query.page == "teamPoints") {
      this.showReview = false;
    }
    if (this.$route.query.scorePackageStatus) {
      this.scorePackageStatus = this.$route.query.scorePackageStatus + "";
    }
  },
  methods: {
    getTaskStatusVal(taskStatus) {
      taskStatus = String(taskStatus).trim();
      const curr = this.task_status_dict.find(
        item => item.value == Number(taskStatus)
      );
      if (curr) {
        return curr.label;
      }
    },

    getTaskStatusDict() {
      getDictType({ type: "task_status" }).then(res => {
        this.task_status_dict = res.data.data;
      });
    },
    selectRefuseReason(refuseReason) {
      let info;
      if (this.taskForm.taskStatusInfo) {
        info = this.taskForm.taskStatusInfo + refuseReason + "；";
      } else {
        info = refuseReason + "；";
      }

      this.$set(this.taskForm, "taskStatusInfo", info);
    },
    getStatus() {
      taskApi.wordStatus(this.$route.query.id).then(res => {
        this.wordStatus = res.data.data;
      });
      taskApi.excelStatus(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.wordReport(this.$route.query.id);
        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.excelReport(this.$route.query.id);
        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=1"
      });
    },
    async getTaskList() {
      const res = await getTaskList(
        this.$route.query.id,
        this.$route.query.taskStatus == "2" ? "2" : ""
      );
      this.taskList = res.data.data;
    },
    getName(row) {
      let id = row.taskTypeId;
      let curr = this.taskList.find(item => item.id == id);
      return curr.taskTypeName;
    },
    // 复row选框选中的值
    selectionChange(selection, row) {
      this.selection = selection;
      this.isHasAudit = false;
      this.packageIds = "";
      if (undefined != selection) {
        for (var i = 0; i < selection.length; i++) {
          if (selection[i].taskStatus > 0) {
            this.isHasAudit = true;
          }

          this.packageIds += selection[i].id;
          if (i < selection.length - 1) {
            this.packageIds += ",";
          }
        }
      }
    },
    // 初始化页面
    getList(page, params) {
      this.tableLoading = true;
      getWmTaskList(
        Object.assign(
          {
            taskStatus: this.$route.query.taskStatus == "2" ? "2" : "",
            scorePackageId: this.$route.query.id,
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = [];
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          this.taskForm = {};
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 查询
    searchVal(form, done) {
      this.searchForm = form;
      this.searchForm.monthStart = this.monthStart;
      this.searchForm.monthEnd = this.monthEnd;
      this.searchForm.taskTypeId = this.taskTypeId;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    searchReset() {
      this.taskTypeId = "";
    },
    // 返回按钮
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    },

    // 审核按钮
    examineBtn(row) {
      this.currentRow = row;
      this.examineVal = row.id;
      this.jfbID = row.scorePackageId;
      this.showDialog = true;
      this.singleFlag = true;
      this.taskDetail =
        Config.outsideUrl + "/h5/#/pages/task/task-detail/index?id=" + row.id;
    },

    //批量审核按钮
    examineBtnPl() {
      this.examineVal = this.packageIds;
      this.currentRow = this.tableData[0];
      this.singleFlag = false;
      if (this.examineVal == null) {
        this.$message.error("请选择需要审核的任务");
        this.examineVal = null;
        return false;
      } else if (this.examineVal == "") {
        this.$message.error("请选择需要审核的任务");
        this.examineVal = null;
        return false;
      } else {
        this.showDialog = true;
      }
    },
    // 弹窗确定按钮
    sureBtn(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.taskForm.id = this.examineVal;
          this.taskForm.scorePackageId = this.jfbID;
          let args = {
            id: this.examineVal,
            taskStatus: this.taskForm.taskStatus,
            taskStatusInfo: this.taskForm.taskStatusInfo,
            nodeId: this.currentRow.checkState.curNodeId
          };
          approvalTask(args)
            .then(response => {
              this.showDialog = false;
              this.getList(this.page);
              this.tableLoading = false;
              this.$message.success(response.data.data);
            })
            .catch(() => {
              this.tableLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查看
    lookBtn(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"
      );
    },

    handleClose() {
      this.showDialog = false;
      this.singleFlag = false;
      this.atypismData = [];
      this.taskForm = {};
      this.examineVal = "";
    },

    // 分页查询
    sizeChange() {},
    currentChange() {},
    // 获取不一致信息
    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;
  }
  .formitem-box {
    margin-bottom: 6px;
  }
}
.down-item {
  margin-left: 20px;
  margin-bottom: 15px;
  span {
    width: 80px;
    display: inline-block;
    text-align: right;
  }
  .first {
    width: 240px;
  }
}
</style>

<style>
.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;
}
.missionContsty {
  height: 300px;
  border: 1px solid #f2f2f2;
  margin-bottom: 15px;
}
</style>
