<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <order-search @search="reload" ref="searchRef"> </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> -->
      <!-- 数据表格 -->
      <div class="btn_box">
        <el-button type="success" size="mini" @click="handleAllExpect"
          >自动排程</el-button
        >
        <!-- <el-button type="success" size="mini" @click="autoScheduleRule"
          >排程规则</el-button> -->
      </div>
      <!-- <plan-statistics></plan-statistics> -->

      <ele-pro-table
        ref="table"
        :columns="newColumns"
        :datasource="datasource"
        cache-key="workOrderTable"
        :selection.sync="selection"
        row-key="code"
        @sort-change="onSortChange"
        height="calc(100vh - 380px)"
        autoAmendPage
        :parse-data="parseData"
        @update:selection="handleSelectionChange"
      >
        <template v-slot:code="{ row }">
          {{ row.code }}
        </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"
              type="number"
              size="mini"
              :min="0"
              :max="10"
              @change="priorityChange(row)"
              style="width: 80px"
            ></el-input>
            <el-popover
              placement="right"
              width="200"
              trigger="hover"
              content="数值越大优先级越高（0-3普通, 4-6优先, 7-10紧急）"
            >
              <div class="sort-wrap" slot="reference">
                <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:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-truck"
            @click="toRelease(row)"
            v-if="
              (row.isSplit != 1 &&
                clientEnvironmentId != '4' &&
                row.status == 8) ||
              (clientEnvironmentId == '4' &&
                !row.productName.includes('板材') &&
                row.status == 8)
            "
          >
            派单
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 自动排程对话框 -->
    <el-dialog
      :title="titleExpect"
      :visible.sync="openExpect"
      width="70%"
      :close-on-click-modal="false"
      modal-append-to-body
    >
      <el-table v-loading="loading" :data="salesorderExpectList">
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="生产订单" align="center" prop="plannedOrder" />
        <el-table-column label="班组" align="center" prop="teamId" />
        <el-table-column label="班次名称" align="center" prop="className" />
        <el-table-column
          label="物料数量"
          align="center"
          prop="materialQuotaVOList.length"
        />
        <!-- <el-table-column label="设备数量" align="center" prop="units" /> -->
        <el-table-column label="年" align="center" prop="year" />
        <el-table-column label="月" align="center" prop="month" />
        <el-table-column label="日" align="center" prop="day" />

        <el-table-column
          label="工单开始时间"
          align="center"
          prop="startTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.startTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="工单结束时间"
          align="center"
          prop="endTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.endTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="footer" slot="footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" v-click-once @click="confirm">确定</el-button>
      </div>
    </el-dialog>

    <unpackDialog ref="unpackRef" @success="createSuccess" />
  </div>
</template>

