<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-button type="primary" icon="el-icon-edit" @click="editYsjl('YSJL')">
            起草原始记录
          </el-button>
          <el-button type="primary" icon="el-icon-edit" @click="editYsjl('JYBG')">
            起草报告
          </el-button>
          <el-button type="success" icon="el-icon-tickets" @click="copyYsjl">
            复制数据
          </el-button>
          <el-button type="warning" @click="turnBack">
            <svg-icon icon-class="reject" /> 任务退回
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteRenwu">
            作废任务
          </el-button>
          <el-button type="success" icon="el-icon-success" @click="completeRenwu">
            任务完成
          </el-button>
          <el-button type="danger" @click="terminationFn">
            <svg-icon icon-class="termination" /> 终止任务
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-select v-model="listQuery.shebeizhongleidaima" placeholder="请选择设备种类" clearable>
            <el-option v-for="item in sbzlList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="listQuery.neibuleibie" placeholder="请选择检验类别" clearable>
            <el-option v-for="item in searchNblist" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
          <el-input v-model="listQuery.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 340px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.zhucedaima" placeholder="注册代码" clearable style="width: 230px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.shiyongdengjibianhao" placeholder="使用登记证号" clearable style="width: 200px" @keyup.enter.native="handleFilter" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="info" icon="el-icon-close" @click="clearQuery">
            清空条件
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      v-adaptive="{bottomOffset: 50}"
      height="0"
      :data="list"
      width="100%"
      size="small"
      border
      fit
      highlight-current-row
      stripe
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column align="center" label="序号" width="60" fixed="left" type="index" />
      <el-table-column align="center" label="设备种类" prop="shebeizhonglei" width="100" />
      <el-table-column :formatter="formatter.formatterCategory" align="center" label="检验类别" prop="neibuleibie" width="100" />
      <el-table-column align="center" label="使用登记证号" prop="shiyongdengjibianhao" width="180" sortable="custom" />
      <el-table-column align="center" label="注册代码" prop="zhucedaima" width="180" sortable="custom" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" min-width="240" />
      <el-table-column align="center" label="产品名称/设备名称" prop="shebeimingcheng" width="180" />
      <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="220" />
      <el-table-column v-if="$store.getters.departmentId === 68" align="center" label="管道级别" prop="s7" width="140" />
      <el-table-column align="center" label="区划名称" prop="quhuamingcheng" width="150" />
      <el-table-column :formatter="formatterSlrq" align="center" label="报检日期" prop="shouliriqi" width="120" sortable />
      <el-table-column align="center" label="下次检验日期" prop="xiacijianyanriqi" width="120" />
      <el-table-column :formatter="formatter.getChineseName" align="center" label="认领人" prop="renlingren" width="140" />
    </el-table>
    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageRow" @pagination="getList" />

    <el-dialog :title="textMap[category]" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-row style="margin-bottom: 15px;">
        <el-select v-model="neibuleibie" placeholder="内部类别" style="width: 180px" @change="getTemplateList">
          <el-option v-for="item in nblbList" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-select v-model="shebeizhongleidaima" placeholder="设备种类" style="width: 180px" @change="getSblbList">
          <el-option v-for="item in sbzlList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="shebeileibiedaima" placeholder="设备类别" style="width: 210px" @change="getSbpzList">
          <el-option v-for="item in sblbList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="shebeipinzhongdaima" placeholder="设备品种" style="width: 220px" :disabled="$store.getters.departmentId === 74" @change="getModelList">
          <el-option v-for="item in sbpzList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-row>
      <el-row>
        <el-select v-model="template" value-key="value" placeholder="模板名称" style="width: 88%" @change="templateChange">
          <el-option v-for="item in modelList" :key="item.value" :label="item.label" :value="item" />
        </el-select>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="initYsjl">
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormCopyVisible" title="复制数据" width="85%">
      <el-container>
        <el-header height="165px">
          <el-input v-model="listQueryCopy.searchYsjl.jilubianhao" placeholder="记录编号" clearable style="width: 200px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.baogaobianhao" placeholder="报告编号" clearable style="width: 200px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.zhucedaima" placeholder="注册代码" clearable style="width: 280px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.shiyongdanwei" placeholder="使用单位" clearable style="width: 310px" @keyup.enter.native="handleFilterCopy" />
          <br><br>
          <el-input v-model="listQueryCopy.searchYsjl.chanpinbianhao" placeholder="产品/出厂编号" clearable style="width: 200px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.shiyongdengjibianhao" placeholder="使用登记证" clearable style="width: 200px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.zhizaodanwei" placeholder="制造单位" clearable style="width: 280px" @keyup.enter.native="handleFilterCopy" />
          <el-input v-model="listQueryCopy.searchYsjl.weibaodanwei" placeholder="维保单位" clearable style="width: 310px" @keyup.enter.native="handleFilterCopy" />
          <br><br>
          <el-select
            v-model="listQueryCopy.searchYsjl.neibuleibie"
            placeholder="检验类别"
            clearable
            style="width: 200px"
          >
            <el-option v-for="item in jylbList" v-show="item.parentId" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-header>
        <div style="margin-left: 400px;height: 60px;">
          <el-button type="primary" icon="el-icon-search" @click="handleFilterCopy">
            查询
          </el-button>
          <el-button type="info" icon="el-icon-close" @click="clearCopyQuery">
            清空条件
          </el-button>
        </div>
      </el-container>
      <el-table
        ref="listCopy"
        :data="listCopy"
        size="small"
        style="width: 100%"
        border
        fit
        height="450px"
        width="100%"
        highlight-current-row
        @row-click="onDialogRowClick"
        @selection-change="handleDialogSelectionChange"
      >
        <el-table-column type="selectionCopy" width="45" />
        <el-table-column align="center" label="序号" width="50" type="index">
          <!-- <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)" />
          </template> -->
        </el-table-column>
        <el-table-column align="center" label="报告编号" prop="baogaobianhao" width="180px;" />
        <el-table-column align="center" label="记录编号" prop="jilubianhao" width="180" sortable="custom" />
        <el-table-column align="center" label="检验类别" :formatter="formatter.formatterCategory" prop="neibuleibie" width="100" />
        <el-table-column align="center" label="使用登记证号" prop="shiyongdengjibianhao" width="180" sortable="custom" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" width="180" sortable="custom" />
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" width="240" />
        <el-table-column align="center" label="产品名称/设备名称" prop="shebeimingcheng" width="220" />
        <el-table-column align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="220" />
        <el-table-column align="center" label="检验日期" prop="jianyanjieshuriqi" width="110" />
        <el-table-column fixed="right" align="center" label="操作" prop="">
          <template slot-scope="scopecopy">
            <el-button type="primary" size="medium" icon="el-icon-tickets" title="复制设备信息" @click="copyYsjl(scopecopy.$index)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="totalCopy" :page-num.sync="listQueryCopy.pageNum" :page-row.sync="listQueryCopy.pageRow" @pagination="getListCopy" />
    </el-dialog>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
