<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" icon="el-icon-circle-check-outline" @click="renwuFinish">
            分配完成
          </el-button>
        </div>
      </sticky>
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.serialNumber" placeholder="流水号" clearable style="width: 160px" />
          <el-input v-model="listQuery.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 400px" @keyup.enter.native="handleFilter" />
          <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-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table ref="list" v-loading.body="listLoading" :data="list" element-loading-text="拼命加载中" 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">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="流水号" prop="serialNumber" min-width="40" />
      <el-table-column align="center" label="检验类别" prop="jianyanleibie" min-width="40" />
      <el-table-column align="center" label="设备种类" prop="shebeizhonglei" min-width="40" />
      <el-table-column align="center" label="设备名称" prop="shebeimingcheng" min-width="40" />
      <el-table-column align="center" label="使用单位" prop="shiyongdanwei" min-width="120" />
      <el-table-column align="center" label="联系人" prop="shiyongdanweiLianxiren" min-width="40" />
      <el-table-column align="center" label="联系电话" prop="shiyongdanweiDianhua" min-width="40" />
      <el-table-column align="center" label="报检日期" prop="shouliriqi" min-width="40" />
      <el-table-column align="center" label="区划名称" prop="quhuamingcheng" min-width="40" />
      <el-table-column align="center" label="操作" min-width="50">
        <template slot-scope="scope">
          <el-popover placement="right" width="1100" trigger="click">
            <div class="filter-container" style="padding-bottom: 3px;">
              <el-button icon="el-icon-edit" type="success" @click="newProject">
                新建设备
              </el-button>
              <el-button icon="el-icon-circle-plus-outline" type="primary" @click="addParamBjd(scope.$index)">
                追加设备
              </el-button>
            </div>
            <el-table ref="shoppingTable" :data="shoppingCartData" border style="width: 100%;" height="350">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="shebeileibie" label="设备类别" />
              <el-table-column prop="shebeipinzhong" label="设备品种" />
              <el-table-column prop="zhucedaima" label="注册代码" min-width="140" />
              <el-table-column prop="shiyongdengjibianhao" label="使用登记编号" min-width="120" />
              <el-table-column prop="chanpinbianhao" label="产品/出厂编号" min-width="80" />
              <el-table-column prop="danweineibubianhao" label="单位内编号" min-width="60" />
              <el-table-column prop="xiacijianyanriqi" label="下次检验日期" min-width="90" />
              <el-table-column prop="fpState" label="分配状态" min-width="60">
                <template slot-scope="scopeParam">
                  <el-tag v-if="scopeParam.row.fpState===true" type="success">
                    已分配
                  </el-tag>
                  <el-tag v-else type="primary">
                    未分配
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="65">
                <template slot-scope="scopeParam">
                  <el-button v-if="scopeParam.row.rwState == null" type="danger" icon="el-icon-delete" @click="delBjdBase(scopeParam.$index)" />
                </template>
              </el-table-column>
            </el-table>
            <el-button slot="reference" style="margin-left:1px" size="medium" round @click="moveCart(scope.$index)">
              <span style="color: #67C23A;font-weight: bold">{{ scope.row.count === null ? 0 : scope.row.count }}</span> / <span style="color: #F56C6C;font-weight: bold">{{ scope.row.totalNum }}</span>
            </el-button>
          </el-popover>
        </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="dialogVisible" title="任务分配" @close="closeDialog">
      <el-container>
        <el-header>
          <el-select v-model="departmentId" placeholder="请选择科室" style="width: 240px;" @change="selectDepUser">
            <el-option v-for="dept in depts" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
          <el-select v-model="renlingren" :collapse-tags="true" placeholder="请选择人员" multiple style="width: 240px;">
            <el-option v-for="user in users" :key="user.id" :label="user.nickname" :value="user.id" />
          </el-select>
          <el-button type="primary" @click="allotRenwu">
            执行分配
          </el-button>
        </el-header>
      </el-container>
      <el-table ref="allotList" :data="allotList" size="small" style="width: 100%" 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">
          <template slot-scope="scope">
            <span v-text="getIndex(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" min-width="200px;" />
        <el-table-column align="center" label="设备名称" prop="shebeimingcheng" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" min-width="120px;" />
        <el-table-column align="center" label="使用登记编号" prop="shiyongdengjibianhao" />
        <el-table-column align="center" label="产品/出厂编号" prop="chanpinbianhao" />
        <el-table-column align="center" label="报检日期" prop="shouliriqi" />
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="dialogBaseInfoVisible" title="检索设备并添加" width="80%" max-height="600px">
      <el-form>
        <el-form-item>
          <el-input v-model="listQueryBase.shiyongdanwei" placeholder="使用单位名称" clearable style="width: 400px" @keyup.enter.native="handleFilterBase" />
          <el-input v-model="listQueryBase.zhucedaima" placeholder="注册代码" clearable style="width: 160px" />
          <el-input v-model="listQueryBase.shiyongdengjibianhao" placeholder="使用登记编号" clearable style="width: 160px" />
          <el-input v-model="listQueryBase.chanpinbianhao" placeholder="产品/出厂编号" clearable style="width: 160px" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilterBase">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table ref="allotList" :data="listBase" style="width: 100%" 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">
          <template slot-scope="scope1">
            <span v-text="getIndex(scope1.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="使用单位" prop="shiyongdanwei" min-width="180px;" />
        <el-table-column align="center" label="注册代码" prop="zhucedaima" min-width="120px;" />
        <el-table-column align="center" label="使用登记编号" prop="shiyongdengjibianhao" />
        <el-table-column align="center" label="产品/出厂编号" prop="chanpinbianhao" />
        <el-table-column align="center" label="下次检验日期" prop="xiacijianyanriqi" />
        <el-table-column align="center" label="操作">
          <template slot-scope="scope1">
            <el-button type="success" icon="el-icon-circle-plus-outline" @click="addBaseToBjd(scope1.$index)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalCountBase>0" :total="totalCountBase" :page-num.sync="listQueryBase.pageNum" :page-row.sync="listQueryBase.pageRow" @pagination="getListBase" />
    </el-dialog>

    <el-dialog :visible.sync="dialogFormVisibleAddBase" title="添加设备">
      <el-form ref="bjdParam" :model="bjdParam" class="small-space" label-position="left" label-width="120px" style="width: 300px; margin-left:50px;">
        <el-form-item label="设备类别" prop="shebeileibiedaima" required>
          <el-select v-model="bjdParam.shebeileibiedaima" placeholder="设备类别" style="width: 215px" @change="getSbpzList">
            <el-option v-for="item in sblbList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备品种" prop="shebeipinzhongdaima" required>
          <el-select v-model="bjdParam.shebeipinzhongdaima" placeholder="设备品种" style="width: 215px">
            <el-option v-for="item in sbpzList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="注册代码" prop="zhucedaima" required>
          <el-input v-model="bjdParam.zhucedaima" type="text" />
        </el-form-item>
        <el-form-item label="使用登记编号" prop="shiyongdengjibianhao" required>
          <el-input v-model="bjdParam.shiyongdengjibianhao" type="text" />
        </el-form-item>
        <el-form-item label="产品/出厂编号" prop="chanpinbianhao" required>
          <el-input v-model="bjdParam.chanpinbianhao" type="text" />
        </el-form-item>
        <el-form-item label="单位内编号" prop="danweineibubianhao">
          <el-input v-model="bjdParam.danweineibubianhao" type="text" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAddBase = false">
          取 消
        </el-button>
        <el-button type="success" @click="createRenwu">
          创 建
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Sticky from '@/components/Sticky'
import Pagination from '@/components/Pagination'
export default {
  name: 'Project',
  components: { Sticky, Pagination },
  data() {
    return {
      dialogVisible: false,
      dialogBaseInfoVisible: false,
      dialogFormVisibleAddBase: false,
      totalCount: 0,
      totalCountBase: 0,
      list: [],
      listBase: [],
      listLoading: false,
      sbzlList: [],
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        bjState: 2, // 只查询报检状态是已审核的数据。
        shiyongdanwei: undefined,
        shebeizhongleidaima: undefined
      },
      listQueryBase: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        shebeizhongleidaima: undefined
      },
      shoppingCartData: [],
      multipleSelection: [],
      allotList: [],
      depts: [],
      users: [],
      departmentId: this.$store.getters.departmentId,
      renlingren: [],
      selection: [],
      bjdId: '',
      bjdParam: {
        bjdId: undefined,
        zhucedaima: '/',
        shiyongdengjibianhao: '',
        chanpinbianhao: '',
        shebeileibiedaima: '',
        shebeipinzhongdaima: '',
        danweineibubianhao: '',
        shebeizhongleidaima: ''
      },
      sblbList: [],
      sbpzList: []
    }
  },
  created() {
    this.getList()
    this.getDepartment()
    this.getSbList(undefined, undefined, 1)
    this.getUserList(this.departmentId)
  },
  methods: {
    getList() {
      this.listLoading = true
      this.api({
        url: '/renwu/bjdlist',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        this.listLoading = false
        this.list = data.list
        this.totalCount = data.totalCount
      })
    },
    getListBase() {
      // 查询列表
      this.listLoading = true
      this.api({
        url: '/baseInfo/list',
        method: 'get',
        params: this.listQueryBase
      }).then(data => {
        this.listLoading = false
        this.listBase = data.list
        this.totalCountBase = data.totalCount
      })
    },
    getSblbList(val) {
      this.sbpzList = []
      this.getSbList(val, undefined, 2)
    },
    getSbpzList(val) {
      this.sbpzList = []
      this.getSbList(this.bjdParam.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
            return ''
          case 3:
            this.sbpzList = data
            return ''
          default:
            this.sbzlList = data
            return ''
        }
      })
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleFilterBase() {
      // 查询事件
      this.listQueryBase.pageNum = 1
      this.getListBase()
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    // 批量分配
    renwuFp() {
      if (this.multipleSelection.length === 0) {
        this.$message({ message: '请在列表选择要操作的数据。', type: 'warning' })
        return false
      }
      const userId = []
      let bjdIds = ''
      for (let i = 0; i < this.multipleSelection.length; i++) {
        if (i === 0) {
          bjdIds = this.multipleSelection[i].id
        } else {
          bjdIds = bjdIds + ',' + this.multipleSelection[i].id
        }
        let membername = this.multipleSelection[i].member
        if (membername.indexOf('[') !== -1) {
          membername = membername.substring(1, membername.length - 1)
        }
        let userIdArray = []
        userIdArray = membername.split(',')
        for (let i = 0; i < userIdArray.length; i++) {
          userId.push(parseInt(userIdArray[i]))
        }
      }
      this.renlingren = userId
      this.api({
        url: '/renwu/getAllotBaseList',
        method: 'post',
        data: {
          bjdIds: bjdIds
        }
      }).then(data => {
        this.allotList = data.list
      })
      this.dialogVisible = true
    },
    // 查看报检单
    addParamBjd(index) {
      this.dialogBaseInfoVisible = true
      this.listQueryBase.shebeizhongleidaima = this.list[index].shebeizhongleidaima
      this.listQueryBase.shiyongdanwei = this.list[index].shiyongdanwei
      this.getListBase()
    },
    addBaseToBjd(index) {
      // 验证是否已经追加过
      const baseid = this.listBase[index].id
      for (let i = 0; i < this.shoppingCartData.length; i++) {
        if (this.shoppingCartData[i].baseId === baseid) {
          this.$message({ message: '该项目中已存在此设备，请勿重复添加。', type: 'warning' })
          return false
        }
      }
      this.api({
        url: '/bjd/addProjectByBaseId',
        method: 'get',
        params: {
          bjdId: this.bjdId,
          baseId: baseid
        }
      }).then(data => {
        if (data === 1) {
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: '添加失败！'
          })
        }
      })
    },
    newProject() {
      this.dialogFormVisibleAddBase = true
      const sbzl = this.bjdParam.shebeizhongleidaima
      this.bjdParam = {}
      this.getSblbList(sbzl)
      this.bjdParam.shebeizhongleidaima = sbzl
    },
    createRenwu() {
      this.$refs['bjdParam'].validate(valid => {
        if (valid) {
          this.bjdParam.bjdId = this.bjdId
          this.api({
            url: '/bjd/newProject',
            method: 'post',
            data: this.bjdParam
          }).then(() => {
            this.dialogFormVisibleAddBase = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    delBjdBase(index) {
      this.api({
        url: '/bjd/delProject',
        method: 'get',
        params: {
          paramId: this.shoppingCartData[index].bjdParamId
        }
      }).then(data => {
        if (data === 1) {
          this.getBjdParam()
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: '删除失败！'
          })
        }
      })
    },
    moveCart(index) {
      this.bjdId = this.list[index].id
      this.bjdParam.shebeizhongleidaima = this.list[index].shebeizhongleidaima
      this.getBjdParam()
    },
    getBjdParam() {
      this.api({
        url: '/renwu/getAllotListByBjdId',
        method: 'get',
        params: {
          bjdId: this.bjdId
        }
      }).then(data => {
        this.shoppingCartData = data.list
      })
    },
    // 表格单击选中行
    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/getAllDepartment',
        method: 'get'
      }).then(data => {
        this.depts = data
      })
    },
    selectDepUser(val) {
      this.getUserList(val)
    },
    getUserList(val) {
      this.api({
        url: '/user/getUserListByDepartmentId',
        method: 'get',
        params: {
          departmentId: val
        }
      }).then(data => {
        this.users = data
      })
    },
    closeDialog() {
      this.renlingren = []
      this.departmentId = this.$store.getters.departmentId
      this.users = this.getUserList(this.departmentId)
    },
    allotRenwu() {
      if (this.selection.length === 0) {
        // this.$message({ message: '请选择要分配的数据。', type: 'warning' })
        // return false
      }
      if (this.renlingren.length > 0) {
        this.api({
          url: '/renwu/completeAllot',
          method: 'post',
          data: {
            renwuList: this.selection.length === 0 ? this.allotList : this.selection,
            renlingren: this.renlingren
          }
        }).then(() => {
          this.$message({ message: '分配成功。', type: 'success' })
          this.dialogVisible = false
          this.getList()
        })
      } else {
        this.$message({ message: '请选择要分配的人员。', type: 'warning' })
        return false
      }
    },
    renwuFinish() {
      let bjdIds = ''
      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].count != null) {
          this.$message({ message: '该项目中存在未分配设备，请确认后再执行该操作。', type: 'warning' })
          return false
        }
        if (i === 0) {
          bjdIds = this.multipleSelection[i].id
        } else {
          bjdIds = bjdIds + ',' + this.multipleSelection[i].id
        }
      }
      this.api({
        url: '/bjd/editBjState',
        method: 'post',
        data: {
          bjdId: bjdIds,
          bjState: '3'
        }
      }).then(() => {
        this.$message({ message: '分配成功。', type: 'success' })
        this.dialogVisible = false
        this.getList()
      })
    }
  }
}
</script>
