<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
    >
      <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="handleCheck('add', '新增')"
          v-hasPermi="['system:post:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <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.reportNo || '--' }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="岗检报告名称" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.reportName || '--' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="完整性问题" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.reportName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适宜性问题" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.reportName || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="有效性问题"
        align="center"
        prop="problemAttribute"
      >
        <template slot-scope="{ row }">
          <span>{{ row.reportName || "--" }}</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
            v-if="row.diskPath"
            >{{ initUrl(row.diskPath) }}</span
          >
          <span v-else> -- </span>
        </template>
      </el-table-column>
      <el-table-column label="存档时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleCheck('edit', '修改', scope.row)"
            v-hasPermi="['system:post:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            @click="
              $router.push(
                `/jobinspectionHistory/jobinspectionHistoryLook?id=${scope.row.id}`
              )
            "
            >查看</el-button
          >
          <el-button
            type="text"
            @click="doLook(scope.row.diskPath)"
            >预览</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            >删除</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="open"
      width="800px"
      class="reset-dialog"
      @close="cancel"
    >
      <div class="shengc">
        <el-form
          ref="form"
          :model="form"
          :disabled="type === 'check'"
          label-width="100px"
        >
          <el-form-item label="报告名称：">
            <el-input
              v-model="form.reportName"
              placeholder="请输入报告名称"
              style="width: 80%"
            />
          </el-form-item>
          <el-form-item label="报告类型：">
            <el-select
              v-model="form.type"
              placeholder="请选择报告类型"
              style="width: 80%"
            >
              <el-option
                label="综合岗检工作组（职能部门）"
                :value="1"
              ></el-option>
              <el-option
                label="生产岗检工作组（生产部门"
                :value="2"
              ></el-option>
              <el-option label="联合办公室" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件地址：">
            <el-upload
              ref="upload"
              :limit="1"
              accept=""
              :action="uploadFileUrl"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :headers="headers"
              :file-list="fileList"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <!-- <div v-if="reason || type === 'edit'">
          <h3>不通过理由</h3>
          <el-input
            style="width: 500px"
            v-model="reason"
            placeholder="请输入"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            disabled
          />
        </div> -->
        <div class="footer-button" v-if="type === 'edit' || type === 'add'">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="查看" :visible.sync="checkDialog" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="提交部门：" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="方案名称：" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="文件名称：" prop="remark">
          <el-link type="primary">主要链接</el-link>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="创建" :visible.sync="establishDialog" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="方案名称：" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="上传附件：" prop="postCode">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </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="cancel">取 消</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 {
  listCheckedReport,
  getCheckedReport,
  delCheckedReport,
  addCheckedReport,
  updateCheckedReport,
  statusApprove,
  problemCategoryByAttribute
} from '@/api/postImplementation/reportManagement.js'
import { getToken } from '@/utils/auth'
import { getBase64 } from '@/api/postInspectionPlanning/projectManagement.js'
import  { getBaseUrl } from '@/utils/baseUrl.js'
export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      valueYear:"",
      reason: '',
      row: {},
      problemList: [],
      type: '',
      checkDialog: false,
      templateManagementDialog: false,
      textarea2: '',
      // 文件预览
      previewAnnex: false,
      previewUrl: '',
      previewType: '',
      filename: '',
      active: 0,
      establishDialog: false,
      options: [
        {
          value: 1,
          label: '综合岗检工作组'
        },
        {
          value: 2,
          label: '生产岗检工作组'
        },
        {
          value: 3,
          label: '联合办公室'
        }
      ],
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      status: {
        1: '待审核',
        2: '审核中',
        3: '通过',
        4: '驳回'
      },
      statusColor: {
        1: '#cdd152',
        2: '#61dd83',
        3: '#61dd83',
        4: 'red'
      },
      title: '',
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: getBaseUrl() + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        reportName: '',
        type: ''
      },
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      uploadList: [],
      fileList: [],
      uploadFileUrl: getBaseUrl() + '/common/upload',
      // 表单校验
      rules: {
        postName: [
          { required: true, message: '岗位名称不能为空', trigger: 'blur' }
        ],
        postCode: [
          { required: true, message: '岗位编码不能为空', trigger: 'blur' }
        ],
        postSort: [
          { required: true, message: '岗位顺序不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.initYear();
    this.getList()
    problemCategoryByAttribute().then((res) => {
      this.problemList = res.data
    })
  },
  methods: {
    handleTemplateManagement() {
      this.templateManagementDialog = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {},
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code != 200) return this.$message.error(response.msg)
      // this.$refs.upload.clearFiles();
      this.uploadList.push({
        name: response.originalFilename,
        url: response.fileName
      })
      console.log(response, this.fileList, 'response')
      // this.$alert(
      //   "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      //     response.msg +
      //     "</div>",
      //   "导入结果",
      //   { dangerouslyUseHTMLString: true }
      // );
      // this.getList();
    },
    // 文件上传成功处理
    // handleFileSuccess(response, file, fileList) {
    //   this.upload.open = false
    //   this.upload.isUploading = false
    //   this.$refs.upload.clearFiles()
    //   this.$alert(
    //     "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    //       response.msg +
    //       '</div>',
    //     '导入结果',
    //     { dangerouslyUseHTMLString: true }
    //   )
    //   this.getList()
    // },
    initYear() {
      let _now = new Date();
      let currentYear = _now.getFullYear();
      this.valueYear = `${currentYear}`;
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      const dateRange = [`${this.valueYear}-01-01`, `${this.valueYear}-12-31`];
      listCheckedReport(this.addDateRange(this.queryParams, dateRange)).then((response) => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.fileList = []
      this.uploadList = []
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = this.$options.data().form
      this.reason = ''
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.initYear();
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.establishDialog = true
    },
    /** 查看 */
    handleCheck(type, title, row) {
      this.type = type
      this.title = title
      if (this.title !== '新增') {
        getCheckedReport(row.id).then((response) => {
          const dateRange = [response.data.startTime, response.data.endTime]
          this.form = { ...response.data, dateRange }
          this.reason = response.data.reason
          this.open = true
          this.row = row
          let str =
            response.data.diskPath.split('/')[
              response.data.diskPath.split('/').length - 1
            ]
          let one = str.split('_')[0]
          let two = str.split('_')[1].split('.')[1]
          this.fileList.push({
            name: one + '.' + two
          })
          this.uploadList.push({
            name: one + '.' + two,
            url: response.data.diskPath
          })
        })
      } else {
        this.open = true
      }
    },
    doLook(val) {
      if(!val) return this.$message.warning("暂无文件")
      getBase64({ path: val }).then((res) => {
        let wj = encodeURIComponent(res.msg)
        wj = decodeURIComponent(wj)
        const myBlob = this.dataURLtoBlob(wj)
        this.previewUrl = myBlob
        this.previewType = this.iconByType(
          val.split('.')[val.split('.').length - 1]
        )
        this.filename = name
        this.previewAnnex = true
      })
    },
    // 获取文件后缀名
    iconByType(filename) {
      return filename.substring(filename.lastIndexOf('.') + 1, filename.length)
    },
    handleDownload() {
      // 生成地址
      const myUrl = URL.createObjectURL(this.previewUrl)
      // 下载文件
      this.downloadFile(myUrl, this.filename)
    },
    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 })
    },
    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)
    },
    initUrl(val) {
      let str = val.split('/')[val.split('/').length - 1]
      let one = str.split('_')[0]
      let two = str.split('_')[1].split('.')[1]
      return one + '.' + two
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row, 888)
      this.reset()
      const postId = row.postId || this.ids
      getPost(postId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改'
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.uploadList, 999)
      // const startTime = this.form?.dateRange[0]
      // const endTime = this.form?.dateRange[1]
      console.log(this.uploadList, 888)
      const params = {
        ...this.form,
        diskPath: this.uploadList[0].url
      }
      if (this.type === 'edit') {
        updateCheckedReport({ ...params, id: this.row.id }).then((response) => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        })
      } else {
        addCheckedReport(params).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      }
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      //     if (this.form.postId != undefined) {
      //       updatePost(this.form).then((response) => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addPost(this.form).then((response) => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id
      this.$modal
        .confirm('是否确认删除？')
        .then(function () {
          return delCheckedReport(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)
    },
    // 上传格式校验
    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
    },
    // 文件上传前
    uploadHttpRequest1(file) {
      this.fileList.push({
        name: file.file.name
      })
      // 判断是否为excel文件
      const formdata = new FormData()
      formdata.append('file', file.file)
      this.formdata = formdata
    }
  }
}
</script>
<style lang="scss" scoped>
.resetStyle {
  width: 100%;
  ::v-deep .el-upload {
    width: 100%;
    .el-upload-dragger {
      width: 100%;
    }
  }
}
.shengc {
  .footer-button {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
