<template>
  <!-- 分配任务3（可做公共组件） -->
  <div style="padding:20px;height:100%;background:white;display: flex;">
    <div class="" v-show="showRight" :style="{ width: showRight ? '300px' : '0px' }">
      <showColumn :projectId="projectId" @markedFields="handleMarkedFields"></showColumn>
    </div>
    <el-container :style="{ width: showRight ? 'calc( 100% - 300px )' : '100%' }">
      <el-header class="header1">
        <!-- <div > -->
        <div style="display: flex;align-items: center;">
          <div style="margin-right: 10px;">
            <el-tooltip class="item" effect="dark" :content="(showRight ? '隐藏' : '显示') + '右侧自定义栏位'" placement="top">
              <i :class="showRight ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
                style="font-size: 25px; margin-left: 10px;color: #2f2f2f; cursor: pointer"
                @click="showRight = !showRight"></i>
            </el-tooltip>
          </div>
          <span>总件数：{{ totalNumber }}</span>
          <span> 剩余件数：{{ leaveNumber }}</span>
        </div>
        <div>
          <label>任务类型：</label>
          <el-select v-model="taskType">
            <el-option label="对比任务" value="3"></el-option>
            <el-option label="标引任务" value="0"></el-option>
          </el-select>
        </div>
        <!-- 平均分配 -->
        <div>
          <el-button @click="getPerson">添加人员</el-button>
          <el-button @click="finish" v-if="params">完成</el-button>
        </div>
        <!-- </div> -->
      </el-header>
      <el-main>
        <div style="margin-top:20px">
          <el-table v-if="showTable" :data="tableData" v-loading="loading" style="width: 100%" border>
            <el-table-column prop="name" label="人员名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="tenantName" label="所属租户" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="email" label="邮箱" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="patentNum" label="件数" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="scope.row.vVisible">{{ scope.row.patentNum }}</span>
                <span v-if="!scope.row.vVisible">
                  <el-input v-model="scope.row.patentNum2" size="small" placeholder="请输入件数"></el-input>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="300px">
              <template slot-scope="scope">
                <div class="special">
                  <el-button v-if="scope.row.vVisible" class="items" @click.native="edit(scope.row)"
                    :disabled="scope.row.isChoose">编辑</el-button>
                  <el-button v-else class="items" @click.native="save(scope.row)">保存</el-button>
                  <el-button @click="chosePatentFile(scope.row)" v-if="scope.row.isChoose != true">选择</el-button>
                  <el-tooltip v-else class="item" effect="dark" content="取消选择的专利" placement="top">
                    <el-button @click="cancelChoose(scope.row)">取消</el-button>
                  </el-tooltip>
                  <el-button @click="removePerson(scope)" type="danger">移除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>




    <el-dialog title="温馨提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <div class="spanDiv">
        <div>
          <span class="spanCountdown">{{ countdown }}</span>
          <span class="spanCenter">秒后跳转到<span class="spanJump" @click="toRouter">报告管理</span>页面</span>
        </div>
      </div>
    </el-dialog>


    <!-- 选择人员 -->
    <personList ref="personList" @getPersonIds="getPersonIds"></personList>
    <!-- 选择专利 -->
    <checkPatent ref="checkPatent" :oldSearchOption="oldSearchOption" :customFields="customFields"
      @checkPatentList="checkPatentList"></checkPatent>

    <examine ref="examine" @save="handleSave" :title="'添加分配任务'" :isShow="false">
    </examine>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import personList from '@/views/components/dialog/person.vue'
