<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-sold-out" @click="renwuFp">
            批量分配
          </el-button>
          <el-button type="warning" @click="returnToBjd">
            <svg-icon icon-class="reject" /> 异常退回
          </el-button>
          <el-button type="danger" icon="el-icon-error" @click="renwuZf">
            作废数据
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.searchRenwu.serialNumber" placeholder="报检单号" clearable style="width: 160px" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.searchRenwu.shebeizhongleidaima" placeholder="请选择设备种类" clearable @change="handleFilter">
            <el-option v-for="item in sbzlList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="listQuery.searchRenwu.quhuadaima" placeholder="请选择所属区划" clearable value="" @change="handleFilter">
            <el-option
              v-for="item in areas"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input v-model="listQuery.searchRenwu.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 400px" @keyup.enter.native="handleFilter" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="info" icon="el-icon-clear" @click="clearSearch">
            清除
          </el-button>
          <br>
          <el-select v-model="listQuery.searchRenwu.jianyanleibie" placeholder="检验类别" clearable style="width:100px" value="" @change="handleFilter">
            <el-option value="DJ" label="定期检验" />
            <el-option value="JJ" label="监督检验" />
            <el-option value="ZJ" label="制造检验" />
          </el-select>
          <el-date-picker v-model="listQuery.searchRenwu.shouliriqi" type="date" value-format="yyyy-MM-dd" placeholder="选择报检日期" style="width: 150px" @change="handleFilter" />
          <el-input v-model="listQuery.searchRenwu.shigongdanwei" placeholder="施工单位名称" clearable style="width: 300px" @keyup.enter.native="handleFilter" />
          <el-date-picker v-model="listQuery.searchRenwu.xianchangjianyanStart" type="date" value-format="yyyy-MM-dd" placeholder="现场检验日期（起）" style="width: 180px;" />
          <el-date-picker v-model="listQuery.searchRenwu.xianchangjianyanEnd" type="date" value-format="yyyy-MM-dd" placeholder="现场检验日期（止）" style="width: 180px;" />
          <el-select v-model="listQuery.searchRenwu.shouliren" filterable allow-create default-first-option clearable placeholder="请选择受理人员" style="width: 110px;">
            <el-option v-for="user in users" :key="user.id" :label="user.nickname" :value="user.nickname" />
          </el-select>
          <span class="radio-group-label">申请现场检验：</span>
          <el-radio-group v-model="listQuery.searchRenwu.zhongjianState" @change="handleFilter">
            <el-radio :label="0">
              否
            </el-radio>
            <el-radio :label="1">
              是
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      v-loading="showLoading"
      element-loading-text="正在加载"
      element-loading-spinner="el-icon-loading"
      :data="list"
      border
      fit
      highlight-current-row
      stripe
      width="100%"
      height="600px"
      :row-class-name="tableRowZhongjian"
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column align="center" label="序号" width="60">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="检验类别" prop="jianyanleibie" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.jianyanleibie === 'DJ'">定期检验</span>
          <span v-else-if="scope.row.jianyanleibie === 'JJ'">监督检验</span>
          <span v-else-if="scope.row.jianyanleibie === 'JJ' && scope.row.neibuleibie === 'SC'">首次检验</span>
          <span v-else-if="scope.row.jianyanleibie === 'ZJ'">制造检验</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="报检单号" prop="serialNumber" width="140" sortable="custom" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" />
      <el-table-column align="center" label="使用单位地址" prop="shiyongdanweiDizhi" />
      <el-table-column align="center" label="区划名称" prop="quhuamingcheng" width="110" sortable />
      <el-table-column align="center" label="报检日期" prop="shouliriqi" width="110" sortable />
      <el-table-column align="center" label="受理人" prop="shouliren" width="100" />
      <el-table-column v-if="departmentId !== 75" align="center" label="备注" prop="bjdBeizhu" width="80" />
      <el-table-column align="left" label="设备台数（待/总）" width="140">
        <template slot-scope="scope">
          <el-button type="success" size="small" circle icon="el-icon-view" title="预览报检单" @click="viewBjd(scope.row)" />
          <el-button style="margin-left:1px" size="small" circle @click="viewBjdRenwu(scope.row.bjdId)">
            <span style="color: #67C23A;font-weight: bold">{{ scope.row.allotNum }}</span> / <span style="color: #F56C6C;font-weight: bold">{{ scope.row.totalNum }}</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="listQuery.pageNum"
      :page-size="listQuery.pageSize"
      :total="totalCount"
      :page-sizes="[10, 20, 40, 100]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog :visible.sync="dialogVisible" :title="title" width="70%" @close="closeDialog">
      <el-container>
        <el-form>
          <el-form-item>
            <el-select v-model="departmentId" placeholder="请选择科室" style="width: 150px;" @change="selectDepartmentUser">
              <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id" />
            </el-select>
            <el-select v-model="renwudan.teamId" placeholder="请选择检验小组" style="width: 150px;" @change="selectTeamUser">
              <el-option v-for="team in teams" :key="team.id" :label="team.name" :value="team.id" />
            </el-select>
            <el-select v-model="renlingren" :collapse-tags="true" placeholder="请选择人员" multiple style="width: 160px;">
              <el-option v-for="user in users" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
            <el-button type="primary" @disabled="btnClick" @click="allotRenwu">
              执行分配
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="renwudan.xiadariqi" type="date" placeholder="选择下达日期" style="width: 150px;" />
            <el-date-picker v-model="renwudan.yuejianriqi" type="date" placeholder="选择约检日期" style="width: 150px;" @blur="setWanchengqixian()" />
            <el-date-picker v-model="renwudan.wanchengqixian" type="date" placeholder="选择完成期限" style="width: 150px;" />
            <el-select v-model="renwudan.jianyanleixing" :collapse-tags="true" placeholder="请选择检验类型" style="width: 130px;">
              <el-option key="初检" label="初检" value="初检" />
              <el-option key="复检" label="复检" value="复检" />
            </el-select>
            <el-input v-model="renwudan.beizhu" type="text" style="width: 240px;" placeholder="请填写备注信息" />
          </el-form-item>
        </el-form>
      </el-container>
      <el-table ref="allotList" :data="allotList" size="small" style="width: 150%" border fit highlight-current-row :row-class-name="tableRowBfZhongjian" @row-click="onDialogRowClick" @selection-change="handleDialogSelectionChange">
        <el-table-column type="selection" width="45" />
        <el-table-column align="center" label="序号" width="50" fixed="left">
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column v-if="allotSbzl === '2000'" align="center" label="设备名称" prop="shebeimingcheng" width="150" />
        <el-table-column align="center" :formatter="formatter.formatterCategory" label="检验项目" prop="neibuleibie" width="100" />
        <el-table-column align="center" label="下次检验日期" prop="xiacijianyanriqi" width="100" />
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" width="240px;" />
        <el-table-column v-if="allotSbzl !== '8000'" align="center" label="产品编号/出厂编号" prop="chanpinbianhao" width="140" />
        <el-table-column align="center" label="区划名称" prop="quhuamingcheng" width="80" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" width="160" />
        <el-table-column align="center" label="使用登记编号" prop="shiyongdengjibianhao" width="160" />
        <template v-if="allotSbzl === '8000'">
          <el-table-column align="center" label="管道长度(m)/数量(条)" prop="s32" width="140" />
          <el-table-column align="center" label="管道级别" prop="s7" width="140" />
        </template>
        <el-table-column align="center" label="申请现场检验日期" prop="shenqingxianchangriqi" width="160" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import Utils from '@/utils/contact'
