<template>
  <div class="app-container">
    <el-form label-width="100px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="被检查单位">
            <el-input v-model="search.INSPECTED_DEPARTMENT_NAME" placeholder="被检查单位..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查部门">
            <el-input v-model="search.INSPECTION_DEPARTMENT_NAME" placeholder="检查部门..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查发起人">
            <el-input v-model="search.INSPECTION_ORIGINATOR_NAME" placeholder="检查发起人..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查类型">
            <SelectTree
              ref="tree_InspectionType"
              :clearable="false"
              :options="inspectionTypeList"
              :props="defaultProps"
              v-model="search.INSPECTION_TYPE"
              :canparent="false"
              placeholder="这里选择检查类型..."
              children-name="nodes" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查时间">
            <el-date-picker
              v-model="search.INSPECTION_TIME"
              style="width: 100%;"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <el-form-item label="检查状态">
            <el-select v-model="search.INSPECTION_STATUS" placeholder="检查状态" clearable style="width: 100%">
              <el-option :value="0" label="待检查人核实"/>
              <el-option :value="1" label="检查人核实中"/>
              <el-option :value="2" label="待被检查人确认"/>
              <el-option :value="3" label="待指派"/>
              <el-option :value="-1" label="检查人核实打回"/>
              <el-option :value="-2" label="被检查人申辩"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查题目">
            <el-select v-model="search.INSPECTION_SUBJECT" placeholder="检查题目" clearable style="width: 100%">
              <el-option v-for="item in INSPECTION_SUBJECT_LIST" :key="item.ID" :label="item.NAME" :value="item.ID" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button v-waves type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" fixed="left" />
      <el-table-column prop="INSPECTED_DEPARTMENT_NAMES" width="200" label="被检查单位" align="center" />
      <el-table-column prop="INSPECTED_SITEUSER_NAME" width="200" label="被检查单位现场负责人" align="center" />
      <el-table-column prop="INSPECTION_LEADDEPARTMENT_NAME" width="150" label="检查部门" align="center" />
      <el-table-column prop="INSPECTION_ORIGINATOR_NAME" label="检查发起人" align="center" />
      <!--      <el-table-column prop="INSPECTED_SITEUSER_NAME" label="被检查单位现场负责人" align="center" />-->
      <el-table-column prop="INSPECTION_TYPE_NAME" label="检查类型" align="center" />
      <!--      <el-table-column prop="INSPECTION_PLACE" label="检查场所" />-->
      <el-table-column label="检查时间" width="280" align="center" >
        <template slot-scope="{row}">
          <span>自 {{ row.INSPECTION_TIME_START }} 至 {{ row.INSPECTION_TIME_END }} 止</span>
        </template>
      </el-table-column>
      <el-table-column prop="INSPECTION_STATUS" label="状态" align="center" >
        <template slot-scope="{row}">
          <template v-if="row.INSPECTION_STATUS == '0'">待检查人核实</template>
          <template v-else-if="row.INSPECTION_STATUS == '1'">检查人核实中</template>
          <template v-else-if="row.INSPECTION_STATUS == '2'">待被检查人确认</template>
          <template v-else-if="row.INSPECTION_STATUS == '3'">待指派</template>
          <template v-else-if="row.INSPECTION_STATUS == '4'">指派中</template>
          <template v-else-if="row.INSPECTION_STATUS == '5'">指派完成</template>
          <template v-else-if="row.INSPECTION_STATUS == '6'">检查待验收</template>
          <template v-else-if="row.INSPECTION_STATUS == '7'">检查已验收</template>
          <template v-else-if="row.INSPECTION_STATUS == '8'">已归档</template>
          <template v-else-if="row.INSPECTION_STATUS == '-1'">检查人核实打回</template>
          <template v-else-if="row.INSPECTION_STATUS == '-2'">被检查人申辩</template>
        </template>
      </el-table-column>
      <el-table-column prop="INSPECTION_SUBJECT" label="检查题目" align="center" width="200"/>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="{row}">
          <el-button icon="el-icon-view" size="mini" @click="goDetail(row)">查看</el-button>
          <el-button
            v-show="edit && row.INSPECTION_STATUS == '2'"
            v-if=" row.INSPECTED_SITEUSER_ID === loginUserId"
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleConfirm(row)">确认</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-btn-group">
      <div/>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :visible.sync="dialogFormEdit" title="检查确认" width="600px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;">
        <el-form-item label="是否申辩" prop="INSPECTED_EXPLAIN">
          <el-radio v-model="form.INSPECTION_STATUS" label="3">否</el-radio>
          <el-radio v-if="count=='1'" v-model="form.INSPECTION_STATUS" label="-2">是</el-radio>
        </el-form-item>
        <el-form-item v-if="form.INSPECTION_STATUS === '-2'" label="申辩内容" prop="INSPECTED_EXPLAIN">
          <el-input v-model="form.INSPECTED_EXPLAIN" :autosize="{ minRows: 1}" type="textarea" maxlength="2000" placeholder="这里输入申辩内容..."/>
        </el-form-item>
        <el-form-item v-if="form.INSPECTION_STATUS === '-2'" label="附件路径">
          <div class="uo-flex">
            <el-input v-model="form.INSPECTED_EXPLAIN_FILENAME" :disabled="true" title="请上传附件" />
            <el-upload
              :before-upload="beforeFileUpload"
              class="avatar-uploader"
              accept=".pdf">
              <el-button type="primary" icon="el-icon-upload" style="margin-left:10px; ">上传附件</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="确认人">
          <el-button data-target="Modal" type="primary" @click="showModal">手写签字</el-button>
        </el-form-item>
        <div v-show="form.INSPECTED_SITEUSER_SIGN_IMG != ''" class="demo-image__preview">
          <el-image
            :src="form.INSPECTED_SITEUSER_SIGN_IMG"
            style="width: 300px; height: 200px;border:1px solid #eee;margin-left:110px"/>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogWriteSign" title="手写签字" width="600px" @close="dialogWriteSign = false">
      <WriteSign :width="600" :height="300" @subCanvas="subCanvas"/>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import WriteSign from '@/components/WriteSign'
