<template>
  <div class="ele-body">
    <el-card v-loading="loading" shadow="never">
      <task-search @search="reload"></task-search>
      <!-- <taskDialog-search></taskDialog-search> -->
      <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="我的任务" name="1"></el-tab-pane>
        <el-tab-pane
          label="全部任务"
          name="2"
          v-if="$hasPermission('mes:taskreport:allorder')"
        ></el-tab-pane>
        <el-tab-pane
          label="班组任务"
          name="3"
          v-if="$hasPermission('mes:taskreport:teamorder')"
        ></el-tab-pane>

        <el-tab-pane
          label="NC编程任务"
          name="4"
          v-if="$hasPermission('mes:taskreport:programmingorder')"
        ></el-tab-pane>

        <!-- <el-tab-pane label="我的任务" name="1"></el-tab-pane>
        <el-tab-pane label="全部任务" name="2"></el-tab-pane> -->
      </el-tabs>
      <ele-pro-table
        ref="table"
        :columns="tabValue == '4' ? ncColumns : columns"
        :datasource="datasource"
        :pageSize="20"
        cache-key="workOrderTable"
        class="my_pro_table"
        row-key="id"
        :height="tableHeight"
        @fullscreen-change="fullscreenChange"
      >
        <template v-slot:assigneeCode="{ row }">
          <el-link
            :underline="false"
            type="primary"
            @click="details('assign', row)"
            >{{ row.assigneeCode }}
          </el-link>
        </template>
        <template v-slot:workOrderCode="{ row }">
          <el-link
            :underline="false"
            type="primary"
            @click="details('assign', row)"
            >{{ row.workOrderCode }}
          </el-link>
        </template>
        <template v-slot:disposalStatus="{ row }">
          <el-tag v-if="row.disposalStatus == 1" type="success">已接收</el-tag>
          <el-tag v-if="row.disposalStatus == 2" type="danger">已拒绝</el-tag>
        </template>

        <template v-slot:action="{ row }">
          <el-link
            v-if="tabValue == '2' && row.disposalStatus == '2'"
            :underline="false"
            type="primary"
            @click="reassignTask(row)"
            >转派
          </el-link>
          <el-link
            :underline="false"
            type="primary"
            @click="details('report', row)"
            v-if="row.disposalStatus == '1' || tabValue == '2'"
            >报工
          </el-link>
          <el-link
            :underline="false"
            type="primary"
            @click="viewRecords(row.id)"
            v-if="row.disposalStatus == '1' || tabValue == '2'"
            >报工记录
          </el-link>

          <el-popconfirm
            icon="el-icon-info"
            title="确定接收任务吗？"
            @confirm="receiveTask(row.id, '1')"
            v-if="
              row.disposalStatus != '1' &&
              row.disposalStatus != '2' &&
              tabValue != '2'
            "
          >
            <el-button slot="reference" type="text">接收</el-button>
          </el-popconfirm>

          <el-popconfirm
            icon="el-icon-info"
            title="确定拒绝任务吗？"
            @confirm="receiveTask(row.id, '2')"
            v-if="
              row.disposalStatus != '1' &&
              row.disposalStatus != '2' &&
              tabValue != '2'
            "
          >
            <el-button slot="reference" type="text">拒绝</el-button>
          </el-popconfirm>

          <!-- <el-link
          :underline="false"
          type="primary"
          @click="receiveTask(row)"
          v-if="row.disposalStatus != '1'"
          >接收任务
        </el-link> -->

          <!-- <el-link
          :underline="false"
          type="primary"
          @click="rejectTask(row)"
          v-if="row.disposalStatus != '1'"
          >拒绝任务
        </el-link> -->
        </template>
      </ele-pro-table>
    </el-card>
    <modifyDialog ref="modifyRef" />
    <Ddtails ref="detailsRef" @success="reload" />

    <el-dialog
      title="选择人员"
      :visible.sync="dialogFormVisible"
      v-if="dialogFormVisible"
      width="30%"
      center
    >
      <el-form :model="form">
        <el-form-item label="人员">
          <el-select
            size="mini"
            class="content_num"
            filterable
            v-model="form.userId"
            placeholder="请选择任务人员"
          >
            <el-option
              v-for="item in teamList"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="chooseUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import TaskSearch from './components/task-search.vue';
  import Ddtails from './components/Ddtails.vue';
  import modifyDialog from '@/views/taskList/components/modifyDialog.vue';
  import { getteampage } from '@/api/produceWord/index.js';
  import {
    pageByCurrentUser,
    pageByCurrentUserLeader,
    listUpdateRealTimeRecord,
    taskManagement,
    transferTasks,
    pageByCurrentCurrentUserTeam,
    getNCtaskListData
  } from '@/api/workOrderList';
  import { revokeWork } from '@/api/manufacture/spreadWorkOrder';

  export default {
    components: { TaskSearch, Ddtails, modifyDialog },
    data() {
      return {
        loading: false,
        tabValue: '1',
        statusOpt: [
          { label: '待生产', value: 4 },
          { label: '生产中', value: 5 },
          { label: '待下达', value: 8 }
        ],
        form: {
          userId: '',
          id: ''
        },
        dialogFormVisible: false,
        teamList: [],
        tableHeight: 'calc(100vh - 380px)'
      };
    },
    computed: {
      // 表格列配置
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            slot: 'assigneeCode',
            prop: 'assigneeCode',
            label: '任务编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 210
          },
          {
            slot: 'workOrderCode',
            prop: 'workOrderCode',
            label: '生产订单号',
            align: 'center',
            showOverflowTooltip: true,
            width: 210
          },
          {
            prop: 'mesWorkOrderCode',
            label: '生产工单号',
            align: 'center',
            showOverflowTooltip: true,
            width: 210
          },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'assigneeType',
            label: '执行类型',
            align: 'center',
            showOverflowTooltip: true,
            width: 120,
            formatter: (row) => {
              if (!row.assigneeType) return '';
              return row.assigneeType.desc;
            }
          },
          {
            prop: 'assigneeName',
            label: '执行对象名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'workCenterName',
            label: '工作中心',
            align: 'center',
            width: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'assignTeamName',
            label: '班组名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'taskName',
            label: '工序名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 150
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'productCode',
            label: '产品编码',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'productName',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 200
          },
          {
            prop: 'productionCodes',
            label: '生产编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            width: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            width: 200,
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            label: '任务数量',
            align: 'center',
            showOverflowTooltip: true,
            width: 110
          },
          {
            prop: 'weight',
            label: '任务重量(kg)',
            align: 'center',
            showOverflowTooltip: true,
            width: 110
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'startTime',
            label: '任务开始时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'endTime',
            label: '任务结束时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            label: '实际开始时间',
            prop: 'realStartTime',
            minWidth: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '实际结束时间',
            prop: 'realEndTime',
            minWidth: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '工时',
            prop: 'durationText',
            width: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'firstTaskName',
            label: '首工序',
            align: 'center',
            width: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'statusText',
            label: '状态',
            align: 'center',
            // formatter: (row) => {
            //   const obj = this.statusOpt.find((i) => i.value == row.status);
            //   return obj && obj.label;
            // },
            width: 120
          },
          {
            prop: 'disposalStatus',
            label: '任务接收状态',
            align: 'center',
            slot: 'disposalStatus',
            width: 120
          },
          {
            prop: 'customerName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'simpleName',
            label: '客户简称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action'
          }
        ];
      },

      ncColumns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            slot: 'code',
            prop: 'code',
            label: '任务编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 210
          },

          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'executeGroupName',
            label: '执行部门',
            align: 'center',
            showOverflowTooltip: true,
            width: 120
          },
          {
            prop: 'executorName',
            label: '执行人',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'taskName',
            label: '工序名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 150
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'categoryCode',
            label: '产品编码',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'categoryName',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 200
          },
          {
            prop: 'productionCodes',
            label: '生产编号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true,
            width: 170
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            width: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            width: 200,
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            width: 200,
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            label: '任务数量',
            align: 'center',
            showOverflowTooltip: true,
            width: 110
          },
          {
            prop: 'weight',
            label: '任务重量(kg)',
            align: 'center',
            showOverflowTooltip: true,
            width: 110
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'startTime',
            label: '任务开始时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'endTime',
            label: '任务结束时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            label: '实际开始时间',
            prop: 'realStartTime',
            minWidth: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '实际结束时间',
            prop: 'realEndTime',
            minWidth: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '工时',
            prop: 'durationText',
            width: 150,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'firstTaskName',
            label: '首工序',
            align: 'center',
            width: 180,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'statusText',
            label: '状态',
            align: 'center',
            // formatter: (row) => {
            //   const obj = this.statusOpt.find((i) => i.value == row.status);
            //   return obj && obj.label;
            // },
            width: 120
          },
          {
            prop: 'disposalStatus',
            label: '任务接收状态',
            align: 'center',
            slot: 'disposalStatus',
            width: 120
          },
          {
            prop: 'customerName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },

          {
            prop: 'simpleName',
            label: '客户简称',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            width: 180
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action'
          }
        ];
      }
    },
    created() {},
    mounted() {
      // if (this.$hasPermission('mes:taskreport:allorder')) {
      //   this.tabValue = '2';
      // }
      // if (this.$hasPermission('mes:taskreport:myorder')) {
      //   this.tabValue = '1';
      // }
      // if (
      //   !this.$hasPermission('mes:taskreport:myorder') &&
      //   !this.$hasPermission('mes:taskreport:allorder')
      // ) {
      //   this.tabValue = '';
      // }
    },
    methods: {
      handleTabClick(e) {
        this.tabValue = e.name;
        this.reload();
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        if (this.tabValue && this.tabValue != 0) {
          let api =
            this.tabValue === '1'
              ? pageByCurrentUser
              : this.tabValue == '2'
              ? pageByCurrentUserLeader
              : this.tabValue == '3'
              ? pageByCurrentCurrentUserTeam
              : getNCtaskListData;

          let params = {
            ...where,
            pageNum: page,
            size: limit
          };

          if (this.tabValue === '3') {
            params.teamIdsStr = this.$store.state.user.info?.teamId;
            // if (teamId) {
            //   const ids = teamId
            //     .split(',')
            //     .map((i) => i.trim())
            //     .filter(Boolean);
            //   params.teamIds = ids; // 不要加 []
            // }
          }

          console.log(params);

          return api(params);
        } else {
          return [];
        }

        // if (
        //   (this.$hasPermission('mes:taskreport:myorder') &&
        //     this.$hasPermission('mes:taskreport:allorder')) ||
        //   (this.$hasPermission('mes:taskreport:myorder') &&
        //     !this.$hasPermission('mes:taskreport:allorder'))
        // ) {
        //   let api = pageByCurrentUser;
        //   return api({
        //     ...where,
        //     pageNum: page,
        //     size: limit
        //   });
        // } else if (
        //   this.$hasPermission('mes:taskreport:myorder') &&
        //   !this.$hasPermission('mes:taskreport:allorder')
        // ) {
        //   let api = pageByCurrentUserLeader;
        //   return api({
        //     ...where,
        //     pageNum: page,
        //     size: limit
        //   });
        // } else {
        //   return [];
        // }

        // if()
      },

      async chooseUser() {
        if (!this.form.userId) {
          return this.$message.warning('请选择转派人员');
        }

        const data = this.teamList.find((it) => it.id == this.form.userId);

        await transferTasks({
          assigneeId: data.id,
          assigneeName: data.name,
          id: this.form.id
        }).then((res) => {
          console.log(res);
        });

        this.dialogFormVisible = false;

        this.reload();
      },

      async receiveTask(id, type) {
        await taskManagement({
          id,
          disposalStatus: Number(type)
        }).then((res) => {
          console.log(res);
          this.reload();
        });
      },

      // async receiveTask(item) {
      //   await taskManagement({
      //     id: item.id,
      //     disposalStatus: 1
      //   }).then((res) => {
      //     console.log(res);
      //     this.reload();
      //   });
      // },

      // async rejectTask(item) {
      //   await taskManagement({
      //     id: item.id,
      //     disposalStatus: 2
      //   }).then((res) => {
      //     console.log(res);
      //     this.reload();
      //   });
      // },

      async reassignTask(item) {
        this.form.userId = '';
        this.form.id = item.id;
        await getteampage({ name: item.assignTeamName }).then((res) => {
          this.teamList = res.list[0].userVOList;
        });

        this.dialogFormVisible = true;
      },

      fullscreenChange(fullscreen) {
        if (fullscreen) {
          this.tableHeight = 'calc(100vh - 120px)';
        } else {
          this.tableHeight = 'calc(100vh - 380px)';
        }
      },

      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },
      details(type, row) {
        let currentRow = {
          assignCode: row.assignCode,
          mesWorkOrderCode: row.mesWorkOrderCode,
          workOrderCode: row.workOrderCode,
          productionPlanCode: row.productionPlanCode,
          produceRoutingName: row.produceRoutingName,
          formingNum: row.formingNum,
          assignTeamName: row.assignTeamName,
          formingWeight: row.formingWeight,
          planStartTime: row.planStartTime,
          planCompleteTime: row.planCompleteTime,
          startTime: row.startTime,
          firstTaskId: row.firstTaskId,
          endTime: row.endTime,
          taskName: row.taskName,
          firstTaskName: row.firstTaskName,
          assigneeType: row.assigneeType ? row.assigneeType.desc : '',
          assigneeName: row.assigneeName,
          weight: row.weight,
          quantity: row.quantity,
          durationText: row.durationText,
          apsAssigneeId: row.id,
          batchNo: row.batchNo,
          productCode: row.productCode,
          productName: row.productName,
          specification: row.specification,
          newWeightUnit: row.newWeightUnit,
          measuringUnit: row.measuringUnit
        };
        let form = {
          realEndTime: row.realEndTime,
          realStartTime: row.realStartTime,
          unqualifiedWeight: row.unqualifiedWeight,
          unqualifiedQuantity: row.unqualifiedQuantity,
          qualifiedWeight: row.qualifiedWeight,
          remark: row.assigneeRemark,
          qualifiedQuantity: row.qualifiedQuantity,
          reportQuantity: row.reportQuantity,
          lossQuantity: row.lossQuantity
        };
        this.$refs.detailsRef.open(type, currentRow, form);
      },
      viewRecords(apsAssigneeId) {
        listUpdateRealTimeRecord(apsAssigneeId)
          .then((res) => {
            if (res && res.length > 0) {
              this.$refs.modifyRef.open(res);
            } else {
              this.$message.warning('暂无修改历史记录数据');
            }
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .ele-body {
    height: 100%;

    // .my_pro_table {
    //   height: calc(100% - 136px);
    // }
  }

  // ::v-deep .el-table {
  //   height: calc(100% - 96px);
  // }
</style>
