<template>
  <div class="height_100">
    <el-container>
      <el-header style="display: flex;justify-content: space-between;align-items: center;">
        <div>
          <mySearch :SearchFields="searchFiled" @search="search" :searchValue="searchOption"></mySearch>
        </div>
        <div>
          <el-button v-if="!show" class="margin-right_10" type="primary" size="small" @click="createTask">创建任务</el-button>
        </div>
      </el-header>
      <el-main class="height_100">
        <el-table :data="tableData" height="calc(100% - 1px)" style="width: 100%;" border
          header-row-class-name="custom-table-header" @sort-change="sortChange">
          <el-table-column label="#" align="center" width="80px">
            <template slot-scope="scope">
              <div>
                {{ (queryParams.current - 1) * queryParams.size + scope.$index + 1 }}
              </div>
            </template>
          </el-table-column>

          <el-table-column v-for="item in columnList" :key="item.value" :prop="item.value"
            :render-header="$commonJS.renderHeaderMethods" :label="item.name" sortable="custom" align="center">
            <template slot-scope="scope">
              <div v-if="['name'].includes(item.value)">
                <el-link @click="handleItem(scope.row, item.value)">
                  <span v-html="$commonJS.getColumnData(scope.row, item)"></span>
                </el-link>
              </div>
              <div v-else-if="['type'].includes(item.value)"
                v-html="$commonJS.getColumnData(scope.row, item, null, { data: taskType })"></div>
              <div v-else-if="['status'].includes(item.value)"
                v-html="$commonJS.getColumnData(scope.row, item, null, { data: taskStatus })"></div>
              <div v-else v-html="$commonJS.getColumnData(scope.row, item)"></div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="180px">
            <template slot-scope="scope">
              <div>
                <el-dropdown split-button type="primary" size="small" @command="handleCommand($event, scope.row)"
                  @click="handleTask(scope.row)">
                  <span v-if="scope.row.status != 2 || scope.row.handlerName != userinfo.name">查 看</span>
                  <span v-else>处 理</span>
                  <el-dropdown-menu slot="dropdown" style="text-align: center;">
                    <el-dropdown-item command="1" v-if="[6].includes(scope.row.type)">查看审核记录</el-dropdown-item>
                    <el-dropdown-item command="4"
                      v-if="scope.row.status != 3 && (scope.row.createName == userinfo.name && [1, 5, 6, 7].includes(scope.row.type))">编
                      辑</el-dropdown-item>
                    <el-dropdown-item command="3" v-if="[4, 6].includes(scope.row.type) && scope.row.status == 2">完
                      成</el-dropdown-item>
                    <el-dropdown-item command="5"
                      v-if="[4].includes(scope.row.type) && scope.row.status == 2 && scope.row.createName == userinfo.name">确认协同结果</el-dropdown-item>
                    <el-dropdown-item command="2"
                      v-if="scope.row.createName == userinfo.name || (scope.row.type == 5 && !scope.row.handlerName.includes('@'))"
                      divided style="color: red;">取 消</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="pagination">
        <el-pagination background layout="total, prev, pager, next, jumper" :current-page.sync="queryParams.current"
          :page-size.sync="queryParams.size" @current-change="handleCurrentChange" :total="queryParams.total">
        </el-pagination>
      </el-footer>
    </el-container>


    <auditRecords ref="auditRecords"></auditRecords>
    <createTask ref="createTaskDialog" :id="id" :processId="processId" @isCreate="isCreate"></createTask>
    <handleTask1 ref="handleTask1Dialog" @isSuccess="isSuccess"></handleTask1>
    <handleTask2 ref="handleTask2Dialog" @isSuccess="isSuccess"></handleTask2>
    <lookReport ref="lookReport" @isSuccess="isSuccess"></lookReport>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { column, optionsData } from '@/views/patentMining/components/mixins/index2'
