<template>
  <div class="ele-body">
    <el-card v-loading="loading" shadow="never">
      <order-search ref="searchRef" @search="reload"></order-search>
      <!--      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="未完成工单" name="first"></el-tab-pane>
        <el-tab-pane label="已完成工单" name="second"></el-tab-pane>
      </el-tabs> -->
      <!-- 数据表格 -->

      <!-- <plan-statistics></plan-statistics> -->

      <!-- <ele-pro-table
        ref="table"
        :columns="newColumns"
        :datasource="datasource"
        cache-key="workOrderTable"
         row-key="code"
        @sort-change="onSortChange"
        height="calc(100vh - 380px)"
        autoAmendPage
        :parse-data="parseData"
      > -->
      <ele-pro-table
        ref="table"
        :cache-key="cacheKeyUrl"
        :columns="columns"
        :datasource="datasource"
        :parse-data="parseData"
        autoAmendPage
        row-key="id"
        @sort-change="onSortChange"
        @columns-change="handleColumnChange"
        @select-all="selectAll"
        default-expand-all
      >
        <!-- :key="activeName" -->
        <!-- :selection.sync="selection" -->
        <!-- @update:selection="handleSelectionChange" -->
        <template v-slot:toolbar>
          <el-button
            class="ele-btn-icon"
            icon="el-icon-truck"
            size="small"
            type="primary"
            v-if="$hasPermission('aps:batchReleaseWorkOrder:release')"
            @click="batchDispatch"
            >批量派单
            <!--  -->
          </el-button>
        </template>
        <template v-slot:selection="{ row }">
          <el-checkbox
            :disabled="!dispatchPermission(row)"
            :value="checkRowData(row)"
            class="batch_checked"
            @change="(e) => selectRow(e, row)"
          ></el-checkbox>
        </template>
        <template v-slot:code="{ row }">
          <el-link
            type="primary"
            :underline="false"
            style="padding-left: 16px"
            @click="openDetails(row)"
          >
            <el-tag type="success" size="mini" v-if="row.originalCode">
              拆</el-tag
            >
            {{ row.code }}
          </el-link>
        </template>
        <template v-slot:formingWeight="{ row }">
          {{ row.formingWeight }} {{ row.newWeightUnit }}
        </template>
        <template v-slot:priority="{ row }">
          <div style="display: flex">
            <el-input
              v-model="row.priority"
              :max="10"
              :min="0"
              size="mini"
              style="width: 80px"
              type="number"
              @change="priorityChange(row)"
            ></el-input>
            <el-popover
              content="数值越大优先级越高（0-3普通, 4-6优先, 7-10紧急）"
              placement="right"
              trigger="hover"
              width="200"
            >
              <div slot="reference" class="sort-wrap">
                <i class="el-icon-caret-top" @click="sortTop(row)"></i>
                <i class="el-icon-caret-bottom" @click="sortBottom(row)"></i>
              </div>
            </el-popover>
          </div>
        </template>

        <template v-slot:status="{ row }">
          <span :class="{ 'ele-text-danger': row.status == 3 }">
            {{ statusFormatter(row.status) }}
          </span>
        </template>
        <!-- 操作列 -->
        <template v-slot:selectionHeader="{ column }">
          <span>123</span>
        </template>
        <template v-slot:action="{ row }">
          <el-link
            v-if="dispatchPermission(row)"
            :underline="false"
            icon="el-icon-truck"
            type="primary"
            @click="toReleaseOpen(row)"
          >
            派单
          </el-link>
          <el-link
            v-if="unpackShow(row) && row.splitResidue !== 0"
            :underline="false"
            type="primary"
            @click="toUnpack(row)"
          >
            拆单
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此子单吗？"
            @confirm="remove(row)"
            v-if="removeShow(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <unpackDialog ref="unpackRef" @success="createSuccess" />
    <releaseDialog
      v-if="dispatchVisible"
      ref="releaseRef"
      :current="dispatchRow"
      :dispatchVisible.sync="dispatchVisible"
      @createSuccess="createSuccess"
    />
    <BatchDialog ref="batchRef" @createSuccess="createSuccess" />
    <Details
      ref="detailsRef"
      v-if="detailsVisible"
      :current="dispatchRow"
      :detailsVisible.sync="detailsVisible"
    />
  </div>
</template>

