<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="方案名称：">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="提交部门：">
        <el-cascader v-model="queryParams.deptId" :options="deptTreeList">
        </el-cascader>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="(item, k) in status"
            :key="item"
            :label="item"
            :value="k"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年度：">
        <el-date-picker
          v-model="valueYear"
          type="year"
          placeholder="选择年"
          value-format="yyyy"
          :clearable="false"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" type="flex" justify="end">
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="handleUpdate('add', '方案上传')"
          v-hasPermi="['postCheck:programme:add']"
          >方案上传</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="handleTemplateManagement"
          v-hasPermi="['postCheck:programme:add']"
          >模板管理</el-button
        >
      </el-col>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="postList"
      height="calc(100% - 190px)"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column label="方案名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.name || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="附件文件" align="center">
        <template slot-scope="{ row }">
          <el-link type="primary" @click="handelPrevie(row.diskPath)">{{
            getFileName(row.diskPath)
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="提交部门" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.deptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.submitDate || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <span :style="{ color: statusColor[row.status] }">{{
            status[row.status]
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通过日期" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updateTime || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            v-if="scope.row.status === 3"
            @click="handleUpdate('check', '查看', scope.row)"
            v-hasPermi="['postCheck:programme:query']"
            >查看</el-button
          >
          <el-button
            v-if="scope.row.status !== 3"
            type="text"
            @click="handleUpdate('edit', '修改', scope.row)"
            v-hasPermi="['postCheck:programme:edit']"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.status !== 3"
            type="text"
            v-hasPermi="['postCheck:programme:audit']"
            @click="handleUpdate('audit', '审核', scope.row)"
            >审核</el-button
          >
          <el-button
            v-if="scope.row.status !== 3"
            type="text"
            v-hasPermi="['postCheck:programme:remove']"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-dropdown
            size="mini"
            v-if="scope.row.status !== 3"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >邮件通知</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleAuditor"
                >审核人</el-dropdown-item
              >
              <el-dropdown-item command="handlePrepared"
                >制单人</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核 -->
    <el-dialog :title="title" :visible="open" width="550px" @close="cancel">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="方案名称：">
          <el-input
            v-model="form.name"
            placeholder="请输入"
            :disabled="type === 'check' || type === 'audit'"
          />
        </el-form-item>
        <el-form-item
          label="提交部门："
          v-if="type !== 'add' || type === 'audit'"
        >
          <el-input
            v-model="form.deptName"
            placeholder="请输入"
            :disabled="type === 'check' || type === 'edit'"
          />
        </el-form-item>
        <el-form-item label="状态：" v-if="type !== 'add'">
          <el-steps :active="form.step">
            <el-step
              v-for="(item, index) in stepList"
              :key="index"
              :title="item.name"
              :status="item.status"
              :description="item.description"
            ></el-step>
          </el-steps>
        </el-form-item>
        <el-form-item label="文件名称：" v-if="type !== 'add'">
          <el-link type="primary" @click="handelPrevie(form.diskPath)">{{
            getFileName(form.diskPath)
          }}</el-link>
        </el-form-item>
        <el-form-item
          label="上传附件："
          prop="postCode"
          v-if="type === 'edit' || type === 'add'"
        >
          <el-upload
            ref="upload"
            :limit="1"
            accept="pdf,docx,xls,xlsx"
            :action="uploadFileUrl"
            :on-progress="handleFileUploadProgress"
            :before-upload="handleBeforeUpload"
            :on-success="handleFileSuccess"
            :headers="headers"
            :file-list="fileList"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传pdf/docx/xls/xlsx文件
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="未通过理由：" v-if="textarea || type === 'audit'">
          <el-input
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 8 }"
            placeholder="请输入"
            v-model="textarea"
            :disabled="type !== 'audit'"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="type !== 'check'">
        <el-button
          type="primary"
          @click="submitForm1"
          v-if="type === 'add' || type === 'edit'"
          >提交</el-button
        >
        <el-button type="primary" v-if="type === 'audit'" @click="submitForm(4)"
          >不通过</el-button
        >
        <el-button type="primary" v-if="type === 'audit'" @click="submitForm(3)"
          >通过</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="模板管理"
      :visible.sync="templateManagementDialog"
      width="1000px"
      append-to-body
    >
      <el-row :gutter="10" class="mb8" type="flex" justify="end">
        <el-col :span="1.5">
          <el-button type="primary" @click="createTemplate">创建模板</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="downloadTemplate"
            >下载模板</el-button
          >
        </el-col>
      </el-row>
      <el-table border v-loading="loading" :data="templateList">
        <el-table-column label="方案名称" align="center">
          <template slot-scope="{ row }">
            <span>{{ row.planName || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板名称" align="center">
          <template slot-scope="{ row }">
            <el-link type="primary" @click="handelPrevie(row.diskPath)">{{
              getFileName(row.diskPath)
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="{ row }">
            <span>{{ row.createTime || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{ row }">
            <span :style="{ color: row.status === 1 ? '#61dd83' : 'red' }">{{
              row.status === 1 ? "启用" : "作废"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="180"
        >
          <template slot-scope="{ row }">
            <!-- <el-button
              type="text"
              @click="handelPrevie(row.diskPath)"
              v-hasPermi="['system:post:edit']"
              >查看</el-button
            > -->
            <el-button
              type="text"
              @click="handleDown(row.diskPath)"
              v-hasPermi="['system:post:edit']"
              >下载</el-button
            >
            <el-button type="text" @click="handleApprove(row)">{{
              row.status === 1 ? "作废" : "启用"
            }}</el-button>
            <el-button type="text" @click="handelDelTemplate(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="templateTotal > 0"
        :total="templateTotal"
        :page.sync="templateParams.pageNum"
        :limit.sync="templateParams.pageSize"
        @pagination="getTemplateList"
      />
    </el-dialog>
    <el-dialog
      title="创建模版"
      :visible="establishDialog"
      width="500px"
      append-to-body
      @close="cancelEstablish"
    >
      <el-form ref="templateForm" :model="templateForm" label-width="100px">
        <el-form-item label="方案名称：">
          <el-input v-model="templateForm.planName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上传附件：">
          <el-upload
            ref="upload"
            :limit="1"
            accept=""
            :action="uploadFileUrl"
            :on-progress="handleFileUploadProgress"
            :before-upload="handleBeforeUpload"
            :on-success="handleFileSuccess"
            :headers="headers"
            :file-list="fileList"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div slot="tip" class="el-upload__tip">
              只能上传pdf/docx/xls/xlsx文件
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTemplate">创建</el-button>
        <el-button @click="cancelEstablish">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="预览附件"
      :visible.sync="previewAnnex"
      :fullscreen="true"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <preview-file
        :preview-url="previewUrl"
        :preview-type="previewType"
        @handleDownload="handleDownload"
      />

      <div slot="footer" class="batch-dialog-footer">
        <el-button type="primary" @click="previewAnnex = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProgramme,
  getProgramme,
  delProgramme,
  addProgramme,
  updateProgramme,
  listProgrammeTemplate,
  getProgrammeTemplate,
  delProgrammeTemplate,
  addProgrammeTemplate,
  updatProgrammeTemplate,
  approveHr,
  approveIcfa,
  getBase64,
  approve,
  sendMailFile,
} from "@/api/postInspectionPlanning/projectManagement.js";
import { getDeptTree } from "@/api/postInspectionPlanning/teamManagement.js";
import download from "@/plugins/download.js";
import { getToken } from "@/utils/auth";
import { getBaseUrl } from "@/utils/baseUrl.js";

export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      deptTreeList: [],
      valueYear: "",
      fileList: [],
      uploadList: [],
      type: "",
      rowId: "",
      checkDialog: false,
      templateManagementDialog: false,
      textarea: "",
      // 文件预览
      previewAnnex: false,
      previewUrl: "",
      previewType: "",
      filename: "",
      establishDialog: false,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      templateTotal: 0,
      postList: [],
      status: {
        1: "待审核",
        2: "审核中",
        3: "通过",
        4: "驳回",
      },
      statusColor: {
        1: "#cdd152",
        2: "#61dd83",
        3: "#61dd83",
        4: "red",
      },
      stepList: [
        {
          name: "内控法务部",
          status: "",
          description: "",
        },
        {
          name: "人力资源",
          status: "",
          description: "",
        },
        {
          name: "方案入档",
          status: "success",
          description: "",
        },
      ],
      // 表单参数
      form: {
        name: "",
        statusTime: "",
        diskPath: "",
        reason: "",
        step: 0,
        deptName: "",
      },
      templateForm: {},
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      uploadFileUrl: getBaseUrl() + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: "",
        deptId: [],
        status: "",
      },
      templateParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        // deptName: [
        //   { required: true, message: "岗位名称不能为空", trigger: "blur" },
        // ],
        // postCode: [
        //   { required: true, message: "岗位编码不能为空", trigger: "blur" },
        // ],
        // postSort: [
        //   { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        // ],
      },
    };
  },
  created() {
    this.initYear();
    this.getList();
    this.getDeptTree();
  },
  methods: {
    // 发送邮件
    handleCommand(command, row) {
      const params = {
        content: "",
        serviceId: row.id,
        serviceType: "",
      };
      this.$confirm("是否发送？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          switch (command) {
            case "handleAuditor":
              params.serviceType = "programme_approve";
              sendMailFile(params).then(() => {
                this.$modal.msgSuccess("发送成功");
              });
              break;
            case "handlePrepared":
              params.serviceType = "programme_create_user";
              sendMailFile(params).then(() => {
                this.$modal.msgSuccess("发送成功");
              });
              break;
            default:
              break;
          }
        })
        .catch(() => false);
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    initYear() {
      let _now = new Date();
      let currentYear = _now.getFullYear();
      this.valueYear = `${currentYear}`;
    },
    handleApprove(row) {
      const params = {
        id: row.id,
        status: row.status === 1 ? 2 : 1,
      };
      approve(params).then(() => {
        this.getTemplateList();
      });
    },
    createTemplate() {
      this.establishDialog = true;
    },
    handleTemplateManagement() {
      this.templateManagementDialog = true;
      this.getTemplateList();
    },
    getTemplateList() {
      listProgrammeTemplate(this.templateParams).then((response) => {
        this.templateList = response.rows;
        this.templateTotal = response.total;
      });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = ["docx", "xls", "xlsx", "pdf"].indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${["docx", "xls", "xlsx", "pdf"].join("/")}格式文件!`);
          return false;
        }
      return true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      // this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadList.push({
        name: response.originalFilename,
        url: response.fileName,
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const deptId =
        this.queryParams.deptId[this.queryParams.deptId.length - 1];
      const dateRange = [`${this.valueYear}-01-01`, `${this.valueYear}-12-31`];
      listProgramme(
        this.addDateRange({ ...this.queryParams, deptId }, dateRange)
      ).then((response) => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelEstablish() {
      this.establishDialog = false;
      this.resetForm("templateForm");
      this.fileList = [];
      this.uploadList = [];
      this.templateForm = this.$options.data().templateForm;
    },
    addTemplate() {
      addProgrammeTemplate({
        ...this.templateForm,
        diskPath: this.uploadList[0].url,
      }).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.cancelEstablish();
        this.getTemplateList();
      });
    },
    // 表单重置
    reset() {
      this.form = {
        name: "",
        statusTime: "",
        diskPath: "",
        reason: "",
        step: 0,
        deptName: "",
      };
      this.textarea = "";
      this.fileList = [];
      this.uploadList = [];
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = this.$options.data().queryParams;
      this.initYear();
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.establishDialog = true;
    },
    /** 查看 */
    handleCheck(row) {
      const postId = row.id;
      getProgramme(postId).then((response) => {
        this.form = response.data;
        this.checkDialog = true;
        this.title = "查看";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(type, title, row) {
      this.title = title;
      this.type = type;
      if (type === "add") {
        this.open = true;
        return;
      }
      this.rowId = row.id;
      const stepColor = {
        1: "finish",
        3: "success",
        4: "error",
      };

      const stepName = {
        1: "待审核",
        3: "已通过",
        4: "驳回",
      };
      getProgramme(this.rowId).then((response) => {
        const { statusHr, statusIcfa, step, reasonIcfa, reasonHr } =
          response.data;
        this.textarea =
          statusHr === 4 ? reasonHr : statusIcfa === 4 ? reasonIcfa : "";
        this.form = response.data;
        this.stepList = [
          {
            name: "内控法务部",
            status: stepColor[statusIcfa],
            description: stepName[statusIcfa],
          },
          {
            name: "人力资源",
            status: stepColor[statusHr],
            description: stepName[statusHr],
          },
          {
            name: "方案入档",
            status: step === 3 ? "success" : "",
            description: "",
          },
        ];
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm: function (type) {
      if (type === 4 && !this.textarea) {
        this.$modal.msgWarning("请输入不通过理由");
        return;
      }
      if (this.form.step === 2) {
        const params = {
          reasonHr: this.textarea,
          statusHr: type,
        };
        approveHr({ ...params, id: this.rowId }).then((response) => {
          this.$modal.msgSuccess("保存成功");
          this.open = false;
          this.getList();
        });
      } else if (this.form.step === 1) {
        const params = {
          reasonIcfa: this.textarea,
          statusIcfa: type,
        };
        approveIcfa({ ...params, id: this.rowId }).then((response) => {
          this.$modal.msgSuccess("保存成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 提交按钮 */
    submitForm1: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.type === "edit") {
            updateProgramme({
              name: this.form.name,
              diskPath: this.uploadList[0]?.url,
              id: this.rowId,
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.getList();
            });
          } else {
            addProgramme({
              name: this.form.name,
              diskPath: this.uploadList[0]?.url,
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delProgramme(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 删除按钮操作 */
    handelDelTemplate(row) {
      const postIds = row.id;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delProgrammeTemplate(postIds);
        })
        .then(() => {
          this.getTemplateList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },

    handelPrevie(path) {
      getBase64({ path }).then((res) => {
        let wj = encodeURIComponent(res.msg);
        wj = decodeURIComponent(wj);
        const myBlob = this.dataURLtoBlob(wj);
        this.previewUrl = myBlob;
        this.previewType = this.iconByType(
          path.split(".")[path.split(".").length - 1]
        );
        this.filename = this.getFileName(path);
        this.previewAnnex = true;
      });
    },

    handleDown(path) {
      getBase64({ path }).then((res) => {
        let wj = encodeURIComponent(res.msg);
        wj = decodeURIComponent(wj);
        const myBlob = this.dataURLtoBlob(wj);
        this.previewUrl = myBlob;
        this.previewType = this.iconByType(
          path.split(".")[path.split(".").length - 1]
        );
        this.filename = this.getFileName(path);
        this.handleDownload();
      });
    },
    // 获取文件后缀名
    iconByType(filename) {
      return filename.substring(filename.lastIndexOf(".") + 1, filename.length);
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    dataURLtoBlob(dataurl) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    handleDownload() {
      // 生成地址
      var myUrl = URL.createObjectURL(this.previewUrl);

      // 下载文件
      this.downloadFile(myUrl, this.filename);
    },
    downloadFile(url, name) {
      const a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("download", name);
      a.setAttribute("target", "_blank");
      const clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },
    downloadTemplate() {
      download.resource("/template/附件1.《岗位责任制检查方案》（模板）.doc");
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}

// ::v-deep .el-step.is-simple .el-step__head {
//   display: flex;
// }
</style>