import { taskPatentMining } from './mixins/task'
import auditRecords from '@/views/patentMining/components/dialog/auditRecords.vue'
import createTask from '@/views/patentMining/components/dialog/createTask.vue'
import handleTask1 from '@/views/patentMining/components/dialog/handleTask1.vue'
import handleTask2 from '@/views/patentMining/components/dialog/handleTask2.vue'
import lookReport from '@/views/report/components/dialog/lookReport.vue'
export default {
  mixins: [column, optionsData, taskPatentMining],
  // type区分是从哪里进入
  props: {
    type: {
      default: 1
    },
    projectId: '',
    processId: '',
    show: {
      type: Boolean,
      default: false
    },
  },
  components: {
    auditRecords,
    createTask,
    handleTask1,
    handleTask2,
    lookReport,
  },
  data() {
    return {
      // table数据
      tableData: [],
      // 分页及总数信息
      queryParams: {
        current: 1,
        size: 10,
        total: 0,
      },
      searchFiled2: {
        projectId: this.projectId,
        processId: this.processId
      },
      // 检索字段
      searchFiled: [],
      // 检索字符串
      searchOption: {},
      //排序字段
      sort: [{ "orderBy": "createTime", "orderType": 1 }],
      // 检索字段标识
      searchType: {
        1: 'projectTask',//专利挖掘任务清单检索字段
      },
      // 任务类型
      taskType: {
        0: '标引任务',
        1: '项目开卷审核任务',
        2: '检索条件任务',
        3: '对比任务',
        4: '协同任务',
        5: '任务审核任务',
        6: '文件分配任务',
        7: '文件审核任务',
      },
      // 任务状态
      taskStatus: {
        1: '审核中',
        2: '处理中',
        3: '已完成',
        4: '缺少资料',
        5: '取消',
      },
    }
  },
  watch: {
    processId(val) {
      if (val) {
        this.searchFiled2.processId = val
        this.tableData = []
        this.getList()
      }

    }
  },
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
  },
  async mounted() {
    // 获取table栏位
    this.columnList = await this.$commonJS.getCustomField('projectTask')
    // 获取栏位
    await this.getColumn()
    // 获取数据
    this.getList()
  },
  methods: {
    // 创建分配任务成功
    isCreate(val) {
      if (val) {
        this.getList()
      }
    },
    // 分配任务审核任务新增成功
    isSuccess(val) {
      if (val) {
        this.getList()
      }
    },
    // 请求数据
    getList() {
      let searchOption = {
        ...this.searchFiled2,//固有检索字段
        ...this.searchOption
      }
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(searchOption),//检索条件
        orderDTOList: this.sort,//排序信息
      }

      this.$api.queryProjectTask(params).then(response => {
        if (response.code == 200) {
          this.tableData = response.data.data
          this.queryParams.current = response.data.current
          this.queryParams.size = response.data.size
          this.queryParams.total = response.data.total
        }
      }).catch(error => {
        // this.tableData = []
        this.queryParams.total = 0
      })
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    // 操作栏下拉菜单按钮
    handleCommand(ev, row) {
      switch (ev) {
        case '1'://查看审核记录
          this.$refs.auditRecords.open(row)
          break;
        case '2'://取消任务//发起人和审核人可以取消任务，外部人员不能取消任务
          this.finishClose(row, 1)
          break;
        case '3'://完成任务
          this.finishClose(row, 0)
          break;
        case '4'://编辑任务
          this.handleEdit(row)
          break;
        case '5'://确认协同结果
          this.handleConfirm(row)
          break;

        default:
          break;
      }
    },
    // 确认协同结果
    handleConfirm(row) {
      let router = this.$router.resolve({
        path: '/tortTeamWork',
        query: {
          taskId: row.id,
          projectId: row.projectId,
          isResult: 3
        }
      })
      window.open(router.href, '_blank')
    },
    // 编辑任务
    handleEdit(row) {
      this.$refs.createTaskDialog.open(row)
    },
    // 取消/完成任务//0完成1取消2缺少资料
    finishClose(row, status) {
      // this.finishCloses([row.id], status)
      this.finishCloses(row.id, status)
    },
    finishCloses(id, status) {
      let params = {
        taskId: id,
        type: status
      }
      var str = ''
      if (status == 0) {
        str = '此操作会将任务置为完成,操作不可逆, 是否继续?'
      } else if (status == 1) {
        str = '此操作会将任务置为取消,操作不可逆, 是否继续?'
      }
      this.$confirm(str, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.updateTaskStatus(params).then(response => {
          if (response.code == 200) {
            if (status == 0) {
              this.$message.success('完成任务成功')
            } else if (status == 1) {
              this.$message.success('取消任务成功')
            }
            this.queryParams.current = 1
            this.getList()
          }
        })
      }).catch(() => {
        this.$message.info('操作已取消')
      });

    },
    //处理任务 
    handleTask(row) {
      // 状态不是处理中或者创建人和处理人不相同是查看{true:查看，false:处理}
      var str = (row.status != 2 || row.handlerName != this.userinfo.name)

      switch (row.type) {//projectType项目类型（1专题库 2报告 3专利挖掘项目）
        case 1://项目开卷审核任务
          this.handleProject(row, str)

          break;
        case 4://侵权分析及FTO协同任务
          this.teamworkTask(row, str ? 2 : 1)
          break;
        case 5://专利挖掘任务审核任务
        case 7://专利挖掘文件审核任务
          this.fileExamine(row)
          break;
        case 6://专利挖掘文件分配任务
          this.$refs.handleTask2Dialog.open(row, !str)
          break;

        default:
          break;
      }
    },
    // 处理项目开卷审核任务
    handleProject(row, str) {
      if (row.projectType == 2) {//报告项目开卷审核
        this.getPatentNoMessage(row, str ? 1 : 2)
      } else {//专利挖掘开卷审核
        this.getPatentMining(row, str ? 1 : 2)
      }
    },
    getPatentNoMessage(row, str) {
      this.$refs.lookReport.open(row,str)
    },
    //协同任务（侵权分析及FTO）
    teamworkTask(row, val) {
      let router = this.$router.resolve({
        path: '/tortTeamWork',
        query: {
          taskId: row.id,
          projectId: row.projectId,
          isResult: val
        }
      })
      window.open(router.href, '_blank')
    },
    //文件及任务审核任务(专利挖掘)
    fileExamine(row) {
      row.disabled = str == '查看' ? true : false
      let router = this.$router.resolve({
        path: '/handleExamine',
        query: {
          row: JSON.stringify(row)
        }
      })
      window.open(router.href, '_blank')
    },
    // 获取挖掘项目
    getPatentMining(row, val) {
      let params = {
        current: 1,
        size: 10,
        searchQuery: `id=${row.projectId}`,//检索条件
      }
      this.$api.queryPatentDigProject(params).then(res => {
        if (res.code == 200) {
          this.$refs.handleTask1Dialog.open(res.data.data[0], row, val)
        }
      })
    },
    // 左侧搜索
    search(val) {
      let params = {}
      val.forEach(item => {
        if (item.type == 3) {
          params[item.value] = item.searchValue.map(itemValue => {
            return itemValue.value
          })
        } else {
          params[item.value] = item.searchValue.label
        }
      })
      // 返回字符串
      this.searchOption = params
      // 调用查询接口
      this.queryParams.current = 1
      this.getList()
    },
    //排序
    sortChange({ column, prop, order }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 1
      this.getList()
    },
    //获取table栏位及分组字段、检索字段
    async getColumn() {
      let params = [this.searchType[this.type]]
      await this.$api.getParamsCommon(params).then(res => {
        if (res.code == 200) {
          let conditionDTOList = JSON.parse(JSON.stringify(res.data[0].conditionDTOList))
          // 搜索字段
          this.searchFiled = this.$commonJS.getField(conditionDTOList, (u) => u.ifSearch == true, {
            label: 'name',
            value: 'value',
            type: 'type',
          })

          var obj = this.searchFiled.find(item => { return item.label == '任务状态' })
          if (obj) {
            obj.options = []
            for (let key in this.taskStatus) {
              obj.options.push({
                label: this.taskStatus[key],
                value: key
              })
            }
          }
          var obj2 = this.searchFiled.find(item => { return item.label == '任务类型' })
          if (obj) {
            obj2.options = []
            for (let key in this.taskType) {
              obj2.options.push({
                label: this.taskType[key],
                value: key
              })
            }
          }
          var obj3 = this.searchFiled.find(item => { return item.label == '所属流程' })
          obj3.options = this.pathOptions

        }
      })

    },

  },
}
</script>

<style lang="scss" scoped></style>