<script>
  import {
    getList,
    releaseWorkOrder,
    updatePriority,
    unpackDel
  } from '@/api/workOrder/index.js';
  import {
    listByFirstTaskId,
    listByWorkCenterId,
    listUserByIds
  } from '@/api/mainData/index.js';
  import OrderSearch from './components/order-search.vue';
  import unpackDialog from './components/unpackDialog.vue';
  import releaseDialog from './components/releaseDialog.vue';
  import { fieldModel } from '@/api/saleOrder';
  import { debounce } from 'lodash';
  import PlanStatistics from '@/components/statistics/PlanStatistics.vue';
  import tabMixins from '@/mixins/tableColumnsMixin';
  import BatchDialog from '@/views/workOrder/components/batchDialog.vue';
  import Details from './components/details.vue';
  export default {
    mixins: [tabMixins],
    components: {
      PlanStatistics,
      OrderSearch,
      unpackDialog,
      releaseDialog,
      BatchDialog,
      Details
    },
    data() {
      return {
        visible: false,
        loading: false,
        form: {
          assignType: 1,
          crewIds: '',
          workstationIds: '',
          teamId: '',
          singleReport: ''
        },
        rules: {
          singleReport: [
            {
              required: true,
              message: '请选择报工类型',
              trigger: ['blur', 'change']
            }
          ],
          workstationIds: [
            {
              required: true,
              message: '请选择工位',
              trigger: ['blur']
            }
          ],
          teamId: [
            {
              required: true,
              message: '请选择班组',
              trigger: ['blur']
            }
          ]
        },
        teamList: [],
        statusOpt: [
          { label: '待生产', value: 4 },
          { label: '生产中', value: 5 },
          { label: '待下达', value: 8 }
        ],
        columns: [],
        stationList: [],
        teamsList: [],
        crewList: [],
        current: null,
        cacheKeyUrl: '3cbbdff9-aps-workOrder-index',
        columnsVersion: 1,
        dispatchRow: {},
        dispatchVisible: false,
        selectionMap: {},
        detailsVisible: false
      };
    },
    computed: {
      // 派单按钮显示
      dispatchPermission() {
        return (row) => {
          if (!row.firstTaskId) {
            return false;
          }
          return (
            (row.isSplit != 1 &&
              this.clientEnvironmentId != '4' &&
              row.status == 8) ||
            (this.clientEnvironmentId == '4' &&
              !row.productName.includes('板材') &&
              row.status == 8)
          );
        };
      },
      // 删除按钮显示
      removeShow() {
        return (row) => {
          return row.originalCode && !row.mesStatus;
        };
      },
      // 拆单按钮显示
      unpackShow() {
        return (row) => {
          if (row.originalCode) return false;
          return (
            (this.clientEnvironmentId != '4' && row.status == 8) ||
            (this.clientEnvironmentId == '4' &&
              !row.productName.includes('板材') &&
              row.status == 8)
          );
        };
      },
      teamId() {
        return this.$store.state.user.info.teamId;
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },

      checkRowData() {
        return (row) => {
          return row.checkedata ? true : false;
        };
      }
    },
    created() {
      this.setColumns();
      this.getFieldModel();
    },
    methods: {
      setColumns() {
        this.columns = [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            slot: 'selection',
            fixed: 'left',
            headerSlot: 'selectionHeader'
            // selectable: (row, index) => {
            //   if (row.children) {
            //   }
            //   return this.dispatchPermission(row);
            // }
          },
          {
            columnKey: 'index',
            slot: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            slot: 'code',
            label: '生产订单号',
            align: 'center',
            minWidth: 220,
            sortable: true,
            showOverflowTooltip: true
          },
          {
            prop: 'lineNumber',
            label: '行号',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'factoryName',
            label: '所属工厂',
            align: 'center',
            minWidth: 100,
          },
          {
            prop: 'taskName',
            action: 'taskName',
            label: '工序进度',
            align: 'center',
            minWidth: 160
          },
          {
            prop: 'mesStatusName',
            label: '状态',
            align: 'center',
            minWidth: 160
          },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'productType',
            label: 'BOM类型',
            align: 'center',
            width: 120,
            formatter: (row) => {
              if (row.produceType == 1) {
                return 'PBOM';
              }
              if (row.produceType == 2) {
                return 'MBOM';
              }
              if (row.produceType == 3) {
                return 'ABOM';
              }
              // return '';
              // if (row.produceType == 2) {
              //   return '加工(MBOM)';
              // }
              // if (row.produceType == 3) {
              //   return '装配(ABOM)';
              // }
              // return '';
            }
          },
          {
            prop: 'bomCategoryName',
            label: 'BOM版本',
            align: 'center',
            width: 130,
            showOverflowTooltip: true,
            formatter: (row) => {
              if (row.bomCategoryName) {
                return `${row.bomCategoryName} (V${row.bomCategoryVersions}.0)`;
              }
              return '';
            }
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            minWidth: 170,
            showOverflowTooltip: true
          },
          {
            prop: 'modelKey',
            label: '机型',
            align: 'center',
            minWidth: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'colorKey',
            label: '颜色',
            align: 'center',
            minWidth: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'productCode',
            label: '编码',
            align: 'center',
            minWidth: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'productName',
            label: '名称',
            align: 'center',
            minWidth: 170,
            showOverflowTooltip: true
          },
          {
            prop: 'productionCodes',
            label: '生产编号',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'priority',
            label: '优先级',
            align: 'center',
            minWidth: 120,
            slot: 'priority',
            sortable: 'custom'
          },

          {
            prop: 'formingNum',
            label: '要求生产数量',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'formingWeight',
            label: '要求生产重量',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'formingWeight'
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            prop: 'workCenterName',
            label: '工作中心',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'firstTaskName',
            label: '首工序',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            sortable: 'custom'
          },
          // {
          //   slot: 'status',
          //   label: '状态',
          //   align: 'center',
          //   formatter: (row) => {
          //     const obj = this.statusOpt.find((i) => i.value == row.status);
          //     return obj && obj.label;
          //   }
          // },
          {
            prop: 'customerName',
            label: '客户名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'simpleName',
            label: '客户简称',
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      },
      // 进入详情
      openDetails(row) {
        let dispatchRow = { ...row };
        this.dispatchRow = { ...row };
        dispatchRow.initialWeight = row.formingWeight
          ? row.formingWeight + row.newWeightUnit
          : '';
        this.dispatchRow = dispatchRow;
        this.detailsVisible = true;
      },
      // 全选/取消全选
      selectAll(selection) {
        if (selection.length == 0) {
          // 取消全选
          let list = this.$refs.table._data.tableData;
          list.map((el) => {
            this.$set(el, 'checkedata', false);
            if (el.children && el.children.length > 0) {
              el.children.map((item) => {
                this.$set(item, 'checkedata', false);
                delete this.selectionMap[item.id];
              });
            }
            delete this.selectionMap[el.id];
          });
          return;
        }
        // 全选
        let list = [];
        selection.map((item) => {
          let flag = this.dispatchPermission(item);
          this.$set(item, 'checkedata', flag);
          if (flag) {
            list.push(item);
          }
          if (item.children && item.children.length > 0) {
            item.children.map((el) => {
              let flags = this.dispatchPermission(el);
              this.$set(el, 'checkedata', flags);
              if (flags) {
                list.push(el);
              }
            });
          }
          list.map((row) => {
            this.selectionMap[row.id] = {
              id: row.id,
              firstTaskId: row.firstTaskId,
              productName: row.productName,
              productCode: row.productCode,
              code: row.code,
              productionPlanCode: row.productionPlanCode,
              batchNo: row.batchNo,
              formingNum: row.formingNum
            };
          });
        });
      },
      // 单选数据
      selectRow(e, row) {
        this.$set(row, 'checkedata', e);
        if (e) {
          this.selectionMap[row.id] = {
            id: row.id,
            firstTaskId: row.firstTaskId,
            productName: row.productName,
            productCode: row.productCode,
            code: row.code,
            productionPlanCode: row.productionPlanCode,
            batchNo: row.batchNo,
            formingNum: row.formingNum
          };
        } else {
          delete this.selectionMap[row.id];
        }
      },

      // 批量派单
      batchDispatch() {
        let list = Object.values(this.selectionMap);
        if (list.length === 0) {
          this.$message.warning('请至少选择一条派单的数据');
          return;
        }
        if (list.length > 1) {
          for (let i = 1; i < list.length; i++) {
            let el = list[i];
            if (list[0].firstTaskId !== el.firstTaskId) {
              this.$message.warning('请选择首工序相同的数据进行批量派单');
              return;
            }
          }
        }

        this.$refs.batchRef.open(list);
      },

      // 删除拆单数据
      remove(row) {
        unpackDel(row.id).then((res) => {
          if (res) {
            this.$message.success('操作成功');
            this.createSuccess();
          }
        });
      },
      // assignTypeFn(e) {},
      statusFormatter(status) {
        const obj = this.statusOpt.find((i) => i.value == status);
        return obj && obj.label;
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        this.selectionMap = {};
        if (where.status) {
          where.statusList = [];
          where.statusList.push(where.status);
          delete where.status;
        }
        return getList({
          pageNum: page,
          size: limit,
          ...where,
          ...this.sort
        });
      },

      /* 数据转为树形结构 */
      parseData(data) {
        const obj = {
          ...data,
          list: this.$util.toTreeData({
            data: data.list,
            count: data.total,

            idField: 'code',
            parentIdField: 'originalCode'
          })
        };
        return obj;
      },

      getFieldModel() {
        fieldModel({ fieldModel: 't_main_category' }).then((res) => {
          const privateColumn = [
            {
              columnKey: 'action',
              label: '操作',
              width: 140,
              align: 'center',
              resizable: false,
              fixed: 'right',
              slot: 'action'
            }
          ];

          let newRes = res.map((m) => {
            return {
              prop: 'extField.' + m.prop,
              label: m.label,
              align: 'center',
              showOverflowTooltip: true
            };
          });

          this.columns = [...this.columns, ...newRes, ...privateColumn];
          this.getTabColumns();

          // this.$forceUpdate();
        });
      },

      // 下达
      toRelease(row) {
        this.current = row;
        this.visible = true;
        this.FirstTaskIdFn();
        this.WorkCenterIdFn();
        this.form.singleReport = this.clientEnvironmentId == 2 ? 0 : 1;
      },
      // 下达
      confirm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const loading = this.$loading({ text: '加载中...' });

            if (this.form.assignType * 1 == 2) {
              this.form.workstationIds = [];
            } else {
              this.form.crewIds = [];
            }

            releaseWorkOrder({
              id: this.current.id,
              ...this.form
            })
              .then((res) => {
                if (res) {
                  this.$message.success('成功');

                  this.reData();
                  this.reload();
                  this.visible = false;
                }
              })
              .finally(() => {
                loading.close();
              });
          }
        });
      },
      close() {
        this.visible = false;
        this.reData();
      },
      reData() {
        this.form = {
          assignType: 1,
          crewIds: '',
          workstationIds: '',
          teamId: '',
          singleReport: this.clientEnvironmentId == 2 ? 0 : 1
        };
      },

      /* 刷新表格 */
      reload(where) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where });
        });
      },

      onSortChange(e) {
        let sort = {
          orderBy: e.order,
          sortName: e.prop
        };
        this.sort = sort;
        this.reload();
      },

      sortTop(row) {
        row.priority = Number(row.priority) + 1;
        this.priorityChange(row);
      },
      sortBottom(row) {
        if (row.priority <= 1) {
          return;
        }
        row.priority = Number(row.priority) - 1;
        this.priorityChange(row);
      },

      FirstTaskIdFn() {
        listByFirstTaskId(this.current.firstTaskId).then((res) => {
          this.stationList = res;
        });
      },

      WorkCenterIdFn() {
        listByWorkCenterId(this.current.workCenterId).then((res) => {
          this.teamsList = res;

          this.$nextTick(() => {
            if (this.teamId) {
              this.$set(this.form, 'teamId', this.teamId);
              this.stationChange();
            }

            // this.$refs.form.clearValidate();
          });
        });
      },

      // 拆分
      toUnpack(row) {
        this.$refs.unpackRef.open(row);
      },
      //派单
      toReleaseOpen(row) {
        this.dispatchRow = { ...row };
        this.dispatchRow.initialWeight = row.formingWeight
          ? row.formingWeight + row.newWeightUnit
          : '';
        this.dispatchVisible = true;
        // getTaskIdByInstanceId(row.firstTaskId)
        //   .then((res) => {
        //     if (res) {
        // }
        // })
        // .catch((err) => {
        //   this.$message.error(err.message);
        // });
      },

      createSuccess() {
        this.reload();
      },

      stationChange() {
        this.crewList = [];
        this.crewIds = [];

        listUserByIds([this.form.teamId]).then((res) => {
          this.crewList = res;
        });
      },

      priorityChange(row) {
        if (row.priority > 10) {
          row.priority = 10; // 如果大于 10，则设置为 10
        } else if (row.priority < 0) {
          row.priority = 0; // 如果小于 0，则设置为 0
        }

        this.priorityFn(row);
      },

      priorityFn: debounce(function (row) {
        let params = {
          id: row.id,
          priority: row.priority
        };
        updatePriority(params).then((res) => {});
      }, 800)
    }
  };
</script>

<style lang="scss" scoped>
  // ::v-deep .el-table__row {
  //   height: 51px !important;
  // }
</style>