<script>
  import {
    occupyResAll,
    occupyAuto,
    listTimes,
    getBomCategory
  } from '@/api/aps/ws_res_capacity_detail';

  import {
    getList,
    releaseWorkOrder,
    updatePriority
  } from '@/api/workOrder/index.js';
  import {
    teamPage,
    listByFirstTaskId,
    listByWorkCenterId,
    listUserByIds
  } from '@/api/mainData/index.js';
  import OrderSearch from './components/order-search.vue';
  import unpackDialog from './components/unpackDialog.vue';

  import { fieldModel } from '@/api/saleOrder';

  import { debounce } from 'lodash';
  import PlanStatistics from '@/components/statistics/PlanStatistics.vue';
  export default {
    components: {
      PlanStatistics,
      OrderSearch,
      unpackDialog
    },
    data() {
      return {
        // 选中数组
        ids: [],
        // 非单个禁用
        single: false,
        // 非多个禁用
        multiple: false,
        // 销售订单交期预估表格数据
        salesorderExpectList: [],
        selection: [],
        // 弹出层标题

        titleExpect: '交期确定',
        // 是否显示弹出层
        openExpect: false,

        visible: false,
        loading: false,

        form: {
          assignType: 1,
          singleReport: this.clientEnvironmentId == 2 ? 0 : 1
        },
        rules: {
          singleReport: [
            {
              required: true,
              message: '请选择报工类型',
              trigger: ['blur', 'change']
            }
          ],
          workstationIds: [
            {
              required: true,
              message: '请选择工位',
              trigger: ['blur']
            }
          ],
          teamId: [
            {
              required: true,
              message: '请选择班组',
              trigger: ['blur', 'change']
            }
          ]
        },

        teamList: [],

        statusOpt: [
          { label: '待生产', value: 4 },
          { label: '生产中', value: 5 },
          { label: '待下达', value: 8 }
        ],
        statusScheduleOpt: [
          { label: '未开始', value: 0 },
          { label: '未排产', value: 1 },
          { label: '已排产', value: 2 }
        ],

        newColumns: [],

        stationList: [],
        teamsList: [],
        crewList: [],

        current: null
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 表格列配置
      columns() {
        return [
          {
            type: 'selection',
            align: 'center'
          },
          {
            columnKey: 'index',
            slot: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            slot: 'code',
            label: '生产订单号',
            align: 'center',
            minWidth: 210,
            sortable: true
          },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center',
            minWidth: 150
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            minWidth: 170
          },
          {
            prop: 'productCode',
            label: '编码',
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'productName',
            label: '名称',
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center'
          },

          {
            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;
            }
          },
          {
            slot: 'scheduleStatus',
            label: '进度状态',
            align: 'center',
            formatter: (row) => {
              const obj = this.statusScheduleOpt.find(
                (i) => i.value == row.status
              );
              return obj && obj.label;
            }
          },

          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'simpleName',
            label: '客户简称',
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      }
    },
    created() {
      this.getFieldModel();
    },
    methods: {
      handOneSelection(row) {
        const index = this.selection.findIndex((item) => item.id == row.id);
        if (index >= 0) {
          this.selection.splice(index, 1);
        } else {
          this.selection.push(row);
        }
        this.ids = this.selection.map((item) => item.id);
        if (this.selection.length == 0) {
          this.single = false;
          this.multiple = false;
        } else if (this.selection.length == 1) {
          this.single = true;
          this.multiple = false;
        } else if (this.selection.length > 1) {
          this.single = false;
          this.multiple = true;
        }
      },

      selectionFilter(row) {
        return this.selection.findIndex((item) => item.id == row.id) >= 0;
      },
      handleSelectionChange(list) {
        console.log(list);
        if (list.length > 1) {
          // let _list = [];
          // list.forEach((e) => {
          //   if (e.childList.length > 0 && e.splitBatch != 2) {
          //     _list.push(...e.childList);
          //   } else {
          //     _list.push(e);
          //   }
          // });
          this.selection = list;
        } else {
          this.selection = [];
        }
      },
      handleAllExpect() {
        if (this.selection.length == 0) return;
        this.selection.map((item) => {
          item.planStartTime = Date.parse(new Date(item.planStartTime));
          item.planCompleteTime = Date.parse(new Date(item.planCompleteTime));
        });
        occupyAuto(this.selection).then((response) => {
          console.log(response);
          this.salesorderExpectList = response.data.data;
          this.openExpect = true;
          this.single = false;
          this.multiple = false;
        });
        return;
      },
      statusFormatter(status) {
        const obj = this.statusOpt.find((i) => i.value == status);
        return obj && obj.label;
      },
      statusScheduleFormatter(status) {
        const obj = this.statusScheduleOpt.find((i) => i.value == status);
        return obj && obj.label;
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        if (where.status) {
          where.statusList = [];
          where.statusList.push(where.status);
        }
        return getList({
          pageNum: page,
          size: limit,
          ...where,
          ...this.sort
        });
      },

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

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

      getFieldModel() {
        fieldModel({ fieldModel: 't_main_category' }).then((res) => {
          const privateColumn = [
            {
              columnKey: 'action',
              label: '操作',
              width: 120,
              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.newColumns = [...this.columns, ...newRes, ...privateColumn];

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

      // 下达
      toRelease(row) {
        this.current = row;
        this.visible = true;

        this.FirstTaskIdFn();
        this.WorkCenterIdFn();
      },
      // 下达
      confirm() {
        const loading = this.$loading({ text: '加载中...' });
        releaseWorkOrder({
          id: this.current.id,
          ...this.form
        })
          .then((res) => {
            if (res) {
              this.$message.success('成功');
              this.reload();
              this.visible = false;
            }
          })
          .finally(() => {
            loading.close();
          });
      },
      /* 刷新表格 */
      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;
        });
      },

      // 拆分
      toUnpack(row) {
        this.$refs.unpackRef.open(row);
      },

      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>
