<template>
  <div class="app-container">
    <el-form label-width="100px">
      <el-row>
        <el-col :span="4">
          <el-form-item label="被检查单位" prop="INSPECTED_DEPARTMENT_ID">
            <SelectTree
              ref="deptTree_Select1"
              :clearable="false"
              :options="treeData"
              :props="defaultProps"
              v-model="search.INSPECTED_DEPARTMENT_ID"
              placeholder="请选择被检查单位"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查部门" prop="INSPECTION_DEPARTMENT_ID">
            <SelectTree
              ref="deptTree_Select2"
              :clearable="false"
              :options="treeData"
              :props="defaultProps"
              v-model="search.INSPECTION_DEPARTMENT_ID"
              placeholder="请选择检查部门"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查人员">
            <el-input v-model="search.INSPECTION_USER_NAME" placeholder="检查人员..." />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查人手机">
            <el-input v-model="search.INSPECTION_USER_PHONE" 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-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="检查时间">
            <el-date-picker
              v-model="search.INSPECTION_TIME"
              type="daterange"
              style="width: 100%;"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="检查状态">
            <el-select v-model="search.INSPECTION_STATUS" placeholder="检查状态" clearable style="width: 100%">
              <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="隐患描述">
            <el-input v-model="search.HIDDENDESCR" placeholder="隐患描述..." />
          </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="检查情况">
            <el-input v-model="search.INSPECTION_CASE" placeholder="检查情况..." />
          </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>
    <div class="app-statistical">
      <span v-if="search.INSPECTION_SUBJECT == '安全'">
        {{ INSPECT_NAME }}<i>{{ safetyTotal }}</i>
      </span>
      <span v-else-if="search.INSPECTION_SUBJECT == '环保'">
        {{ INSPECT_NAME }}<i>{{ safetyTotal }}</i>
      </span>
      <span v-else-if="search.INSPECTION_SUBJECT == '综合'">
        {{ INSPECT_NAME }}<i>{{ safetyTotal }}</i>
      </span>
      <span v-else>
        {{ INSPECT_NAME }}<i>{{ safetyTotal }}</i>
      </span>
      <span>
        涉及隐患总数：<i>{{ hiddenTotal }}</i>
      </span>
    </div>
    <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="INSPECTED_SITEUSER_NAME" label="被检查单位现场负责人" align="center" />
      <el-table-column prop="INSPECTION_DEPARTMENT_NAME" label="检查部门" align="center" />
      <el-table-column prop="INSPECTION_ORIGINATOR_NAME" label="检查发起人" align="center" width="120" />
      <!--      <el-table-column prop="INSPECTED_SITEUSER_NAME" label="被检查单位现场负责人" align="center" />-->
      <el-table-column prop="INSPECTION_TYPE_NAME" label="检查类型" align="center" />
      <!--      <el-table-column prop="SITUATION_COUNT" label="检查记录数" align="center" width="120" />-->
      <el-table-column prop="HIDDEN_COUNT" label="涉及隐患数" align="center" width="120" />
      <!--      <el-table-column prop="INSPECTION_PLACE" label="检查场所" />-->
      <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 label="状态" align="center" width="120">
        <template slot-scope="{row}">
          {{ translate(row.INSPECTION_STATUS) }}
        </template>
      </el-table-column>
      <el-table-column prop="INSPECTION_SUBJECT" label="检查题目" align="center" />
      <el-table-column label="操作" align="center" width="480">
        <template slot-scope="{row}">
          <el-button icon="el-icon-view" size="mini" @click="goDetail(row)">查看</el-button>
          <el-button type="success" icon="el-icon-view" size="mini" @click="checkFlow(row)">流程图</el-button>
          <el-button
            v-show="edit && ( row.INSPECTION_STATUS == '-1')"
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleEdit(row.INSPECTION_ID)">编辑</el-button>
          <el-button
            v-show="row.INSPECTION_STATUS == '-2'"
            v-if="row.INSPECTION_ORIGINATOR_ID == loginUserId"
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleExplain(row)">申辩处理</el-button>
          <el-button v-show="del&&row.INSPECTION_SOURCE!='4'" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.INSPECTION_ID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新建检查</el-button>
        <!--        <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>-->
      </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="申辩人">
          <el-image
            :src="config.fileUrl + form.INSPECTED_SITEUSER_SIGN_IMG"
            :preview-src-list="new Array(config.fileUrl + form.INSPECTED_SITEUSER_SIGN_IMG)"
            style="width: 100px; height: 100px"/>
        </el-form-item>
        <el-form-item label="申辩时间">
          {{ form.INSPECTED_SITEUSER_SIGN_TIME }}
        </el-form-item>
        <el-form-item label="申辩说明">
          <el-input v-model="form.INSPECTED_EXPLAIN" :disabled="true" :autosize="{ minRows: 1}" type="textarea" maxlength="2000" placeholder="这里输入申辩内容..."/>
        </el-form-item>
        <el-form-item v-if="form.INSPECTED_EXPLAIN_FILEPATH" label="申辩附件">
          <span>{{ form.INSPECTED_EXPLAIN_FILENAME }}</span>
          <el-button type="primary" @click="downloadFile(form.INSPECTION_ID)">下载</el-button>
        </el-form-item>
        <el-form-item label="申辩是否成立" prop="INSPECTION_STATUS">
          <el-radio v-model="form.INSPECTION_STATUS" label="3">否</el-radio>
          <el-radio v-model="form.INSPECTION_STATUS" label="-2">是</el-radio>
        </el-form-item>
        <el-form-item v-if="form.INSPECTION_STATUS === '3'" label="不成立理由内容" prop="INSPECTED_EXPLAIN_REFUSE">
          <el-input v-model="form.INSPECTED_EXPLAIN_REFUSE" :autosize="{ minRows: 1}" type="textarea" maxlength="2000" placeholder="这里输入申辩内容..."/>
        </el-form-item>
        <el-form-item v-if="form.INSPECTION_STATUS === '3'" label="确认人">
          <el-button data-target="Modal" type="primary" @click="showModal">手写签字</el-button>
        </el-form-item>
        <div v-show="form.INSPECTION_ORIGINATOR_SIGN_IMG != ''" class="demo-image__preview">
          <el-image
            :src="form.INSPECTION_ORIGINATOR_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>
    <safety-flow-chart ref="safetyFlowChart"/>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import WriteSign from '@/components/WriteSign'