export default {
  name: 'AllotListChengYa',
  components: { Sticky },
  data() {
    return {
      dialogVisible: false,
      totalCount: 0,
      list: [],
      sbzlList: [],
      listQuery: {
        pageNum: 1, // 页码
        pageSize: 20, // 每页条数
        orderBy: 'shouliriqi desc',
        searchRenwu: {
          shiyongdanwei: undefined,
          shebeizhongleidaima: '',
          bjState: '2'
        }
      },
      renwudan: {
        teamId: '',
        xiadariqi: '',
        yuejianriqi: '',
        wanchengqixian: '',
        jianyanleixing: '初检',
        beizhu: ''
      },
      tempDepartment: {},
      multipleSelection: [],
      allotList: [],
      depts: [],
      users: [],
      areas: [], // 区划数组
      departmentId: this.$store.getters.departmentId,
      renlingren: [],
      selection: [],
      departmentUserList: [],
      unAllotUserList: [],
      btnClick: false,
      showLoading: true,
      allotSbzl: '',
      teams: [],
      bjdids: '',
      dialogXianchangVisible: false,
      dialogXcjyVisible: false,
      bjdZhongjian: {
        bjdid: '',
        xianchangriqi: '',
        xianchangbeizhu: '',
        renwuIds: ''
      },
      title: '任务分配'
    }
  },
  created() {
    this.getList()
    this.getDepartment()
    this.getArea()
    this.getSbzlList()
    this.getUserList(this.departmentId)
    this.getTeamList(this.departmentId)
  },
  mounted() {
    const that = this
    this.common.$on('AllotListChengYaListRefresh', function() {
      that.handleFilter()
    })
  },
  methods: {
    getList() {
      this.showLoading = true
      this.apibjd({
        url: '/renwu/list',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.list = data.list
        this.totalCount = data.totalCount
        this.showLoading = false
        const messagePush = this.$store.getters.messageCount
        for (let i = 0; i < messagePush.length; i++) {
          if (messagePush[i].key === 'AllotList') {
            messagePush[i].value = this.totalCount
          }
          this.$store.state.messageCount = messagePush
        }
      })
    },
    getSbzlList() {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: undefined,
          level: '1'
        }
      }).then(data => {
        this.sbzlList = data
      })
    },
    handleSizeChange(val) {
      // 改变每页数量
      this.listQuery.pageSize = val
      this.handleFilter()
    },
    handleCurrentChange(val) {
      // 改变页码
      this.listQuery.pageNum = val
      this.getList()
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageSize + $index + 1
    },
    // 批量分配
    renwuFp() {
      this.allotList = []
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要操作的数据。', type: 'warning' })
        return false
      }
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0) {
          this.bjdIds = this.multipleSelection[i].bjdId
        } else {
          this.bjdIds = this.bjdIds + ',' + this.multipleSelection[i].bjdId
        }
      }
      this.apibjd({
        url: '/renwu/getAllotBaseList',
        method: 'post',
        data: {
          bjdIds: this.bjdIds
        }
      }).then(data => {
        this.allotList = data.list
        this.allotSbzl = this.allotList[0].shebeizhongleidaima
        this.renwudan = {
          xiadariqi: new Date()
        }
        if (this.multipleSelection[0].shebeileixing !== undefined && this.multipleSelection[0].shebeileixing !== null) {
          this.title = '任务分配（' + this.multipleSelection[0].shebeileixing + '）'
        }
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.allotList.toggleAllSelection()
          this.selection = data.list
        })
      })
    },
    // 任务异常退回
    returnToBjd() {
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要退回的数据。', type: 'warning' })
        return false
      }
      let bjdIds = ''
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0) {
          bjdIds = this.multipleSelection[i].bjdId
        } else {
          bjdIds = bjdIds + ',' + this.multipleSelection[i].bjdId
        }
      }
      // 查询任务的分配状态
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (this.multipleSelection[i].allotNum !== this.multipleSelection[i].totalNum) {
          this.$message({ message: '有任务已经分配，请重新选择。', type: 'warning' })
          return false
        } else {
          this.$prompt('请输入退回原因', '提示', {
            inputType: 'textarea',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(({ value }) => {
            this.apibjd({
              url: '/bjd/returnToBjd',
              method: 'get',
              params: {
                bjdIds: bjdIds,
                reason: value
              }
            }).then(data => {
              this.getList()
              this.$message({ message: '任务异常退回成功', type: 'success' })
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            })
          })
        }
      }
    },
    // 作废数据
    renwuZf() {
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要作废的数据。', type: 'warning' })
        return false
      }
      let bjdIds = ''
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0) {
          bjdIds = this.multipleSelection[i].bjdId
        } else {
          bjdIds = bjdIds + ',' + this.multipleSelection[i].bjdId
        }
      }
      this.$prompt('共选择了' + this.multipleSelection.length + '台设备进行作废，请输入作废原因！', '提示', {
        inputType: 'textarea',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value === null) {
          this.$message({ message: '请填写作废原因！', type: 'warning' })
          return false
        }
        this.apibjd({
          url: '/bjd/zfDbRenwuByBjdId',
          method: 'get',
          params: {
            bjdIds: this.$refs.list.selection.map(rw => {
              return rw.bjdId
            }).join(','),
            reason: value
          }
        }).then(data => {
          this.getList()
          if (data.count > 0) {
            this.$alert(data.count + '条任务作废成功！', '确认信息', {
              confirmButtonText: '确定'
            })
          } else {
            this.$message({ message: '任务作废失败！', type: 'warning' })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消作废'
        })
      })
    },
    viewBjd(bjd) {
      const type = '/finish'
      if (bjd.jianyanleibie === 'DJ') {
        this.$router.push({ path: '/bjd/bjd-dj-input/' + bjd.bjdId + '/' + bjd.shebeizhongleidaima + '/' + bjd.shebeizhongleidaima + type })
      } else {
        this.$router.push({ path: '/bjd/bjd-jj-input/' + bjd.bjdId + '/' + bjd.shebeizhongleidaima + '/' + bjd.shebeizhongleidaima + type })
      }
    },
    viewBjdRenwu(bjdid) {
      if (this.$store.getters.username === 'shiting') {
        return false
      }
      this.allotList = []
      this.bjdIds = bjdid
      this.apibjd({
        url: '/renwu/getAllotBaseList',
        method: 'post',
        data: {
          bjdIds: bjdid
        }
      }).then(data => {
        this.allotList = data.list
        this.allotSbzl = this.allotList[0].shebeizhongleidaima
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.allotList.toggleAllSelection()
          this.selection = data.list
        })
      })
    },
    clearSearch() {
      this.listQuery.searchRenwu = {
        bjState: '2'
      }
      this.getList()
    },
    // 表格单击选中行 getAllotListByBjdId
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    // 获取选中行的bjdId
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    onDialogRowClick(row) {
      this.$refs.allotList.toggleRowSelection(row)
    },
    handleDialogSelectionChange(val) {
      this.selection = val
    },
    // 查询检验科室
    getDepartment() {
      this.api({
        url: '/department/all',
        method: 'get'
      }).then(data => {
        this.depts = data
      })
    },
    getArea() { // 查询区划
      this.api({
        url: '/area/getShiArea',
        method: 'get',
        params: {
          shidaima: '370100'
        }
      }).then(data => {
        this.areas = data
      })
    },
    selectDepartmentUser(val) {
      this.renlingren = []
      this.getUserList(val)
    },
    getUserList(val) {
      this.api({
        url: '/user/getUserListByDepartmentId',
        method: 'get',
        params: {
          departmentId: val
        }
      }).then(data => {
        this.users = data
      })
    },
    openZhongjian() {
      if (this.multipleSelection.length !== 1) {
        this.$message({ message: '请在列表选择要进行现场检验的设备,只允许单台操作。', type: 'warning' })
        return false
      }
      if (this.multipleSelection[0].zhongjianriqi) {
        this.bjdZhongjian.xianchangriqi = this.multipleSelection[0].zhongjianriqi
      } else {
        this.bjdZhongjian.xianchangriqi = new Date()
      }
      this.bjdZhongjian.xianchangbeizhu = this.multipleSelection[0].zhongjianBeizhu
      this.dialogXianchangVisible = true
    },
    openBaseZhongjian() {
      if (this.multipleSelection.length !== 1) {
        this.$message({ message: '请在列表选择要操作的数据，只能选择单台设备。', type: 'warning' })
        return false
      }
      this.apibjd({
        url: '/renwu/getAllotBaseList',
        method: 'post',
        data: {
          bjdIds: this.multipleSelection[0].bjdId
        }
      }).then(data => {
        this.allotList = data.list
        this.dialogXcjyVisible = true
      })
    },
    clearBaseZhongjian() {
      if (this.multipleSelection.length !== 1) {
        this.$message({ message: '请在列表选择要操作的数据，只能选择单台设备。', type: 'warning' })
        return false
      }
      this.apibjd({
        url: '/renwu/clearZhongjian',
        method: 'get',
        params: {
          bjdId: this.multipleSelection[0].bjdId
        }
      }).then(data => {
        if (data === '清除成功！') {
          this.getList()
        }
      })
    },
    clearShenqingriqi(index) {
      this.apibjd({
        url: '/renwu/clearShenqingriqi',
        method: 'get',
        params: {
          renwuId: this.allotList[index].id
        }
      }).then(data => {
        if (data === '清除成功！') {
          this.allotList[index].shenqingxianchangriqi = null
        }
      })
    },
    closeDialog() {
      this.renlingren = []
      this.departmentId = this.$store.getters.departmentId
      this.users = this.getUserList(this.departmentId)
    },
    allotRenwu() {
      this.btnClick = true
      if (this.selection.length === 0) {
        this.$message({ message: '请选择要分配的数据。', type: 'warning' })
        return false
      }
      if (this.renlingren.length > 0) {
        for (let i = 0; i < this.teams.length; i++) {
          if (this.renwudan.teamId === this.teams[i].id) {
            this.renwudan.teamName = this.teams[i].name
            break
          }
        }
        for (let i = 0; i < this.depts.length; i++) {
          if (this.departmentId === this.depts[i].id) {
            this.renwudan.departmentName = this.depts[i].name
            break
          }
        }
        this.apibjd({
          url: '/renwu/completeAllot',
          method: 'post',
          data: {
            renwuList: this.selection,
            renlingren: this.renlingren,
            renwudan: this.renwudan,
            bjdids: this.bjdIds
          }
        }).then(() => {
          this.multipleSelection = []
          // 刷新分配任务列表
          this.getList()
          // 刷新我的任务列表
          Utils.$emit('task-list')
          this.$message({ message: '分配成功。', type: 'success' })
          this.dialogVisible = false
          this.showLoading = true
        })
      } else {
        this.$message({ message: '请选择要分配的人员。', type: 'warning' })
        return false
      }
    },
    tijiaoJianyan() {
      this.bjdZhongjian.bjdid = this.multipleSelection[0].bjdId
      this.apibjd({
        url: '/bjd/updBjdEndState',
        method: 'post',
        data: this.bjdZhongjian
      }).then(data => {
        this.$message.success('添加成功。')
        this.getList()
        this.dialogXianchangVisible = false
      })
    },
    tijiaoJianyanBf() {
      if (this.selection.length === 0) {
        this.$message({ message: '请在列表选择要操作的数据。', type: 'warning' })
        return false
      }
      this.bjdZhongjian.bjdid = this.multipleSelection[0].bjdId
      this.bjdZhongjian.renwuIds = this.$refs.allotList.selection.map(rw => {
        return rw.id
      }).join(',')
      this.apibjd({
        url: '/renwu/updBjdEndState',
        method: 'post',
        data: this.bjdZhongjian
      }).then(data => {
        this.$message.success('添加成功。')
        this.getList()
        this.dialogXcjyVisible = false
      })
    },
    getTeamList(departmentId) { // 获取对应组
      this.apibjd({
        url: '/team/getTeamList',
        method: 'get',
        params: { departmentId }
      }).then(data => {
        this.teams = data
      })
    },
    selectTeamUser(val) {
      for (let i = 0; i < this.teams.length; i++) {
        if (this.teams[i].id === val) {
          this.renlingren = JSON.parse(this.teams[i].renyuans)
          break
        }
      }
    },
    setWanchengqixian() {
      var date = new Date(this.renwudan.yuejianriqi)
      date.setMonth(date.getMonth() + 1)
      this.$set(this.renwudan, 'wanchengqixian', date)
    },
    tableRowZhongjian({ row, rowIndex }) {
      if (row.zhongjianState === 1) {
        return 'qiyezhongjian-row'
      } else if (row.zhongjianState === 2) {
        return 'keshizhongjian-row'
      }
      return ''
    },
    tableRowBfZhongjian({ row, rowIndex }) {
      if (row.shenqingxianchangriqi !== null) {
        return 'xianchangriqi-row'
      }
      return ''
    },
    sortChange(column) {
      if (column.order !== null) {
        this.listQuery.orderBy = column.prop + ' '
        this.listQuery.orderBy += column.order.replace('ending', '')
      } else {
        this.listQuery.orderBy = 'shouliriqi desc'
      }
      this.getList()
    }
  }
}
</script>

<style>
  /** 允许终检 */
  .el-table .qiyezhongjian-row {
    color: #0831e4;
  }
  .el-table .keshizhongjian-row {
    color: #da6b83;
  }
  .el-table .xianchangriqi-row {
    color: #66e41e;
  }
</style>