import Utils from '../../utils/contact.js'
import { getOwnList, terminateRenwu, completeRenwuFn } from '@/api/renwu'
import { cancelRenwuFn } from '@/api/common'
import { mapGetters } from 'vuex'
import qs from 'qs'
export default {
  name: 'MyTask',
  components: { Sticky, Pagination },
  filters: {
    screen(value) {
      console.log(value, 254444)
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  },
  data() {
    return {
      total: 0,
      list: [],
      totalCopy: 0,
      listCopy: [],
      sbzlList: [],
      sblbList: [],
      sbpzList: [],
      jylbList: [],
      nblbList: [],
      modelList: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20 // 每页条数
      },
      listQueryCopy: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        hasChild: false,
        searchYsjl: {
          neibuleibie: 'DQ'
        }
      },
      multipleSelection: [],
      selectionCopy: [],
      selection: {},
      dialogFormVisible: false,
      dialogFormCopyVisible: false,
      shebeizhongleidaima: '',
      shebeileibiedaima: '',
      shebeipinzhongdaima: '',
      jianyanleibie: '',
      neibuleibie: '',
      template: {},
      renwuId: '',
      category: '',
      textMap: {
        YSJL: '起草原始记录',
        JYBG: '起草检验报告'
      },
      path: '',
      // 压力容器移动式起草报告模板 将设备信息传到后台
      sbxxList: {
        sblbmc: '',
        sbpzmc: '',
        sblbdm: '',
        sbpzdm: ''
      },
      currentRenwuId: 0,
      dialogEnclosureVisible: false,
      isSysUser: this.$store.getters.clientType === 'System',
      searchNblist: []
    }
  },
  computed: {
    ...mapGetters(['allCategory'])
  },
  watch: {
    allCategory: {
      handler(n, o) {
        console.log(n.filter(item => item.parentId))
        this.searchNblist = n.filter(item => item.parentId)
      },
      deep: true
    }
  },
  created() {
    this.getList()
    this.getSbList(undefined, undefined, 1)
  },
  mounted() {
    const that = this
    this.common.$on('task-list', function() {
      that.handleFilter()
    })
    this.jylbList = this.$store.getters.allCategory
  },
  methods: {
    getList() {
      getOwnList(this.listQuery).then(data => {
        this.list = data.list
        this.total = data.total
      })
    },
    getListCopy() {
      this.listQueryCopy.searchYsjl.bglx = '1'
      this.listQueryCopy.copyPage = true
      this.listQueryCopy.hasLook = 0
      this.listQueryCopy.searchYsjl.shebeizhongleidaima = this.multipleSelection[0].shebeizhongleidaima
      this.api({
        url: '/ysjl/getList',
        method: 'get',
        params: this.listQueryCopy
      }).then(data => {
        this.listCopy = data.list
        this.totalCopy = data.total
      })
    },
    onDialogRowClick(row) {
      this.$refs.listCopy.toggleRowSelection(row)
    },
    handleDialogSelectionChange(val) {
      this.selectionCopy = val
    },
    getSblbList(val) {
      this.shebeileibiedaima = ''
      this.sbpzList = []
      this.shebeipinzhongdaima = ''
      this.modelList = []
      this.template = {}
      this.getSbList(val, undefined, 2)
      this.neibuleibie = ''
      this.getCategoryList('nblb', this.jianyanleibie, this.shebeizhongleidaima)
    },
    getSbpzList(val) {
      this.modelList = []
      this.template = {}
      this.shebeipinzhongdaima = ''
      this.getSbList(this.shebeizhongleidaima, val, 3)
    },
    getSbList(sbzl, sblb, level) {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: sbzl,
          sblb: sblb,
          level: level
        }
      }).then(data => {
        switch (level) {
          case 2:
            this.sblbList = data
            break
          case 3:
            this.sbpzList = data
            this.shebeipinzhongdaima = this.sbpzList[0].value
            this.getModelList(this.shebeipinzhongdaima)
            break
          default:
            this.sbzlList = data
            break
        }
      })
    },
    getModelList(val) {
      if (this.neibuleibie === null || this.neibuleibie === '' || this.neibuleibie === undefined) {
        this.$message({
          message: '请先选择内部类别。',
          type: 'warning'
        })
        return false
      }
      this.getTemplateData(val, this.jianyanleibie, this.neibuleibie, this.category)
    },
    getTemplateList(val) {
      if (this.shebeipinzhongdaima === null || this.shebeipinzhongdaima === '' || this.shebeipinzhongdaima === undefined) {
        return false
      }
      this.getTemplateData(this.shebeipinzhongdaima, this.jianyanleibie, val, this.category)
    },
    getTemplateData(sbpz, jianyanleibie, neibuleibie, category) {
      this.api({
        url: '/template/getTemplateBySbpz',
        method: 'get',
        params: {
          sbpz: sbpz,
          jianyanleibie: jianyanleibie,
          neibuleibie: neibuleibie,
          category: category
        }
      }).then(data => {
        if (data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            if (data[i].label === 'JTYJL252-2016氧舱定期检验报告' || data[i].label === 'JTYJL252-2016氧舱年度检验报告' || data[i].label === '压力容器改造与重大修理监督检验报告') {
              data.splice(i, 1)
            }
            if (this.$store.getters.clientType === 'Enterprise' && data[i].label.indexOf('JTY') === 0) {
              data[i].label = data[i].label.substr(13)
            }
          }
          this.modelList = data
          this.template = data[0]
          this.path = data[0].path
        } else {
          this.modelList = []
          this.template = {}
        }
      })
    },
    templateChange(item) {
      this.path = item.path
    },
    getCategoryList(type, parentCode, species) {
      this.api({
        url: '/category/getCategoryList',
        method: 'get',
        params: {
          parentCode: parentCode,
          species: species
        }
      }).then(data => {
        switch (type) {
          case 'jylb':
            this.jylbList = data
            return ''
          case 'nblb':
            this.nblbList = data
            return ''
        }
      })
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleFilterCopy() {
      // 查询事件
      this.listQueryCopy.pageNum = 1
      this.getListCopy()
    },
    onRowClick(row) {
      this.selection = row
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    editYsjl(val) {
      if (this.multipleSelection.length !== 1) {
        let mes = ''
        if (val === 'YSJL') {
          mes = '请选择一条任务起草原始记录！'
        } else {
          mes = '请选择一条任务起草检验报告！'
        }
        this.$message({
          type: 'error',
          message: mes
        })
        return false
      }
      this.category = val
      this.jianyanleibie = this.multipleSelection[0].jianyanleibie
      this.shebeizhongleidaima = this.multipleSelection[0].shebeizhongleidaima
      this.renwuId = this.multipleSelection[0].id
      if (this.shebeizhongleidaima !== null && this.shebeizhongleidaima !== '') {
        this.getSblbList(this.shebeizhongleidaima)
        this.shebeileibiedaima = this.multipleSelection[0].shebeileibiedaima
        if (this.shebeileibiedaima !== null && this.shebeileibiedaima !== '') {
          this.getSbpzList(this.shebeileibiedaima)
          this.neibuleibie = this.multipleSelection[0].neibuleibie
          this.shebeipinzhongdaima = this.multipleSelection[0].shebeipinzhongdaima
          if (this.shebeipinzhongdaima !== null && this.shebeipinzhongdaima !== '' && this.neibuleibie !== null && this.neibuleibie !== undefined) {
            this.getModelList(this.shebeipinzhongdaima)
          }
        }
      }
      this.dialogFormVisible = true
    },
    closeDialog() {
      this.shebeizhongleidaima = ''
      this.shebeileibiedaima = ''
      this.shebeipinzhongdaima = ''
      this.template = {}
      this.neibuleibie = ''
      this.sblbList = []
      this.sbpzList = []
      this.modelList = []
      this.nblbList = []
    },
    initYsjl() {
      if (this.template === '' || this.template === null || this.template === undefined) {
        this.$message({
          message: '请选择模板。',
          type: 'warning'
        })
        return false
      }
      for (let i = 0; i < this.sblbList.length; i++) {
        if (this.sblbList[i].value === this.shebeileibiedaima) {
          this.sbxxList.sblbmc = this.sblbList[i].label
        }
      }
      for (let i = 0; i < this.sbpzList.length; i++) {
        if (this.sbpzList[i].value === this.shebeipinzhongdaima) {
          this.sbxxList.sbpzmc = this.sbpzList[i].label
        }
      }
      this.sbxxList.sblbdm = this.shebeileibiedaima
      this.sbxxList.sbpzdm = this.shebeipinzhongdaima
      console.log(this.path + '/null')
      this.$router.push({
        path: this.path + '/null',
        query: {
          state: 'create',
          renwuId: this.renwuId,
          templateId: this.template.value,
          jylb: this.jianyanleibie,
          neibuleibie: this.neibuleibie,
          departmentId: this.$store.getters.departmentId,
          sbzldm: this.shebeizhongleidaima,
          sblbdm: this.sbxxList.sblbdm,
          sblbmc: this.sbxxList.sblbmc,
          sbpzdm: this.sbxxList.sbpzdm,
          sbpzmc: this.sbxxList.sbpzmc
        }
      })
      this.dialogFormVisible = false
    },
    copyYsjl($index) {
      if (this.multipleSelection.length <= 0) {
        this.$message({
          message: '请选择需要复制设备的任务。',
          type: 'warning'
        })
        return false
      }
      let renwuids = ''
      for (var i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[0].shebeizhongleidaima !== this.multipleSelection[i].shebeizhongleidaima) {
          this.$message({
            message: '请选择同设备种类任务进行复制。',
            type: 'warning'
          })
          return false
        }
        if (i === 0) {
          renwuids = this.multipleSelection[i].id
        } else {
          renwuids = renwuids + ',' + this.multipleSelection[i].id
        }
      }
      if (!this.dialogFormCopyVisible) {
        this.listQueryCopy.neibuleibie = this.multipleSelection[0].neibuleibie
        this.handleFilterCopy()
        this.dialogFormCopyVisible = true
      } else {
        this.api({
          url: '/copy/createCopyObj',
          method: 'get',
          params: {
            ysjlId: this.listCopy[$index].id,
            renwuIds: renwuids
          }
        }).then(data => {
          Utils.$emit('ysjl-list')
          this.$message({
            type: 'success',
            message: '任务复制成功！'
          })
          this.dialogFormCopyVisible = false
          this.getList()
        })
      }
    },
    turnBack() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'error',
          message: '请选择要退回的任务'
        })
        return false
      }
      this.apibjd({
        url: 'renwu/backToLeader',
        method: 'get',
        params: {
          renwuIds: this.$refs.list.selection.map(rw => {
            return rw.id
          })
        },
        paramsSerializer: function(params) {
          return qs.stringify(params, { indices: false })
        }
      }).then(data => {
        this.$message({
          type: 'success',
          message: '任务退回成功'
        })
        this.getList()
      })
    },
    clearQuery() {
      this.listQuery = {}
      this.getList()
    },
    clearCopyQuery() {
      this.$set(this.listQueryCopy, 'searchYsjl', {})
      this.handleFilterCopy()
    },
    formatterSlrq(row) {
      if (row.shouliriqi) {
        return row.shouliriqi.substring(0, 10)
      }
      return row.shouliriqi
    },
    deleteRenwu() {
      if (!this.$refs.list.selection.length) {
        this.$message.error('请选择要作废的任务')
        return false
      }
      this.$prompt('正在执行作废任务操作,确定继续?', '提示', {
        inputType: 'textarea',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value === null) {
          this.$message({ message: '请填写作废原因！', type: 'warning' })
          return false
        }
        const arr = this.$refs.list.selection.map(rw => {
          return rw.id
        })
        cancelRenwuFn({
          renwuIds: arr,
          reason: value
        }).then(data => {
          this.$message.success('作废成功！')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消作废'
        })
      })
    },
    completeRenwu() {
      if (!this.$refs.list.selection.length) {
        this.$message.error('请选择要完成的任务')
        return false
      }
      this.$confirm('正在执行任务完成操作，确定继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = []
        this.$refs.list.selection.map(rw => {
          arr.push(rw.id)
        })

        completeRenwuFn({ renwuIds: arr }).then(res => {
          this.$message.success('任务已完成')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 终止任务
    terminationFn() {
      if (!this.$refs.list.selection.length) {
        this.$message.error('请选择要终止的任务')
        return false
      }
      const renwuIds = []
      this.$refs.list.selection.map(rw => {
        renwuIds.push(rw.id)
      })
      this.$prompt('请输入终止原因', '确认提前终止任务？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '终止原因不能为空'
      }).then(({ value }) => {
        const data = {
          reason: value,
          renwuIds
        }
        terminateRenwu(data).then(data => {
          this.$message.success('任务已终止')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    /**
     * 显示相关鉴证文件上传窗口
     * @param renwuId
     */
    showVerification(renwuId) {
      this.dialogEnclosureVisible = true
      this.currentRenwuId = renwuId
    }
  }
}
</script>
