<template>
  <div class="app-container resetStyle">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="工作组：">
        <el-select
          v-model="queryParams.checkGroupId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门：">
        <el-cascader
          v-model="queryParams.checkedDeptId"
          :options="deptTreeList"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="岗位：">
        <el-input
          v-model="queryParams.checkedPostNames"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="岗检状态：">
        <el-select v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="(item, key) in status"
            :key="key"
            :label="item"
            :value="key"
          >
          </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-table border v-loading="loading" :data="postList" height="calc(100% - 150px)">
      <el-table-column label="序号" align="center" type="index" width="80" />
      <!-- <el-table-column label="部门属性" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedDeptTypeView || "--" }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="工作组" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkGroupName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查小组" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkTeamName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="受检部门" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedDeptName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="受检岗位" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkedPostNames || "--" }}</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.checkedUserName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检查时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.checkTime || "--" }}</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
            v-if="scope.row.status === 1"
            type="text"
            @click="handleCheck(scope.row, '岗检完成确认')"
            >岗检完成确认</el-button
          >
          <el-button
            v-if="scope.row.status === 2"
            type="text"
            @click="handleCheck(scope.row, '重新上传')"
            >重新上传</el-button
          >
          <el-button
            v-if="scope.row.checkedImg"
            type="text"
            @click="handelPrevie(scope.row.checkedImg)"
            >预览</el-button
          >
        </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.sync="establishDialog"
      width="700px"
      @close="cancelEstablish"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="250px">
        <el-form-item
          label="检查人："
          prop="checkedUserName"
          v-if="title !== '重新上传'"
        >
          <el-input v-model="form.checkedUserName" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          label="检查时间："
          prop="checkedTime"
          v-if="title !== '重新上传'"
        >
          <el-date-picker
            style="width: 100%"
            v-model="form.checkedTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上传岗检记录(岗检表签字扫描件)：" prop="postCode">
          <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="submitForm">确认</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>
    <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 {
  postPlanAffirm,
  imgReUpload,
  getPostPlanList,
} from "@/api/postImplementation/problemEntry.js";
import {
  getBase64,
} from "@/api/postInspectionPlanning/projectManagement.js";
import { listGroupList, getDeptTree } from "@/api/postInspectionPlanning/teamManagement.js";
import { getToken } from "@/utils/auth";
import  { getBaseUrl } from '@/utils/baseUrl.js'

export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      valueYear: "",
      fileList: [],
      uploadList: [],
      groupList: [],
      deptTreeList: [],
      postId: "",
      checkDialog: false,
      // 文件预览
      previewAnnex: false,
      previewUrl: "",
      previewType: "",
      filename: "",
      active: 0,
      establishDialog: false,
      options: [
        {
          value: "选项1",
          label: "待审核",
        },
        {
          value: "选项2",
          label: "已通过",
        },
        {
          value: "选项3",
          label: "未通过",
        },
      ],
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],

      status: {
        1: "未检",
        2: "已检",
      },
      statusColor: {
        1: "red",
        2: "#cdd152",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      uploadFileUrl: getBaseUrl() + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        checkGroupId: "",
        checkedPostNames: "",
        checkedDeptId: [],
        status: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // postName: [
        //   { required: true, message: "岗位名称不能为空", trigger: "blur" },
        // ],
        // postCode: [
        //   { required: true, message: "岗位编码不能为空", trigger: "blur" },
        // ],
        // postSort: [
        //   { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        // ],
      },
    };
  },
  created() {
    this.initYear();
    this.getList();
    this.getGroupList();
    this.getDeptTree();
  },
  methods: {
    initYear() {
      let _now = new Date();
      let currentYear = _now.getFullYear();
      this.valueYear = `${currentYear}`;
    },
    getDeptTree() {
      getDeptTree().then((data) => {
        this.deptTreeList = data.data;
      });
    },
    getGroupList() {
      listGroupList().then((data) => {
        this.groupList = data.data;
      });
    },
    // 上传前校检格式和大小
    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) {},
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadList.push({
        name: response.originalFilename,
        url: response.fileName,
      });
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const checkedDeptId = this.queryParams.checkedDeptId[this.queryParams.checkedDeptId.length - 1];
      const dateRange = [`${this.valueYear}-01-01`, `${this.valueYear}-12-31`];
      getPostPlanList(this.addDateRange({...this.queryParams, checkedDeptId}, 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.reset();
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form;
      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.handleQuery();
    },

    /** 查看 */
    handleCheck(row, title) {
      this.establishDialog = true;
      this.title = title;
      this.postId = row.planInfoId;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title === "重新上传") {
            imgReUpload({
              checkedImg: this.uploadList[0].url,
              planInfoId: this.postId,
            }).then((response) => {
              this.$modal.msgSuccess("已上传");
              this.cancelEstablish();
              this.getList();
            });
          } else {
            postPlanAffirm({
              ...this.form,
              checkedImg: this.uploadList[0].url,
              planInfoId: this.postId,
            }).then((response) => {
              this.$modal.msgSuccess("已上传");
              this.cancelEstablish();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$modal
        .confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？')
        .then(function () {
          return delPost(postIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },

    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);
    },
    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);
    },
  },
};
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
</style>