import checkPatent from '../../checkPatent/checkPatent.vue'
import examine from '@/views/components/dialog/examine.vue'
import showColumn from './showColumn.vue'
export default {
  components: {
    personList,
    checkPatent,
    examine,
    showColumn,
  },
  props: {
    projectId: {
      default: '',
    },
    oldSearchOption: {
      default: () => {
        return {}
      }
    },
    customFields: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      // 
      showRight: false,
      totalNumber: 0,//总件数
      leaveNumber: 0,//剩余件数
      // 任务类型
      taskType: "3",
      // 表格数据源
      tableData: [],
      // 分页信息
      queryParams: {
        current: 1,
        size: 10,
      },
      // 表格的loading
      loading: false,
      // 控制温馨提示弹窗
      dialogVisible: false,
      // 倒计时初始值
      countdown: 3,
      //当前数据
      row: {},
      //控制table视图显示
      showTable: true,
      // 完成？？？
      params: {},
      // 自定义栏位
      markedFields: [],
    }
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.out()
      }
    },
  },
  created() {

  },
  async mounted() {
    await this.getList()
    this.getUser()
  },
  methods: {
    // 倒计时
    out() {
      this.timer = setInterval(() => {
        if (this.countdown == 0) {
          this.$router.replace("/AllReport");
          clearInterval(this.timer);
          this.dialogVisible = false
        } else {
          this.countdown--;
        }
      }, 1000);
    },
    //获取专利列表
    async getList() {
      let params = {
        ...this.queryParams,//分页信息
        projectId: this.projectId,
        searchQuery: this.$commonJS.objectToString(this.oldSearchOption),//检索条件
        customFields: this.customFields,
        orderDTOList: [],//排序信息
      }
      await this.$api.QueryPatent(params).then(res => {
        if (res.code == 200) {
          this.totalNumber = res.data.total
          this.leaveNumber = res.data.total
        }
      }).catch(error => {
        this.totalNumber = 0
        this.leaveNumber = 0
      })
    },
    getUser() {
      let user = JSON.parse(JSON.stringify(this.userinfo))
      user.patentNum = this.totalNumber
      user.vVisible = true
      user.isChoose = false
      user.isEdit = false
      this.tableData.push(user)
    },
    // 点击直接跳转页面
    toRouter() {
      this.$router.replace("/AllReport");
    },
    // 关闭温馨提示的弹窗
    handleClose() {
      this.dialogVisible = false;
    },
    //移除人员
    removePerson(scope) {
      let index = scope.$index
      if (index != -1) {
        this.tableData.splice(index, 1)
      }
      this.handleConfirm()
    },
    // 取消
    cancelChoose(row) {
      row.patentNos = []
      this.$set(row, 'patentNum', 0)
      row.isChoose = false
      this.handleConfirm()
    },
    // 选择专利
    chosePatentFile(row) {
      this.row = row
      var patentNoList = this.getPatentNoList()
      this.$refs.checkPatent.open(this.projectId, patentNoList)
    },
    getPatentNoList() {
      var patentNoList = []
      this.tableData.forEach(item => {
        if (item.patentNos) {
          patentNoList = patentNoList.concat(item.patentNos)
        }
      })
      return patentNoList
    },
    // 子组件选择的专利号数组数据 
    checkPatentList(val) {
      if (val.length > 0) {
        this.row.isChoose = true
        this.row.patentNos = val
        this.$set(this.row, 'patentNum', val.length)
        this.handleConfirm()
      }
    },

    //编辑
    edit(row) {
      this.$set(row, 'patentNum2', row.patentNum)
      row.vVisible = !row.vVisible
      // this.tableData = JSON.parse(JSON.stringify(this.tableData))
    },
    //保存
    save(row) {
      if (isNaN(row.patentNum2)) {
        this.$message.error('请输入数字')
        return false
      } else if (Number(row.patentNum2) < 0 || Number(row.patentNum2) + this.leaveNumber > this.totalNumber) {
        this.$message.error('请输入正确数量')
        return false
      }
      row.vVisible = !row.vVisible
      // row.patentNum = row.patentNum2
      this.$set(row, 'patentNum', row.patentNum2)
      row.isEdit = true
      row.patentNos = []
      this.handleConfirm()
    },
    //完成打开弹窗
    finish() {
      this.$refs.examine.open()
    },
    handleMarkedFields(val) {
      this.markedFields = val
    },
    // 发送任务
    handleSave(form) {
      let params = {
        projectId: this.projectId,
        taskType: this.taskType,
        ...form,
        stringRequest: {
          projectId: this.projectId,
          searchQuery: this.$commonJS.objectToString(this.oldSearchOption || {}),//列表上方检索条件
          customFields: this.customFields,//统计检索
        },//检索内容条件
        markedFields: this.markedFields,//自定义栏位
        personAssignedDTOList: this.tableData.map(item => {
          return {
            personId: item.id,
            patentNum: item.patentNum,
            patentNos: item.patentNos || [],
          }
        }),
      }
      this.$api.addMarkTask(params).then(res => {
        if (res.code == 200) {
          this.$message('添加分配任务成功')
          this.$refs.examine.handleCloseTask()
          this.dialogVisible = true
        }
      })
    },

    // 添加人员
    getPerson() {
      var personIds = this.tableData.map(item => item.id)
      var persons = JSON.parse(JSON.stringify(this.tableData))
      this.$refs.personList.open(personIds, persons)
    },
    //获取子组件返回的人员信息
    getPersonIds({ personIds, persons }) {
      if (persons.length > 0) {
        persons.forEach(item => {
          item.patentNum = 0
          this.$set(item, 'vVisible', true)
          if (this.tableData.length > 0) {
            let index = this.tableData.findIndex(dataItem => {
              return dataItem.id == item.id
            })
            if (index != -1) {
              // this.tableData.splice(index,1)
            } else {
              this.tableData.push(item)
            }
          } else {
            this.tableData.push(item)
          }
        });
        this.handleConfirm()
      }
    },

    // 平均分配
    handleConfirm() {
      if (this.tableData.length == 0) {
        this.$message.warning('请先选择人员！！！')
        return false
      }
      var { user, leaveNumber } = this.clearPatentNum()
      if (user.length == 0) {
        this.leaveNumber = leaveNumber
        return
      }

      var pjNum = parseInt(leaveNumber / user.length) ? parseInt(leaveNumber / user.length) : 0
      if (pjNum != 0) {
        user.forEach(item => {
          this.$set(item, 'patentNum', pjNum)
        })
      }
      var leaveNumber2 = leaveNumber - (user.length * pjNum)
      try {
        user.forEach(item => {
          if (leaveNumber2 > 0) {
            var num = item.patentNum + 1
            this.$set(item, 'patentNum', num)
            leaveNumber2--
          } else {
            throw Error();
          }
        })
      }
      catch {

      }
      this.leaveNumber = 0
      this.refreshTable()
    },
    //刷新表格
    refreshTable() {
      this.showTable = false
      this.$nextTick(() => {
        this.showTable = true
      })
    },
    //清空人员分配专利数量
    clearPatentNum() {
      var user = []
      var leaveNumber = this.totalNumber
      this.tableData.forEach(item => {
        if (!item.isChoose && !item.isEdit) {
          item.patentNum = 0
          user.push(item)
        } else {
          leaveNumber -= item.patentNum
        }
      })
      return {
        user,
        leaveNumber
      }
    },

  },

}
</script>

<style lang="scss" scoped>
.header1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spanDiv {
  display: flex;
  justify-content: center;
  height: 100px;
}

.spanCountdown {
  color: red;
  font-size: 24px;
  margin: 10px;
}

.spanCenter {
  margin: 0;
  font-size: 16px;
}

.spanJump:hover {
  cursor: pointer;
  color: red;
  text-decoration: underline;
}

.spanJump {
  font-size: 16px;
  margin: 10px 0;
  color: #42A5F5;
}
</style>