<template>
  <div class="app-container">
    <div class="filter-container">
      <sticky style="margin-bottom: 10px;">
        <div class="sub-navbar">
          <el-button type="success" icon="el-icon-check" @click="batchUpdateBohui('success')">
            同意退回待分配列表
          </el-button>
          <el-button type="danger" icon="el-icon-close" @click="batchUpdateBohui('danger')">
            拒绝退回
          </el-button>
          <el-button type="primary" icon="el-icon-check" @click="renwuFp()">
            重新分配
          </el-button>
          <el-button type="danger" icon="el-icon-close" @click="renwuZf()">
            作废数据
          </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-input v-model="listQuery.serialNumber" placeholder="报检单号" clearable style="width: 160px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 300px" @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-input v-model="listQuery.zhucedaima" placeholder="注册代码" clearable style="width: 220px" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.shiyongdengjibianhao" placeholder="使用登记证编号" clearable style="width: 180px" @keyup.enter.native="handleFilter" />
        </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
      height="650px"
      width="100%"
      size="small"
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
    >
      <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="serialNumber" width="170" />
      <el-table-column align="center" label="设备种类" prop="shebeizhonglei" width="120" />
      <el-table-column :formatter="formatter.formatterCategory" align="center" label="检验类别" prop="neibuleibie" width="80" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" width="250" />
      <el-table-column align="center" label="注册代码" prop="zhucedaima" width="180" />
      <el-table-column align="center" label="使用登记编号" prop="shiyongdengjibianhao" width="140" />
      <el-table-column align="center" label="出厂编号" prop="chanpinbianhao" width="140" />
      <el-table-column align="center" label="报检日期" prop="shouliriqi" width="100" />
      <el-table-column align="center" label="区划名称" prop="quhuamingcheng" width="90" />
      <el-table-column :formatter="formatter.getChineseName" align="center" label="认领人" prop="renlingren" width="180" />
      <el-table-column align="center" label="退回原因" prop="returnReason" width="200" />
      <el-table-column align="center" label="任务退回操作" prop="rwState" width="190" fixed="right">
        <template slot-scope="scope">
          <span v-if="scope.row.highlight === 0">
            <el-button type="success" size="mini" circle icon="el-icon-check" title="同意" @click="updateBohui(scope.row.id, 'success')" />
            <el-button type="danger" size="mini" circle icon="el-icon-close" title="拒绝" @click="updateBohui(scope.row.id, 'danger')" />
          </span>&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button size="mini" type="info" icon="el-icon-message" title="查看退回原因" circle @click="viewBohui(scope.row.id)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageRow" @pagination="getList" />
    <!-- 驳回操作 -->
    <el-dialog :visible.sync="dialogBohuiVisible" title="驳回意见" width="50%">
      <el-table :data="infoNotes">
        <el-table-column align="center" type="index" label="序号" width="50" />
        <el-table-column align="center" prop="flowName" label="当前环节" width="120" />
        <el-table-column align="center" prop="infoSend" label="环节操作人" width="120" />
        <el-table-column align="center" prop="infoActor" label="环节处理人" width="180" />
        <el-table-column prop="infoNotes" label="执行操作" width="240" />
        <el-table-column align="center" prop="createTime" label="操作时间" width="200" />
      </el-table>
    </el-dialog>
    <!-- 任务分配 -->
    <el-dialog :visible.sync="dialogVisible" title="任务分配" width="60%" @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-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-button type="primary" @disabled="btnClick" @click="allotRenwu">
              执行分配
            </el-button>
          </el-form-item>
        </el-form>
      </el-container>
      <el-table ref="allotList" :data="allotList" size="small" style="width: 150%" border fit highlight-current-row @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 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" />
        <el-table-column v-if="allotSbzl === '8000'" align="center" label="管道长度(m)/数量(条)" prop="s32" width="140" />
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="dialogImageUrlsVisible" title="退回附件查看" width="60%" @close="dialogImageUrlsVisible = false">
      <el-image v-for="url in imageUrls" :key="url" :src="url" :preview-src-list="imageUrls" />
    </el-dialog>
  </div>