import waves from '@/directive/waves' // waves directive
import { upload } from '@/utils/upload'
import formatDate from '@/utils/dateformat'
import SelectTree from '@/components/SelectTree'

export default {
  components: { Pagination, WriteSign, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      count: '',
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      loginUserId: '', // 登录人ID
      search: {
        INSPECTED_SITEUSER_ID: '',
        INSPECTED_DEPARTMENT_NAME: '', // 被检查单位
        INSPECTION_DEPARTMENT_NAME: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_SUBJECT: '', // 检查题目
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_STATUS: '' // 检查状态
      },
      INSPECTION_SUBJECT_LIST: [
        { ID: '安全', NAME: '安全' },
        { ID: '环保', NAME: '环保' },
        { ID: '综合', NAME: '综合' }
      ],
      inspectionTypeList: [],
      varList: [],
      form: {
        INSPECTION_STATUS: '3',
        INSPECTION_ID: '', // 安全环保检查ID
        INSPECTED_EXPLAIN: '', // 申辩内容
        INSPECTED_EXPLAIN_FILENAME: '', // 申辩附件名称
        INSPECTED_SITEUSER_SIGN_IMG: '', // 被检查单位现场负责人签字
        INSPECTED_SITEUSER_SIGN_TIME: '', // 被检查单位现场负责人签字时间
        file: '' // 申辩附件
      },
      dialogFormEdit: false,
      rules: {
        INSPECTION_ID: [{ required: true, message: '安全环保检查ID不能为空', trigger: 'blur' }]
      },
      dialogWriteSign: false,
      defaultProps: { value: 'id', children: 'nodes', label: 'name' }
    }
  },
  watch: {
    'form.INSPECTION_STATUS': {
      handler(val) {
        if (val === '-2') {
          this.form.INSPECTED_EXPLAIN = ''
          this.form.INSPECTED_EXPLAIN_FILENAME = ''
          this.form.file = ''
        }
      },
      immediate: false
    }
  },
  created() {
    this.getDict()
    this.getList(this.ROLE_ID)
    this.getEditMyInfo()
  },
  methods: {
    /** 获取行数据 Key，用于优化 table 表格的渲染 */
    getRowKey(row) {
      return row.INSPECTION_ID
    },
    /** 获取登录人信息 */
    getEditMyInfo() {
      requestFN(
        '/user/goEditMyInfo',
        {}
      ).then((data) => {
        this.loginUserId = data.pd.USER_ID
        console.log(this.loginUserId)
        this.ISMAIN = data.pd.ISMAIN
        this.$forceUpdate()
      }).catch((e) => {

      })
    },
    /** 执行参数搜索 */
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    /** 执行重置 */
    goKeyReset() {
      this.resetSearch()
      this.getQuery()
    },
    /** 获取列表 */
    getList() {
      this.listLoading = true
      requestFN(
        '/safetyenvironmental/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          ...this.search,
          INSPECTION_TIME_START: this.search.INSPECTION_TIME[0],
          INSPECTION_TIME_END: this.search.INSPECTION_TIME[1]
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalCount
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })

      setTimeout(() => {
        this.listLoading = false
        this.varList = inspectedList
        this.total = inspectedList.length
      }, 400)
    },
    /** 查看 */
    goDetail(row) {
      this.$parent.activeName = 'InspectionInfo'
      this.$parent.INSPECTION_ID = row.INSPECTION_ID
    },
    /** 处理确认按钮 */
    handleConfirm(row) {
      this.resetForm(row)
      // this.hiddenCount(row.INSPECTION_ID)
      this.dialogFormEdit = true
    },
    /** 上传文件前的钩子处理函数 */
    beforeFileUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'pdf'
      if (!extension) {
        this.$message.error('上传文件只能是 PDF 格式!')
        return false
      } else {
        this.form.file = file
        this.form.INSPECTED_EXPLAIN_FILENAME = file.name
        this.$forceUpdate()
        return false
      }
    },
    /** 查询安环检查是否有隐患 */
    hiddenCount(INSPECTION_ID) {
      this.listLoading = true
      requestFN(
        '/safetyenvironmental/hiddencount',
        {
          INSPECTION_ID: INSPECTION_ID
        }
      ).then((data) => {
        this.listLoading = false
        this.count = data.hiddencount
      }).catch((e) => {
        this.listLoading = false
      })
    },
    /** 手写板弹框打开 */
    showModal() {
      this.dialogWriteSign = true
    },
    /** 手写板完成 */
    subCanvas(img64) {
      console.info('img64：' + img64)
      this.form.INSPECTED_SITEUSER_SIGN_IMG = img64
      this.$set(this.form, 'INSPECTED_SITEUSER_SIGN_TIME', formatDate(new Date(), 'YYYY-MM-DD HH:mm'))
      console.info(this.form)
      this.dialogWriteSign = false
    },
    /** 表单保存 */
    confirm(INSPECTION_STATUS) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.INSPECTION_STATUS === '-2') {
            if (!this.validStr(this.form.INSPECTED_EXPLAIN)) {
              this.$message.warning('申辩时，申辩内容不能为空')
              return false
            }
          }
          if (!this.validStr(this.form.INSPECTED_SITEUSER_SIGN_IMG)) {
            this.$message.warning('请在确认人签字处签字！')
            return false
          }
          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.listLoading = true
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          upload(
            '/safetyenvironmentalexplain/add',
            formData
          ).then((data) => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.listLoading = false
            loading.close()
            this.dialogFormEdit = false
            this.getQuery()
          }).catch((e) => {
            this.listLoading = false
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    /** 判断按钮权限，用于是否显示按钮 */
    hasButton() {
      var keys = 'safetyenvironmentalinspector:add,safetyenvironmentalinspector:del,safetyenvironmentalinspector:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.safetyenvironmentalinspectorfhadminadd		// 新增权限
        this.del = data.safetyenvironmentalinspectorfhadmindel		// 删除权限
        this.edit = data.safetyenvironmentalinspectorfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    /** 获取数据字典数据 */
    getDict() {
      requestFN(
        '/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
        }
      ).then((data) => {
        this.inspectionTypeList = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    /** 重置搜索状态 */
    resetSearch() {
      this.search = {
        INSPECTED_DEPARTMENT_NAME: '', // 被检查单位
        INSPECTION_DEPARTMENT_NAME: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_SUBJECT: '', // 检查题目
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_STATUS: '' // 检查状态
      }
      this.$refs.tree_InspectionType.clearHandle()
    },
    /** 重置表单数据 */
    resetForm(row) {
      this.form = {
        INSPECTION_STATUS: '3',
        INSPECTION_ID: row.INSPECTION_ID, // 安全环保检查ID
        INSPECTED_EXPLAIN: '', // 申辩内容
        INSPECTED_EXPLAIN_FILENAME: '', // 申辩附件名称
        INSPECTED_SITEUSER_SIGN_IMG: '', // 被检查单位现场负责人签字
        INSPECTED_SITEUSER_SIGN_TIME: '', // 被检查单位现场负责人签字时间
        file: '' // 申辩附件
      }
    },
    /** 格式化日期时间 */
    formatDate(date, format) {
      return formatDate(date, format)
    }
  }
}
</script>
<style lang="scss" scoped>
  .uo-flex {
    display: flex;
  }
</style>
