<template>
  <div class="app-container">
    <!-- <iframe
          ref="iframe"
          class="node-editor__iframe"
          frameborder="0"
          src="https://juejin.cn/user/818508066730008"
          style="width: 150px;height: 100px;"
        /> -->
    <el-form ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="岗位名称：">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在部门：">
        <el-cascader
          style="width: 300px"
          v-model="unitId1"
          :options="postOptions"
          @change="handleChange"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="是否涉密：">
        <el-select
          v-model="queryParams.isConfidential"
          placeholder="请选择是否涉密"
          clearable
        >
          <el-option label="是" value="是"></el-option>
          <el-option label="否" value="否"></el-option>
        </el-select>
      </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="$router.push(`/postResponsibility/assign?type=2`)"
          >批量修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="$router.push(`/postResponsibility/assign?type=1`)"
          >批量新建</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" @click="doAdd(`新建`, 0)">新建</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" @click="importWen = true">批量导入</el-button>
      </el-col>
    </el-row>

    <el-table
      border
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      height="calc(100% - 150px)"
    >
      <el-table-column
        label="全选/反选"
        type="selection"
        width="60"
        align="center"
      >
      </el-table-column>
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          <span>{{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在单位" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.unitId ? scope.row.unitId : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在部门" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.deptName ? scope.row.deptName : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="岗位名称" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.postName ? scope.row.postName : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否涉密" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
            scope.row.isConfidential ? scope.row.isConfidential : '--'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="直接上级" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
            scope.row.directSuperior ? scope.row.directSuperior : '--'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="直接下级" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
            scope.row.directSubordinate ? scope.row.directSubordinate : '--'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管辖人数" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{
            scope.row.subordinateCount ? scope.row.subordinateCount : '--'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="编制/修订日期"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.revisionDate
              ? scope.row.revisionDate
              : scope.row.creationDate || '-'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ initStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="
              $router.push(
                `/postResponsibility/postResponsibilityOrganizationLook?id=${scope.row.id}&type=1`
              )
            "
            >查看</el-button
          >
          <el-button type="text" @click="doAdd(`修改`, scope.row.id)"
            >修改</el-button
          >
          <el-button type="text" @click="doDel(scope.row.id)">删除</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"
    />

    <!-- 新建的dialog -->
    <AddDialog
      :dialogVisible="dialogVisible"
      @closeDialog="closeDialog"
      v-if="dialogVisible"
      :ids="ids"
      :title="title"
    />

    <!-- 导入文件 -->
    <el-dialog
      v-dialogDrag
      v-loading="loading"
      v-if="importWen"
      title="批量导入"
      :visible.sync="importWen"
      width="40%"
      :close-on-click-modal="false"
      :before-close="cancelCredent"
    >
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" label-position="right" label-width="200px">
            <el-form-item label="导入文件：">
              <el-upload
                ref="upload"
                drag
                class="upload-demo"
                :action="uploadFileUrl"
                multiple
                accept=".xls, .xlsx"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :on-success="uploadHttpRequest1"
                :on-remove="removeContractAttachment"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <span
          class="download"
          style="
            cursor: pointer;
            width: 100px;
            margin-left: 200px;
            color: #0c80ea;
          "
          @click="handleDown(`/template/岗位责任清单-XX岗位-模板.xlsx`)"
          >下载模板</span
        >
      </el-row>
      <div style="margin-top: 20px; margin-left: 200px; color: #c7bd78">
        提示:请先按照导出模版文件填写后进行上传
      </div>
      <el-row style="text-align: right; margin-top: 50px; padding-top: 10px">
        <el-button @click="cancelCredent"> 取消 </el-button>
        <el-button
          style="margin-right: 10px"
          type="primary"
          @click="confirmCredent"
        >
          确定
        </el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  postCheckListList,
  deptTree,
  postCheckListDel,
  getBase64,
  upload,
  batchlmport
} from '@/api/allApi/index.js'
import AddDialog from './addDialog.vue'

export default {
  name: 'PostResponsibilityMeun',
  components: {
    AddDialog
  },
  data() {
    return {
      uploadFileUrl: this.getBaseUrl() + "/common/upload",
      uploadList:[],
      queryParams: {
        postName: '',
        status: 1,
        deptId: '',
        isConfidential: '',
        pageNum: 1,
        pageSize: 10
      },
      // 文件预览
      previewAnnex: false,
      previewUrl: '',
      previewType: '',
      filename: '',

      unitId1: [],
      tableData: [],
      total: 0,
      loading: false,
      showSearch: true,
      postOptions: [],

      dialogVisible: false,
      ids: '',
      title: '',
      importWen: false,
      fileList: [],
      whiteList: ['xlsx', 'xls']
    }
  },

  mounted() {
    this.initDeptTree()
    this.getList()
  },

  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      postCheckListList(this.queryParams).then((response) => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.unitId1 = []
      this.queryParams = {
        postName: '',
        status: 1,
        deptId: '',
        isConfidential: '',
        pageNum: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    async initDeptTree() {
      const res = await deptTree()
      if (res.code !== 200) return this.$message.error(res.msg)
      this.postOptions = res.data
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    closeDialog() {
      this.dialogVisible = false
      this.handleQuery()
    },
    // 选择部门
    handleChange(value) {
      this.queryParams.deptId = value[value.length - 1]
    },
    initStatus(val) {
      switch (val) {
        case 0:
          return '待提交'
        case 1:
          return '待审核'
        case 2:
          return '审核中'
        case 3:
          return '通过'
        case 4:
          return '驳回'
      }
    },
    doAdd(title, id) {
      this.ids = id
      this.title = title
      setTimeout(() => {
        this.dialogVisible = true
      }, 100)
    },
    doDel(id) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await postCheckListDel(id)
          if (res.code !== 200) return this.$message.error(res.msg)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 导入证件文件取消按钮
    cancelCredent() {
      this.importWen = false
      this.uploadList = []
      this.fileList = []
      // 清除上传的文件数据
      this.$refs.upload.clearFiles()
    },
    async confirmCredent() {
      if (this.uploadList.length === 0) return this.$message.error('文件必传')
      // 调用上传文件接口
      const res  = await batchlmport(this.uploadList);
      if (res.code != 200) return this.$message.error(res.msg)
        this.$message.success('导入成功')
        // 清除校验记录
        this.importWen = false
        this.getList()
        this.fileList = []
        this.uploadList = []

    },
    // 文件上传前
    async uploadHttpRequest1(response, file, fileList) {
      this.uploadList.push(response.fileName)
    },
    // 上传格式校验
    beforeUpload(file) {
      const end = file.name.split('.')[file.name.split('.').length - 1]
      if (!this.whiteList.includes(end)) {
        this.$message.error('文件格式错误')
        return false
      }
      return true
    },
    // 复审导入的移出
    removeContractAttachment(file, fileList) {
      this.fileList = fileList
      this.uploadList =  this.uploadList.filter(item=>item !== file.response.fileName)
    },
    // 下载模板
    downZ() {
      // const hrefStr = encodeURI(`${this.baseUrl}static/upload/file/取证导入.xlsx`);
      window.location.href = hrefStr
    },
    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>
</style>
