<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" style="width: 140px;" placeholder="被检查单位..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查部门：">
            <el-input v-model="search.INSPECTION_DEPARTMENT_NAME" style="width: 140px;" placeholder="检查部门..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查发起人：">
            <el-input v-model="search.INSPECTION_ORIGINATOR_NAME" style="width: 140px;" placeholder="检查发起人..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查类型：">
            <el-select v-model="search.INSPECTION_TYPE" placeholder="检查类型..." clearable style="width: 100px" class="filter-item">
              <el-option v-for="item in inspectionTypeList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检查时间：">
            <el-date-picker
              v-model="search.INSPECTION_TIME"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="filter-item"/>
          </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: 110px" class="filter-item">
              <el-option v-for="item in statusList" :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 class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves class="filter-item" 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" />
      <el-table-column prop="INSPECTED_DEPARTMENT_NAMES" label="被检查单位" align="center" />
      <el-table-column prop="INSPECTION_LEADDEPARTMENT_NAME" label="检查部门" align="center" />
      <el-table-column prop="INSPECTION_ORIGINATOR_NAME" label="检查发起人" align="center" />
      <el-table-column prop="INSPECTION_TYPE_NAME" label="检查类型" align="center" />
      <el-table-column label="检查时间" width="260" 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 label="操作" align="center" width="200">
        <template slot-scope="{row}">
          <el-button icon="el-icon-view" size="mini" @click="goDetail(row)">查看</el-button>
          <el-button type="primary" @click="openTrajectory(row.INSPECTION_ID)">申辩记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-btn-group">
      <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="INSPECTION_USER_OPINION">
          <el-input v-model="form.INSPECTION_USER_OPINION" :autosize="{ minRows: 1}" type="textarea" maxlength="2000" placeholder="这里输入检查人意见（有异议时必填）..." title="检查人意见（有异议时必填）"/>
        </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.INSPECTION_USER_SIGN_IMG != ''" class="demo-image__preview">
          <el-image
            :src="form.INSPECTION_USER_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 type="danger" @click="confirm('-1')">不通过</el-button>
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm('1')">通 过</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>

    <trajectory ref="trakectory"/>
  </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 formatDate from '@/utils/dateformat'
import trajectory from './trajectory'

export default {
  components: { Pagination, WriteSign, trajectory },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      search: {
        INSPECTED_DEPARTMENT_NAME: '', // 被检查单位
        INSPECTION_DEPARTMENT_NAME: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_STATUS: '' // 检查状态
      },
      statusList: [
        { ID: '0', NAME: '待检查人核实' },
        { ID: '1', NAME: '检查人核实中' },
        { ID: '2', NAME: '待被检查人确认' },
        { ID: '3', NAME: '待指派' },
        { ID: '4', NAME: '指派中' },
        { ID: '5', NAME: '指派完成' },
        { ID: '6', NAME: '检查待验收' },
        { ID: '7', NAME: '检查已验收' },
        { ID: '8', NAME: '已归档' },
        { ID: '-1', NAME: '检查人核实打回' },
        { ID: '-2', NAME: '被检查人申辩' }
      ],
      inspectionTypeList: [],
      varList: [],
      form: {
        INSPECTION_INSPECTOR_ID: '', // 安全环保检查人员主键ID
        INSPECTION_ID: '', // 安全环保检查ID
        INSPECTION_USER_ID: '', // 检查人
        INSPECTION_USER_OPINION: '', // 检查人意见（有异议时必填）
        INSPECTION_USER_SIGN_IMG: '', // 检查人签字
        INSPECTION_USER_SIGN_TIME: ''// 检查人签字时间
      },
      dialogFormEdit: false,
      rules: {
        INSPECTION_ID: [{ required: true, message: '安全环保检查ID不能为空', trigger: 'blur' }],
        INSPECTION_USER_ID: [{ required: true, message: '检查人不能为空', trigger: 'blur' }]
      },
      dialogWriteSign: false
    }
  },
  created() {
    this.getDict()
    this.getList(this.ROLE_ID)
  },
  methods: {
    /** 获取行数据 Key，用于优化 table 表格的渲染 */
    getRowKey(row) {
      return row.INSPECTION_ID
    },
    /** 执行参数搜索 */
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    /** 执行重置 */
    goKeyReset() {
      this.resetSearch()
      this.getQuery()
    },
    /** 获取列表 */
    getList() {
      this.listLoading = true
      requestFN(
        '/safetyenvironmental/pleadList?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.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })

      setTimeout(() => {
        this.listLoading = false
        this.varList = []
        this.total = 0
      }, 400)
    },
    /** 查看指定项 */
    goDetail(row) {
      this.$parent.activeName = 'InspectionInfo'
      this.$parent.INSPECTION_ID = row.INSPECTION_ID
    },
    /** 处理核实逻辑 */
    // handleVerify(row) {
    //   this.resetForm(row)
    //   this.dialogFormEdit = true
    // },
    /** 手写板弹框打开 */
    showModal() {
      this.dialogWriteSign = true
    },
    /** 手写板完成 */
    subCanvas(img64) {
      console.info('img64：' + img64)
      this.form.INSPECTION_USER_SIGN_IMG = img64
      this.$set(this.form, 'INSPECTION_USER_SIGN_TIME', formatDate(new Date(), 'YYYY-MM-DD HH:mm'))
      this.dialogWriteSign = false
    },
    /** 表单保存 */
    confirm(INSPECTION_STATUS) {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (INSPECTION_STATUS === '-1') {
            if (!this.validStr(this.form.INSPECTION_USER_OPINION)) {
              this.$message.warning('有异议时，检查人意见不能为空')
              return false
            }
          }
          if (!this.validStr(this.form.INSPECTION_USER_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
          requestFN(
            '/safetyenvironmentalinspector/verify',
            { ...this.form,
              INSPECTION_STATUS: INSPECTION_STATUS
            }
          ).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/getLevels',
        {
          DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
        }
      ).then((data) => {
        this.inspectionTypeList = data.list
      }).catch((e) => {

      })
    },
    /** 重置搜索状态 */
    resetSearch() {
      this.search = {
        INSPECTED_DEPARTMENT_NAME: '', // 被检查单位
        INSPECTION_DEPARTMENT_NAME: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_STATUS: '' // 检查状态
      }
    },
    /** 重置表单数据 */
    resetForm(row) {
      this.form = {
        INSPECTION_INSPECTOR_ID: row.INSPECTION_INSPECTOR_ID, // 安全环保检查人员主键ID
        INSPECTION_ID: row.INSPECTION_ID, // 安全环保检查ID
        INSPECTION_USER_ID: row.INSPECTION_USER_ID, // 检查人
        INSPECTION_USER_OPINION: '', // 检查人意见（有异议时必填）
        INSPECTION_USER_SIGN_IMG: '', // 检查人签字
        INSPECTION_USER_SIGN_TIME: ''// 检查人签字时间
      }
    },
    /** 格式化日期时间 */
    formatDate(date, format) {
      return formatDate(date, format)
    },
    /** 申辩记录进入,此时会调用 trajectory 所在子组件内的 init 方法,并传入 id 执行 init 方法的逻辑 */
    openTrajectory(id) {
      this.$refs.trakectory.init(id)
    }
  }
}

</script>
