<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-button v-show="hasPerm('liaison:add')" type="primary" icon="el-icon-edit" @click="showCreate">
            添加
          </el-button>
          <el-button v-show="hasPerm('liaison:delete')" type="danger" icon="el-icon-delete" @click="deleteSet">
            删除
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.number" clearable placeholder="请填写编号" style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.zzdwId" placeholder="请选择制造单位" clearable style="width: 200px;" @keyup.enter.native="handleFilter">
            <el-option v-for="item in manufacturerList" :key="item.id" :label="item.zhizaodanwei" :value="item.id" />
          </el-select>
          <el-select v-model="workItemQuerys" placeholder="请选择问题项" multiple clearable style="width: 200px;" @keyup.enter.native="handleFilter">
            <el-option v-for="item in checkedCities" :key="item" :label="item" :value="item" />
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      :data="list"
      border
      fit
      size="small"
      width="100%"
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50px;" />
      <el-table-column align="center" label="编号" prop="number" />
      <el-table-column align="center" label="制造单位" :formatter="getManufacturerName" prop="zzdwId" />
      <el-table-column align="center" label="文件类型" width="100px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type" type="danger">
            联络单
          </el-tag>
          <el-tag v-else type="warning">
            意见书
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="下发日期" prop="processingDate" />
      <el-table-column align="center" label="检验人员" prop="inspector" />
      <el-table-column align="center" label="检验日期" prop="inspectorDate" />
      <el-table-column align="center" label="受检单位接收人" prop="receiver" />
      <el-table-column align="center" label="问题项" prop="workItem" />
      <el-table-column align="center" label="操作" fixed="right" width="250px">
        <template slot-scope="scope">
          <el-button v-show="hasPerm('liaison:update')" type="primary" @click="showUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-show="hasPerm('liaison:upload')" type="success" @click="showVerification(scope.row.id)">
            上传相关鉴证
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageSize" style="float: left;" @pagination="getList" />
    <!--选择文件类型-->
    <el-dialog title="文件类型" :visible.sync="dialogVisibleType" width="20%">
      <el-button type="warning" plain @click="setLiaisonTpye(true)">
        联络单
      </el-button>
      <el-button type="warning" plain @click="setLiaisonTpye(false)">
        意见书
      </el-button>
    </el-dialog>
    <!--打开录入框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" style="width: 120%; margin-top: -7vh;margin-left: -12%" @close="closeDialog">
      <el-form ref="liaison" :model="liaison" :rules="rules" style="overflow: auto;">
        <el-row>
          <el-col :span="10">
            <el-form-item label="受检单位：" prop="inspectorDate">
              <el-select v-model="liaison.zzdwId" size="medium" filterable placeholder="请选择受检单位" style="width: 200px;" clearable>
                <el-option v-for="item in manufacturerList" :key="item.id" :label="item.zhizaodanwei" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9" :offset="5">
            <el-form-item label="编号：" prop="inspectorDate">
              <el-input v-model="liaison.number" size="medium" placeholder="请录入编号" style="width: 200px;" clearable type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="问题项：" prop="inspectorDate">
              <el-checkbox-group v-model="workItem" size="medium" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="city in checkedCities" :key="city" :label="city">
                  {{ city }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="height: 90px">
          <el-col :span="24">
            经监督检验，发现你单位在（
            <el-input v-model="liaison.position" size="medium" show-word-limit maxlength="200" placeholder="填写压力容器产品名称、产品批号、编号或者位号" style="width: 380px;" clearable type="text" />
            ）的（
            <el-input v-model="liaison.process" size="medium" show-word-limit maxlength="200" placeholder="填写制造、安装、改造、重大修理" style="width: 280px;" clearable type="text" />
            ）过程中，存在以下影响安全性能的问题，请于
            <el-date-picker v-model="liaison.processingDate" size="medium" value-format="yyyy-MM-dd" style="width: 150px;" clearable type="date" placeholder="选下发日期" />
            前将处理结果报送监检机构。
          </el-col>
        </el-row>
        <el-row style="height: 100px">
          <el-col :span="24">
            <el-form-item label="问题和意见：" prop="inspectorDate">
              <el-input v-model="liaison.questions" style="width: 100%" show-word-limit maxlength="200" placeholder="请录入问题和意见" clearable type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="13" :offset="2">
            <el-form-item label="检验人员：" prop="inspector">
              <el-input v-model="liaison.inspector" size="medium" style="width: 200px;" disabled type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="日期：" prop="inspectorDate">
              <el-date-picker v-model="liaison.inspectorDate" size="medium" value-format="yyyy-MM-dd" style="width: 200px;" clearable type="date" placeholder="选择检验日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="!type">
          <el-col :span="13" :offset="2">
            <el-form-item label="监检机构技术负责人：" prop="director">
              <el-input v-model="liaison.director" size="medium" placeholder="请录入监检机构技术负责人" style="width: 200px;" clearable type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="日期：" prop="directorDate">
              <el-date-picker v-model="liaison.directorDate" size="medium" style="width: 200px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择监检机构技术负责人签字日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="13" :offset="2">
            <el-form-item label="受检单位接收人：" prop="receiver">
              <el-input v-model="liaison.receiver" size="medium" placeholder="请录入受检单位接收人" style="width: 200px;" clearable type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="日期：" prop="receiverDate">
              <el-date-picker v-model="liaison.receiverDate" size="medium" value-format="yyyy-MM-dd" style="width: 200px;" clearable type="date" placeholder="选择受检单位接收日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="处理结果：" prop="results">
            <el-input v-model="liaison.results" placeholder="请录入处理结果" show-word-limit maxlength="200" style="width: 100%" clearable type="textarea" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="受检单位主管负责人：" prop="executive">
              <el-input v-model="liaison.executive" size="medium" style="width: 200px;" placeholder="请录入受检单位主管负责人" clearable type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="日期：" prop="executiveDate">
              <el-date-picker v-model="liaison.executiveDate" size="medium" style="width: 200px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择受检单位主管负责人签字日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9" :offset="15">
            <el-form-item label="日期：" prop="closingDate">
              <el-date-picker v-model="liaison.closingDate" size="medium" style="width: 200px;" value-format="yyyy-MM-dd" clearable type="date" placeholder="选择回复日期" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取 消
        </el-button>
        <el-button v-show="dialogStatus==='create'" type="success" @click="saveOrUpdate">
          保 存
        </el-button>
        <el-button v-show="dialogStatus!=='create' " type="primary" @click="saveOrUpdate">
          修 改
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="上传相关鉴证" :modal-append-to-body="false" :visible.sync="dialogEnclosureVisible">
      <enclosure :relation-id.sync="currentId" :if-liaison.sync="ifLiaison" :view-button.sync="viewButton" />
    </el-dialog>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
import Enclosure from '@/views/common/Enclosure'

export default {
  name: 'LiaisonList',
  components: { Sticky, Pagination, Enclosure },
  data() {
    return {
      list: [],
      ifClientType: this.$store.getters.clientType === 'System',
      listQuery: {
        pageNum: 1, // 页码
        pageSize: 20, // 每页条数
        inspector: this.ifClientType ? this.$store.getters.userId : ''
      },
      workItemQuerys: [],
      totalCount: 0,
      manufacturerList: [],
      dialogStatus: '',
      liaison: {},
      type: false,
      textMap: {
        create: '添加',
        update: '编辑'
      },
      activeName: 'first',
      dialogVisibleType: false,
      dialogVisible: false,
      multipleSelection: [],
      dialogEnclosureVisible: false,
      currentId: '',
      ifLiaison: true,
      viewButton: true,
      checkedCities: ['设计', '材料', '制造', '无损检测', '出厂资料', '其它'],
      workItem: [],
      rules: {
        zzdwId: [{ required: true, message: '请选择制造单位', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getManufacturerByUserId()
  },
  methods: {
    /**
     *  检索条件查询事件
     */
    handleFilter() {
      this.listQuery.pageNum = 1
      if (this.workItemQuerys.length > 0) {
        this.listQuery.workItems = this.workItemQuerys.join(',')
      } else {
        this.listQuery.workItems = ''
      }
      this.getList()
    },
    /**
     * 根据登录用户获得所属列表数据事件
     */
    getList() {
      this.api({
        url: '/liaison/list',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.totalCount = data.total
      })
    },
    /**
     * 工作项选择事件
     */
    handleCheckedCitiesChange(val) {
      this.workItem = val
    },
    /**
     * 根据登录用户获取所属制造单位集合事件
     */
    getManufacturerByUserId() {
      this.api({
        url: '/dwxx/getAll',
        method: 'get',
        params: {
          shebeizhongleidaima: this.$store.getters.departmentId === 74 ? '1000' : '2000',
          // zhuchangjianyanrenyuan: this.ifClientType && this.$store.getters.username !== 'admin' ? this.$store.getters.userId : null,
          userId: this.ifClientType ? null : this.$store.getters.userId
        }
      }).then(data => {
        this.manufacturerList = data
      })
    },
    /**
     * 打开添加页面事件
     */
    showCreate() {
      this.dialogStatus = 'create'
      this.workItem = []
      this.liaison = {}
      this.liaison.inspector = this.$store.getters.nickname
      this.dialogVisibleType = true
    },
    /**
     * 选择文件类型事件
     */
    setLiaisonTpye(type) {
      this.liaison.type = type
      this.type = type
      this.textMap.create = type ? '添加特种设备监督检验联络单' : '添加特种设备监督检验意见通知书'
      this.textMap.update = type ? '编辑特种设备监督检验联络单' : '编辑特种设备监督检验意见通知书'
      this.dialogVisibleType = false
      this.dialogVisible = true
    },
    /**
     * 根据主键批量删除事件-同时删除所包含相关鉴证事件
     */
    deleteSet() {
      if (this.multipleSelection.length === 0) {
        this.$message({ type: 'error', message: '请选择需要删除的数据！' })
        return false
      } else {
        this.$confirm('确定删除当前选中联络单意见书?', '提示', {
          confirmButtonText: '确定',
          showCancelButton: true,
          type: 'warning'
        }).then(() => {
          const ids = []
          const qs = require('qs')
          this.multipleSelection.forEach(data => {
            ids.push(data.id)
          })
          this.api({
            url: '/liaison/delLiaison',
            method: 'delete',
            params: { ids: ids },
            paramsSerializer: function(params) {
              return qs.stringify(params, { indices: false })
            }
          }).then(() => {
            this.$message.success('删除成功！')
            //  待删除相关鉴证信息方法！
            this.preview({
              url: '/upload/deleteProveByRelationIds',
              method: 'delete',
              params: { relationIds: ids, ifLiaison: true },
              paramsSerializer: function(params) {
                return qs.stringify(params, { indices: false })
              }
            }).then(() => {
              this.getList()
            })
          })
        })
      }
    },
    /**
     * 根据主键获取数据信息事件
     */
    getById(id) {
      this.api({
        url: '/liaison/getById',
        method: 'get',
        params: { id: id }
      }).then(data => {
        this.liaison = data
        if (this.liaison.workItem) {
          this.workItem = this.liaison.workItem.split(',')
        }
      })
    },
    /**
     * 打开编辑页面事件
     */
    showUpdate(row) {
      this.getById(row.id)
      this.dialogStatus = 'update'
      this.dialogVisible = true
    },
    /**
     * 保存事件
     */
    saveOrUpdate() {
      this.$refs['liaison'].validate(valid => {
        if (valid) {
          if (!this.liaison.zzdwId || this.liaison.zzdwId === '') {
            this.$message.error('请选择受检单位！')
            return false
          }
          if (this.workItem) {
            this.liaison.workItem = this.workItem.join(',')
          }
          let url = '/liaison/saveLiaison'
          let text = '添加成功!'
          if (this.dialogStatus === 'update') {
            url = '/liaison/updateLiaison'
            text = '编辑成功!'
          }
          this.api({
            url: url,
            method: 'post',
            data: this.liaison
          }).then(() => {
            this.$message.success(text)
            this.dialogVisible = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    /**
     * 展示上传相关鉴证窗口事件
     * @param liaisonId
     */
    showVerification(liaisonId) {
      this.currentId = liaisonId
      this.dialogEnclosureVisible = true
    },
    /**
     *  根据列表行制造单位主键展示对应制造单位名称事件
     * @param value
     */
    getManufacturerName(value) {
      if (this.$store.getters.clientType === 'Enterprise') {
        if (this.manufacturerList.length > 0) {
          return this.manufacturerList[0].zhizaodanwei
        }
      } else {
        const manufacturer = this.manufacturerList.filter(item => item.id === value.zzdwId)
        if (manufacturer.length > 0) {
          return manufacturer[0].zhizaodanwei
        }
      }
    },
    /**
     * 行点击事件
     * @param row
     */
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    /**
     * 列表勾选事件
     * @param val
     */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
     * 关闭保存、编辑窗口事件
     */
    closeDialog() {
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>

</style>