import SelectTree from '@/components/SelectTree'
import safetyFlowChart from '../../../hiddenUtil/safetyFlowChart'
export default {
  components: { Pagination, WriteSign, safetyFlowChart, SelectTree },
  directives: { waves },
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem('user')),
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      INSPECT_NAME: '安全环保总数：',
      safetyTotal: '',
      hiddenTotal: '',
      listQuery: {
        page: 1,
        limit: 20
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      loginUserId: '', // 登录人ID
      search: {
        HIDDENDESCR: '',
        INSPECTED_DEPARTMENT_ID: '', // 被检查单位
        INSPECTION_DEPARTMENT_ID: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_USER_NAME: '', // 检查人员
        INSPECTION_USER_PHONE: '', // 检查人员手机
        INSPECTION_CASE: '', // 检查情况
        INSPECTION_STATUS: '', // 检查状态
        INSPECTION_SUBJECT: '' // 检查题目
      },
      statusList: [
        // { ID: '', NAME: '请选择' },
        { 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: '被检查人申辩' }
      ],
      INSPECTION_SUBJECT_LIST: [
        { ID: '安全', NAME: '安全' },
        { ID: '环保', NAME: '环保' },
        { ID: '综合', NAME: '综合' }
      ],
      treeData: [],
      inspectionTypeList: [],
      varList: [],
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      form: {
        INSPECTED_SITEUSER_SIGN_IMG: '',
        INSPECTED_SITEUSER_SIGN_TIME: '',
        INSPECTED_EXPLAIN: '',
        INSPECTED_EXPLAIN_FILENAME: '', // 申辩附件名称
        INSPECTED_EXPLAIN_FILEPATH: '',
        INSPECTION_STATUS: '3',
        INSPECTION_ID: '', // 安全环保检查ID
        INSPECTED_EXPLAIN_REFUSE: '', // 申辩拒绝理由
        INSPECTION_ORIGINATOR_SIGN_IMG: '' // 检查发起人签字
        // INSPECTION_ORIGINATOR_SIGN_TIME: '', // 被检查单位现场负责人签字时间
      },
      dialogFormEdit: false,
      dialogWriteSign: false,
      rules: {
        INSPECTION_ID: [{ required: true, message: '安全环保检查ID不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getDict()
    this.getList()
    this.getTreeData()
    this.getEditMyInfo()
  },
  methods: {
    getRowKey(row) {
      return row.INSPECTION_ID
    },
    translate(id) {
      for (var i = 0; i < this.statusList.length; i++) {
        if (this.statusList[i].ID == id) return this.statusList[i].NAME
      }
    },
    getEditMyInfo() { // 获取登录人信息
      return new Promise((resolve) => {
        requestFN(
          '/user/goEditMyInfo',
          {}
        ).then((data) => {
          this.loginUserId = data.pd.USER_ID
          this.loginUserName = data.pd.NAME
          resolve('ok')
        }).catch((e) => {

        })
      })
    },

    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
      if (this.search.INSPECTION_SUBJECT == '安全') {
        this.INSPECT_NAME = '安全检查总数：'
      } else if (this.search.INSPECTION_SUBJECT == '环保') {
        this.INSPECT_NAME = '环保检查总数：'
      } else if (this.search.INSPECTION_SUBJECT == '综合') {
        this.INSPECT_NAME = '综合检查总数：'
      } else this.INSPECT_NAME = '安全环保总数：'
    },
    goKeyReset() {
      this.resetSearch()
      this.getQuery()
      this.$refs.deptTree_Select1.clearHandle()
      this.$refs.deptTree_Select2.clearHandle()
    },
    // 获取列表
    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.safetyTotal = data.safetyTotal
        this.hiddenTotal = data.hiddenTotal
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 添加
    handleAdd() {
      this.$parent.INSPECTION_ID = ''
      this.$parent.activeName = 'Add'
    },
    // 修改
    handleEdit(ID) {
      this.$parent.INSPECTION_ID = ID
      this.$parent.activeName = 'Edit'
    },
    // 查看
    goDetail(row) {
      this.$parent.activeName = 'Info'
      this.$parent.INSPECTION_ID = row.INSPECTION_ID
    },
    checkFlow(row) {
      this.$refs.safetyFlowChart.init(row)
    },
    // 申辩处理
    handleExplain(row) {
      this.resetForm(row)

      this.form.INSPECTED_SITEUSER_SIGN_IMG = row.INSPECTED_SITEUSER_SIGN_IMG
      this.form.INSPECTED_SITEUSER_SIGN_TIME = row.INSPECTED_SITEUSER_SIGN_TIME
      this.form.INSPECTED_EXPLAIN = row.INSPECTED_EXPLAIN
      this.form.INSPECTED_EXPLAIN_FILENAME = row.INSPECTED_EXPLAIN_FILENAME
      this.form.INSPECTED_EXPLAIN_FILEPATH = row.INSPECTED_EXPLAIN_FILEPATH
      this.dialogFormEdit = true
    },
    /** 手写板*/
    showModal() {
      this.dialogWriteSign = true
    },
    // 完成
    subCanvas(img64) {
      console.info('img64：' + img64)
      this.form.INSPECTION_ORIGINATOR_SIGN_IMG = img64
      this.dialogWriteSign = false
    },
    // 保存
    confirm() {
      if (this.form.INSPECTION_STATUS === '-2') {
        this.$parent.INSPECTION_ID = this.form.INSPECTION_ID
        this.dialogFormEdit = false
        this.$parent.activeName = 'Edit'
      } else {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form.INSPECTION_STATUS === '3') {
              if (!this.validStr(this.form.INSPECTED_EXPLAIN_REFUSE)) {
                this.$message.warning('申辩不成立时，不成立理由内容不能为空')
                return false
              }
              if (!this.validStr(this.form.INSPECTION_ORIGINATOR_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(
              '/safetyenvironmental/explain',
              { ...this.form }
            ).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
          }
        })
      }
    },

    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/safetyenvironmental/hide',
          {
            INSPECTION_ID: id,
            hide: '1'
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.INSPECTION_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/safetyenvironmental/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'safetyenvironmental:add,safetyenvironmental:del,safetyenvironmental:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        console.log(data)
        this.add = data.safetyenvironmentalfhadminadd		// 新增权限
        this.del = data.safetyenvironmentalfhadmindel		// 删除权限
        this.edit = data.safetyenvironmentalfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
        }
      ).then((data) => {
        this.inspectionTypeList = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    // 获得部门树
    getTreeData() {
      requestFN(
        '/department/listTree',
        {}
      ).then((data) => {
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    resetSearch() {
      this.search = {
        HIDDENDESCR: '',
        INSPECTED_DEPARTMENT_NAME: '', // 被检查单位
        INSPECTION_DEPARTMENT_NAME: '', // 检查部门
        INSPECTION_ORIGINATOR_NAME: '', // 检查发起人
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TIME: ['', ''], // 检查时间
        INSPECTION_STATUS: '', // 检查状态
        INSPECTION_SUBJECT: '' // 检查题目
      }
      this.$refs.tree_InspectionType.clearHandle()
    },
    resetForm(row) {
      this.form = {
        INSPECTION_STATUS: '3',
        INSPECTION_ID: row.INSPECTION_ID, // 安全环保检查ID
        INSPECTED_EXPLAIN_REFUSE: '', // 申辩内容
        INSPECTION_ORIGINATOR_SIGN_IMG: '' // 被检查单位现场负责人签字
        // INSPECTION_ORIGINATOR_SIGN_TIME: '', // 被检查单位现场负责人签字时间
      }
    },
    downloadFile(INSPECTION_ID) {
      this.$confirm('确定要下载此文件吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + 'safetyenvironmental/download?INSPECTION_ID=' + INSPECTION_ID
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    }
  }
}

</script>