</template>
<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
import Utils from '../../utils/contact.js'
export default {
  name: 'BackRenwu',
  components: { Sticky, Pagination },
  data() {
    return {
      totalCount: 0,
      list: [],
      sbzlList: [],
      tempDepartment: {},
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20 // 每页条数
      },
      renwudan: {
        teamId: '',
        xiadariqi: '',
        yuejianriqi: '',
        wanchengqixian: '',
        jianyanleixing: '初检',
        beizhu: ''
      },
      multipleSelection: [],
      selection: [],
      showLoading: true,
      dialogBohuiVisible: false,
      dialogVisible: false,
      infoNotes: [],
      depts: [],
      users: [],
      areas: [], // 区划数组
      teams: [],
      allotList: [],
      renlingren: [],
      departmentId: this.$store.getters.departmentId,
      allotSbzl: '',
      btnClick: false,
      dialogImageUrlsVisible: false,
      imageUrls: [],
      jsonUrls: [],
      bjdids: ''
    }
  },
  created() {
    // this.getList()
    this.getSbzlList()
    this.getDepartment()
    this.getUserList(this.departmentId)
    this.getTeamList(this.departmentId)
  },
  methods: {
    getList() {
      this.apibjd({
        url: '/renwu/getTuihuiList',
        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 === 'BackRenwu') {
            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
      })
    },
    renwuFp() { // 任务分配
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要操作的数据。', type: 'warning' })
        return false
      }
      // for (let i = 0; i < this.multipleSelection.length; i++) {
      //   if (this.multipleSelection[i].highlight !== 1) {
      //     this.$message({ type: 'info', message: '请先"同意退回"在进行重新分配操作！！！' })
      //     return false
      //   }
      // } // 起重科室张楠需要此功能，电梯可以统一后需要退回到待分配里面。
      this.apibjd({
        url: '/renwu/getRenwuListByIds',
        method: 'get',
        params: {
          renwuids: this.$refs.list.selection.map(rw => {
            return rw.id
          }).join(',')
        }
      }).then(data => {
        this.allotList = data.list
        this.allotSbzl = this.allotList[0].shebeizhongleidaima
        this.renwudan = {
          xiadariqi: new Date()
        }
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs.allotList.toggleAllSelection()
          this.selection = data.list
        })
      })
    },
    viewBohui(id) { // 任务撤回
      this.api({
        url: '/taskinfo/list',
        method: 'get',
        params: {
          renwuId: id
        }
      }).then(data => {
        if (data !== '') {
          this.dialogBohuiVisible = true
          this.infoNotes = data
        }
      })
    },
    viewFujian(id) {
      // 查看附件
      this.apibjd({
        url: '/renwu/getRenwuBackFiles',
        method: 'get',
        params: {
          renwuId: id
        }
      }).then(data => {
        console.log(data)
        if (data.returnCode === 80001) {
          this.$message({
            message: '未找到相关附件！！！',
            type: 'error'
          })
        } else {
          this.imageUrls = []
          for (let i = 0; i < data.length; i++) {
            if (data[i].url !== undefined) {
              this.imageUrls.push(process.env.VUE_APP_IMG_URL + data[i].url)
            }
          }
          this.dialogImageUrlsVisible = true
        }
      })
    },
    batchUpdateBohui(type) {
      this.apibjd({
        url: '/renwu/updateRwState',
        method: 'get',
        params: {
          ids: this.$refs.list.selection.map(rw => {
            return rw.id
          }).join(','),
          type: type
        }
      }).then(data => {
        if (data !== '') {
          this.$message({
            message: '操作成功！！！',
            type: 'success'
          })
          this.getList()
          Utils.$emit('allot-list')
        } else {
          this.$message({
            message: '操作失败！！！',
            type: 'warning'
          })
        }
      })
    },
    updateBohui(id, type) {
      this.apibjd({
        url: '/renwu/updateRwState',
        method: 'get',
        params: {
          ids: id,
          type: type
        }
      }).then(data => {
        if (data !== '') {
          this.$message({
            message: '操作成功！！！',
            type: 'success'
          })
          this.getList()
          Utils.$emit('allot-list')
        } else {
          this.$message({
            message: '操作失败！！！',
            type: 'warning'
          })
        }
      })
    },
    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: [...new Set(this.$refs.list.selection.map(rw => {
              return rw.bjdId
            }))].join(',')
          }
        }).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
      }
    },
    // 作废数据
    renwuZf() {
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要作废的数据。', type: 'warning' })
        return false
      }
      this.$prompt('共选择了' + this.multipleSelection.length + '台设备进行作废，请输入作废原因！', '提示', {
        inputType: 'textarea',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value === null) {
          this.$message({ message: '请填写作废原因！', type: 'warning' })
          return false
        }
        this.apibjd({
          url: '/renwu/deleteRenwu',
          method: 'delete',
          params: {
            renwuIds: this.$refs.list.selection.map(rw => {
              return rw.id
            }).join(','),
            reason: value
          }
        }).then(data => {
          this.getList()
          if (data === 1) {
            this.$message.success('作废成功！')
          } else {
            this.$message.error('作废失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消作废'
        })
      })
    },
    getDepartment() {
      this.api({
        url: '/department/getAllDepartment',
        method: 'get'
      }).then(data => {
        this.depts = data
      })
    },
    getUserList(val) {
      this.api({
        url: '/user/getUserListByDepartmentId',
        method: 'get',
        params: {
          departmentId: val
        }
      }).then(data => {
        this.users = data
      })
    },
    getTeamList(departmentId) { // 获取对应组
      this.apibjd({
        url: '/team/getTeamList',
        method: 'get',
        params: { departmentId }
      }).then(data => {
        this.teams = data
      })
    },
    handleFilter() {
      // 查询事件
      console.log(this.listQuery)
      this.listQuery.pageNum = 1
      this.getList()
    },
    clearSearch() {
      this.listQuery = {
        pageNum: 1, // 页码
        pageRow: 20
      }
      this.getList()
    },
    onDialogRowClick(row) {
      this.$refs.allotList.toggleRowSelection(row)
    },
    handleDialogSelectionChange(val) {
      this.selection = val
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    closeDialog() {
      this.renlingren = []
      this.departmentId = this.$store.getters.departmentId
      this.users = this.getUserList(this.departmentId)
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    selectDepartmentUser(val) {
      this.renlingren = []
      this.getUserList(val)
    },
    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)
    }
  }
}
</script>
