<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <productionPlan-search
        @search="reload"
        ref="searchRef"
        :statusOpt="statusOpt"
        :planType="planType"
        :activeName="activeName"
      >
      </productionPlan-search>

      <div class="btn_box">
        <el-button type="success" size="mini" @click="homogeneityInspect"
          >齐套性检查</el-button
        >
        <el-button type="success" size="mini" v-if="single" @click="handleExpect"
          >单个自动排程</el-button>
        <el-button type="success" size="mini" v-if="multiple"  @click="handleAllExpect"
          >全部自动排程</el-button>
        <!-- <el-button type="success" size="mini" @click="autoScheduleRule"
          >排程规则</el-button> -->
      </div>

      <el-tabs v-model="activeName" type="card" size="mini">
        <el-tab-pane label="未发布" name="first"></el-tab-pane>
        <!-- <el-tab-pane label="已发布" name="second"></el-tab-pane>
        <el-tab-pane label="已变更" name="change"></el-tab-pane> -->
      </el-tabs>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :key="activeName"
        :initLoad="false"
        :columns="newColumns"
        :datasource="datasource"
        row-key="code"
        :selection.sync="selection"
        :cache-key="`${activeName}ProductionPlanTable`"
        @sort-change="onSortChange"
        autoAmendPage
        :parse-data="parseData"
        @update:selection="handleSelectionChange"
      >
        <template v-slot:batchNo="{ row }">
          <el-link type="primary" :underline="false">
            <!-- @click.stop="splitDetails(1, row)" -->
            <el-tag type="success" size="mini" v-if="row.joinPlanCode">
              拆</el-tag
            >

            <el-tag
              type="danger"
              size="mini"
              v-if="row.splitBatch == 2"
              @click.stop="splitDetails(2, row)"
            >
              合</el-tag
            >
            {{ row.batchNo }}
          </el-link>
        </template>

        <template v-slot:selection="{ row }">
          <div class="check_box" @click="handOneSelection(row)">
            <div class="check act_check" v-if="selectionFilter(row)">
              <i class="el-icon-check"></i>
            </div>
            <div class="check" v-else></div>
          </div>
        </template>

        <template v-slot:code="{ row }">
          <el-link type="primary" :underline="false" @click="goDetail(row)">
            {{ row.code }}
          </el-link>
        </template>

        <template v-slot:salesCode="{ row }">
          {{ row.salesCode }}
        </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:productNum="{ row }">
          {{ row.productNum }} {{ row.unit }}
        </template>

        <template v-slot:productWeight="{ row }">
          {{ row.productWeight }} {{ row.weightUnit }}
        </template>

        <template v-slot:requiredFormingNum="{ row }">
          {{ row.requiredFormingNum }} {{ row.unit }}
        </template>

        <template v-slot:newSumOrderWeight="{ row }">
          {{ row.newSumOrderWeight }} {{ row.newWeightUnit }}
        </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"
            v-if="row.status == 2 && row.splitBatch != 1"
            @click="handleOrderPublish(1, row)"
          >
            发布
          </el-link>
          <el-link
            type="primary"
            v-if="row.status == 3"
            :underline="false"
            @click="handleOrderPublish(2, row)"
          >
            重新发布
          </el-link>


        </template>
      </ele-pro-table>
      <!-- 自动排程对话框 -->
      <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="produceRoutingId" />
          <template slot-scope="scope">{{getRouteItemById(scope.row.produceRoutingId)}}</template>
          </el-table-column> -->
          <el-table-column label="产线" align="center" prop="factoryLineId" >
            <template slot-scope="scope">{{getItemById(scope.row.productLineId)}}</template>
          </el-table-column>
          <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="deliverDay" />
          <el-table-column label="规划产能" align="center" prop="plannedCapacity" />
          <el-table-column label="已排产产能" align="center" prop="plannedSumCapacity" />
          <el-table-column label="未排产产能" align="center" prop="unplannedSumCapacity" />
          <el-table-column label="本次排产产能" align="center" prop="currentPlannedSumCapacity" />
          <el-table-column label="已排产单号列表" align="center" prop="plannedOrder" />
          <el-table-column label="已排产产能列表" align="center" prop="plannedOrderCapacity" />
        </el-table>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="!single" @click="submitFormExpect">确定交期</el-button>
            <el-button type="primary" :disabled="!multiple" @click="submitFormAllExpect">确定所有交期</el-button>
            <el-button @click="cancelExpect">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>

    <unpackDialog ref="unpackRef" @success="reload" />

    <mergeDialog ref="mergeRef" @success="reload"></mergeDialog>

    <unpackDetails ref="DetailsRef"></unpackDetails>

    <homogeneityInspectDialog
      ref="homogeneityInspectDialog"
      @success="reload"
    />
    <homogeneityInspectInstallDialog
      ref="homogeneityInspectInstallDialog"
      @success="reload"
    />

    <disassemblePlanPop
      ref="disassemblePlanRef"
      @close="reload"
    ></disassemblePlanPop>

    <factoryAdd
      v-if="factoryShow"
      :factoryType="factoryType"
      :factoryObj="factoryObj"
      @close="factoryClose"
    ></factoryAdd>
  </div>
</template>

<script>
  import { listProduct_line, getProduct_line, delProduct_line, addProduct_line, updateProduct_line } from "@/api/aps/product_line";
  import {expect,expectAll,queryOccupyRes, occupyRes,occupyAllRes, listProduct_line_capacity_detail,listDetail, getProduct_line_capacity_detail, delProduct_line_capacity_detail, addProduct_line_capacity_detail, updateProduct_line_capacity_detail } from "@/api/aps/product_line_capacity_detail";

  import {
    bomRoutingList,
    bomListByPlan,
    saveSaleToPlan,
    temporarilyUpdate
  } from '@/api/saleOrder';
  import {
    getById,
    getList,
    del,
    updatePriority,
    getPlanStatistics
  } from '@/api/productionPlan/index.js';
  import productionPlanSearch from './components/productionPlan-search.vue';
  import unpackDialog from './components/unpackDialog.vue';
  import mergeDialog from './components/mergeDialog.vue';
  import homogeneityInspectDialog from './components/homogeneityInspectDialog.vue';
  import homogeneityInspectInstallDialog from './components/homogeneityInspectInstallDialog.vue';
  import unpackDetails from './components/unpackDetails.vue';
  import disassemblePlanPop from './components/disassemblePlanPop.vue';
  import factoryAdd from './components/factoryAdd/index.vue';
  import { release } from '@/api/productionPlan/order.js';
  import { getCode } from '@/api/codeManagement';
  import { fieldModel } from '@/api/saleOrder';
  import { debounce } from 'lodash';
  export default {
    components: {
      productionPlanSearch,
      unpackDialog,
      mergeDialog,
      unpackDetails,
      disassemblePlanPop,
      factoryAdd,
      homogeneityInspectDialog,
      homogeneityInspectInstallDialog
    },
    props: {
      timeDimensionPlanType: { type: Number, default: 1 }
    },
    data() {
      return {
        // 选中数组
        ids: [],
        // 非单个禁用
        single: false,
        // 非多个禁用
        multiple: false,
        // 销售订单交期预估表格数据
        salesorderExpectList:[],
        // 弹出层标题
        titleExpect: "交期确定",
        // 是否显示弹出层
        openExpect: false,
        //日期选择框
        checkImg: require('@/assets/checked.png'),
        capacityList: [

        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          thisCapacity:[
            { required: true, message: "本次产能不能为空", trigger: "blur" }
          ],
          produceRoutingId: [
            { required: true, message: "工艺路线不能为空", trigger: "blur" }
          ],
          productLineId:[
            { required: true, message: "产线不能为空", trigger: "blur" }
          ],
          year: [
            { required: true, message: "年份不能为空", trigger: "blur" }
          ],
          month: [
            { required: true, message: "月份不能为空", trigger: "blur" }
          ],
          day: [
            { required: true, message: "日期不能为空", trigger: "blur" }
          ],
        },
        //产线数组
        product_line_select:[],
        routingList: [],
        year_select:[
          {"value":2025},{"value":2026},{"value":2027},{"value":2028}
          ],
        month_select:[
          {"value":1},{"value":2},{"value":3},{"value":4},
          {"value":5},{"value":6},{"value":7},{"value":8},
          {"value":9},{"value":10},{"value":11},{"value":12},
          ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        planStatistics: {
          waitPlanNum: 0,
          planNum: 0,
          issueNum: 0,
          waitFinishNum: 0,
          finishNum: 0,
          stockNum: 0
        },
        activeName: 'first',

        // 加载状态
        loading: false,
        pageType: 'add',
        dialogTitle: '',
        isBindPlan: false,
        statusOpt: {
          first: [
            { label: '所有状态', value: '3,2' },
            { label: '待发布', value: '2' },
            { label: '发布失败', value: '3' },
            { label: '已发布', value: '4' }
          ],
          second: [
            { label: '所有状态', value: '7,4,5,6' },
            { label: '待生产', value: '4' },
            { label: '生产中', value: '5' },
            { label: '已完成', value: '6' },
            { label: '已延期', value: '7' }
          ],
          change: [{ label: '已变更', value: '9' }]
        },
        planType: [
          { label: '所有计划类型', value: null },
          { label: '内销计划', value: '1' },
          { label: '外销计划', value: '2' },
          { label: '预制计划', value: '3' }
        ],
        newColumns: [],

        selection: [],

        factoryShow: false,
        factoryType: 3,
        factoryObj: {},
        cardSpan: 3
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 表格列配置
      columns() {
        const opt = {
          first: [],
          second: [
            {
              prop: 'releaseTime',
              label: '工单发布日期',
              align: 'center',

              minWidth: 110
            },
            {
              prop: 'planFormingTime',
              label: '预测生产日期',
              align: 'center',

              minWidth: 110
            },
            {
              prop: 'deliveryTime',
              label: '预测交货日期',
              align: 'center',

              minWidth: 110
            },
            {
              prop: 'formingTime',
              label: '实际交货日期',
              align: 'center',

              minWidth: 110
            }
          ],
          change: []
        };

        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            slot: 'selection'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },

          {
            slot: 'batchNo',
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 140,
            sortable: true
          },

          {
            slot: 'code',
            prop: 'code',
            action: 'code',
            label: '计划编号',
            align: 'center',

            minWidth: 160,
            sortable: true
          },

          {
            prop: 'salesCode',
            action: 'salesCode',
            label: '销售订单号',
            align: 'center',
            minWidth: 160
          },

          {
            prop: 'productCode',
            label: '编码',
            align: 'center',

            minWidth: 140
          },
          {
            prop: 'productName',
            label: '名称',
            align: 'center',

            minWidth: 140
          },

          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 150,

            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },

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

          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center',
            width: 140,
            showOverflowTooltip: true
          },

          {
            prop: 'productNum',
            label: '计划数量',
            align: 'center',

            slot: 'productNum'
          },
          {
            prop: 'productWeight',
            label: '计划重量',
            align: 'center',

            slot: 'productWeight'
          },
          {
            prop: 'requiredFormingNum',
            label: '要求生产数量',
            align: 'center',

            slot: 'requiredFormingNum'
          },

          {
            prop: 'newSumOrderWeight',
            label: '要求生产重量',
            align: 'center',

            slot: 'newSumOrderWeight'
          },

          {
            prop: 'scheduleStatusName',
            label: '进度状态',
            align: 'center',
            minWidth: 100
          },

          {
            prop: '',
            label: '已排产数量',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: '',
            label: '未排产数量',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: '',
            label: '已生产数量',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: '',
            label: '未生产数量',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'factoryName',
            label: '所属工厂',
            align: 'center'
          },

          {
            prop: '',
            label: '合格品数',
            align: 'center'
          },

          {
            prop: '',
            label: '不合格品数',
            align: 'center'
          },

          {
            prop: '',
            label: '合格率',
            align: 'center'
          },

          {
            prop: 'moCount',
            label: '模数',
            align: 'center',
            show: this.clientEnvironmentId == '4'
          },

          {
            prop: 'blockCount',
            label: '块数',
            align: 'center',
            show: this.clientEnvironmentId == '4'
          },
          {
            prop: 'noWordCount',
            label: '未排程块数',
            align: 'center',

            show: this.clientEnvironmentId == '4',
            minWidth: 110
          },
          {
            prop: 'planDeliveryTime',
            label: '计划交付日期',
            align: 'center',
            width: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'reqMoldTime',
            label: '订单要求计划交付日期',
            align: 'center',
            width: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'startTime',
            label: '计划开始日期',
            align: 'center',
            width: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'endTime',
            label: '计划结束日期',
            align: 'center',
            width: 110,
            showOverflowTooltip: true
          },

          {
            prop: 'orderType',
            label: '计划类型',
            align: 'center',

            formatter: (row) => {
              const obj = this.planType.find((i) => i.value == row.planType);
              return obj && obj.label;
            }
          },
          {
            prop: 'version',
            label: '版本',
            align: 'center',

            minWidth: 80
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            width: 110,
            showOverflowTooltip: true
          },
          {
            columnKey: 'status',
            slot: 'status',
            label: '状态',
            align: 'center',
            formatter: (row) => {
              const obj = this.statusOpt[this.activeName].find(
                (i) => i.value == row.status
              );
              return obj && obj.label;
            }
          }
        ];
      }
    },
    created() {
      this.getFieldModel();
      this.getProductLine();
    },
    mounted() {
      this.getPlanStatistics();
    },
    methods: {
      /*单个计划交期预估*/
      handleExpect(){

        // console.log(this.ids);

        const id = this.ids;

        getById(id).then(response => {
          let saleorder = response;
          // this.form = response.data;
          console.log(response);
          //如果是已经占用资源，则显示已经占用的资源,不能重复
          if (saleorder.scheduleStatus==20){

            queryOccupyRes(saleorder.code).then(response => {
                console.log(response);
                this.salesorderExpectList = response.data;
                this.openExpect = true;
                this.single = false;
                this.multiple = false;
              });
            return;
          }
          else if (saleorder.scheduleStatus==null||saleorder.scheduleStatus==""){

            expect(saleorder.id).then(response => {
              console.log(response);
              this.salesorderExpectList = response.data;
              this.openExpect = true;
              this.single = true;
              this.multiple = false;
            });
          }
        });

       },
      //多个计划交期预览
      handleAllExpect(){

            expectAll().then(response => {
              // console.log(response);
              this.salesorderExpectList = response.data;
              this.openExpect = true;
              this.single = false;
              this.multiple = true;
            });
      },
      autoScheduleRule(){

      },
      /** 提交交期确定按钮 */
       submitFormExpect() {
        const id = this.ids
        getById(id).then(response => {
          console.log(response);
          let saleorder = response;
          if (saleorder.scheduleStatus==2) {
            this.$message.success("已经分配过资源");
            return;
          }
          var i=0;
          this.salesorderExpectList.forEach(item=>{
            i++;
            item.plannedOrder = saleorder.code;
            item.plannedOrderCapacity = item.currentPlannedSumCapacity;
            item.plannedSumCapacity  = item.currentPlannedSumCapacity;
          });

          var lastNode = this.salesorderExpectList[this.salesorderExpectList.length-1];
            // console.log(lastNode);
            var productDay = lastNode.deliverDay;
            saleorder.productionDeliveryDate = productDay;
            // console.log(saleorder.productionDeliveryDate);

            var arr = [];
            this.salesorderExpectList.forEach(item=>{
              var node = {};
              node.id = item.id;
              node.productLineId = item.productLineId;
              node.createTime = item.createTime;
              node.createUserId = item.createUserId;
              node.year = item.year;
              node.month = item.month;
              node.day = item.day;
              node.plannedCapacity = item.plannedCapacity;
              node.unplannedSumCapacity = item.unplannedSumCapacity;
              node.deliverDay = item.deliverDay;
              node.currentPlannedSumCapacity = item.currentPlannedSumCapacity;
              node.plannedSumCapacity = item.plannedSumCapacity;
              node.plannedOrder = item.plannedOrder;
              node.plannedOrderCapacity = item.plannedOrderCapacity;
              node.plannedOrderDate = item.plannedOrderDate;
              arr.push(node);
            });
            console.log(arr[0]);
            occupyRes(arr[0]).then(response => {
              console.log(response);
              if (response.data.code != "-1"){
                this.$message.success("占用成功");
                this.openExpect = false;
                this.getFieldModel();
              } else {
                this.$message.warning("占用出错"+response.data.message);
              }

            // saleorder.status = 2;
            // console.log(saleorder);
            // updateSalesorder(saleorder).then(response => {
            //   this.$message.success("修改成功");
            //   this.openExpect = false;
            //   this.getList();
            // });
          });


        });
      },
    // 取消按钮
        cancelExpect() {
          this.openExpect = false;

        },
      submitFormAllExpect(){
        var arr = [];
        this.salesorderExpectList.forEach(item=>{
          var node = {};
          node.id = item.id;
          node.createTime = item.createTime;
          node.createUserId = item.createUserId;
          node.year = item.year;
          node.month = item.month;
          node.day = item.day;
          node.productLineId = item.productLineId;
          node.plannedCapacity = item.plannedCapacity;
          node.unplannedSumCapacity = item.unplannedSumCapacity;
          node.deliverDay = item.deliverDay;
          node.currentPlannedSumCapacity = item.currentPlannedSumCapacity;
          node.plannedSumCapacity = item.plannedSumCapacity;
          node.plannedOrder = item.plannedOrder;
          node.plannedOrderCapacity = item.plannedOrderCapacity;
          node.plannedOrderDate = item.plannedOrderDate;
          arr.push(node);
        });

        occupyAllRes(arr).then(response => {
          console.log(response);
          if (response.data.code != "-1"){
            this.$message.success("占用成功");
            this.openExpect = false;
            this.getFieldModel();
          } else {
            this.$message.warning("占用出错"+response.data.message);
          }
        });
      },
      getRouteItemById(id) {
           var node = this.routingList.find(item => item.id === id);
           if (node == null||node == undefined) return '';else
            return node.name;
          },

      getItemById(id) {
           var node = this.product_line_select.find(item => item.factoryLineId === id);
           if (node == null||node == undefined) return '';else
            return node.factoryLineName;
          },
      checkedChange(index){
        if (!this.capacityList[index].checked) return;
        this.form.day = this.capacityList[index].day;
         this.form.id = this.capacityList[index].id;
      },
      /** 查询产线月产能详情定义列表 */
      getCapacityList() {
        this.form.day = "";
        if (this.form.produceRoutingId == ""||this.form.produceRoutingId==null) {
          this.$message.warning('需要选择工艺路线！');
          return;
        }
        if (this.form.productLineId == ""||this.form.productLineId==null) {
          this.$message.warning('需要选择产线！');
          return;
        }

        if (this.form.year == ""||this.form.year==null) {
          this.$message.warning('需要选择年份！');
          return;
        }
        if (this.form.month == ""||this.form.month==null) {
          this.$message.warning('需要选择月份！');
          return;
        }
        this.loading = true;
        listProduct_line_capacity_detail(this.form).then(response => {
          console.log(response)
          this.capacityList = response.data.data;
          this.capacityList.forEach(item=>{
            item.checked = (item.plannedCapacity-item.plannedSumCapacity>=this.form.thisCapacity)
          })
          this.loading = false;
        });
      },
      manuSchedule(){

        if (this.selection.length != 1) {
          this.$message.warning('请选择一条计划！');
          return;
        };

        if (this.selection[0].scheduleStatus != null) {
          this.$message.warning('该计划已经发布排程信息！');
          return;
        };
        this.reset();
        //初始化工艺路线
        bomRoutingList(this.selection[0].bomCategoryId).then((res) => {
          this.routingList = res || [];
        });

        //计算本计划的
        this.form.thisCapacity = this.selection[0].productNum * this.selection[0].productUnitWeight;



        // const id = this.selection[0].productLineId;

        // this.form.productLineId = id;
        this.open = true;
        this.title = "占用产线月产能详情";

      },
      /** 查询产线列表 */
      getProductLine() {
        this.loading = true;
        listProduct_line(null).then(response => {
          this.loading = false;
          this.product_line_select = response.data.data.list;
         if (this.product_line_select==null||this.product_line_select.length==0) {
          this.$message.success("没有配置产线");
         }

        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          year: null,
          month: null,
          day: null,
          plannedCapacity: null,
          plannedSumCapacity: null,
          plannedOrder: null,
          plannedOrderCapacity: null,
          plannedOrderDate: null,
          status: null,
          delFlag: null,
          loginIp: null,
          loginDate: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.capacityList = [];
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {

              this.form.plannedOrderCapacity = this.form.thisCapacity;
              this.form.plannedSumCapacity = this.form.thisCapacity;
              this.form.plannedOrder = this.selection[0].code;
              this.form.plannedOrderDate = this.form.year+"-"+this.form.month+"-"+this.form.day;
              occupyRes(this.form).then(response => {

                this.open = false;
                if (response.code == -1)  this.$message.warning('系统错误！');
                else this.$message.success("占用成功");
                this.getFieldModel();
              });
            } else {
              this.form.plannedOrderCapacity = this.thisCapacity;
              this.form.plannedSumCapacity = this.thisCapacity;
              this.form.plannedOrder = this.selection[0].code;
              this.form.plannedOrderDate = this.form.year+"-"+this.form.month+"-"+this.form.day;
              addProduct_line_capacity_detail(this.form).then(response => {

                this.open = false;
                if (response.code == -1)  this.$message.warning('系统错误！');
                else this.$message.success("新增成功");
                this.getFieldModel();
              });
            }
          }
        });
      },
      async getPlanStatistics() {
        let res = await getPlanStatistics();
        console.log(res);
        this.planStatistics = res;
      },
      homogeneityInspect() {
        if (this.selection.length == 0) {
          this.$message.warning('请至少选择一条计划！');
          return;
        }
        let flag = false;
        let type = 0;
        for (let item of this.selection) {
          type = item.produceType;
          for (let ele of this.selection) {
            if (item.produceType != ele.produceType) {
              flag = true;
              break;
            }
          }
        }
        if (flag) {
          this.$message.warning('请选择生产类型相同的计划！');
          return;
        }
        console.log(type);
        if (type == 2) {
          this.$refs.homogeneityInspectDialog.open(this.selection);
        } else if (type == 3) {
          this.$refs.homogeneityInspectInstallDialog.open(this.selection);
        } else {
          this.$message.warning('请确认生产类型！');
        }
      },
      statusFormatter(status) {
        const obj = this.statusOpt[this.activeName].find(
          (i) => i.value == status
        );

        return obj && obj.label;
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        return getList({
          pageNum: page,
          timeDimensionPlanType: this.timeDimensionPlanType,
          size: limit,
          ...where,
          ...this.sort
        });
      },
      // 发布工单
      handleOrderPublish(type, row) {
        if (!row.produceRoutingName) {
          return this.$message.error('请先选择工艺路线！');
        }

        this.$confirm('发布工单后不可撤回，确定发布吗？', '发布确认')
          .then(async () => {
            const loading = this.$loading({
              lock: true,
              fullscreen: true,
              text: '工单发布中...'
            });
            try {
              let code = row.workOrderCode;
              if (!code) {
                code = await getCode('product_order_code');
              }
              // 反显对象会报错 status
              const data = await release([row.id]);
              if (data || data === 0) {
                this.$message.success('发布成功！');
              } else {
                this.$message.error('发布失败，请重新发布！');
              }
              this.reload();
            } catch (error) {
              console.error(error);
            }
            loading.close();
          })
          .catch((err) => {
            console.error(err);
          });

        // this.$router.push({
        //   path: '/productionPlan/workOrderPublish',
        //   query: {
        //     type,
        //     id: row.id
        //   }
        // });
      },
      // 修改计划
      planEdit(row) {
        console.log(row,'888888888');
        if (row.timeDimensionPlanType == 3) {
          this.factoryObj = row;
          // this.factoryType = ;
          this.factoryShow = true;
        } else {
          this.$router.push({
            path: '/saleOrder/salesToProduction',
            query: {
              type: 'edit',
              id: row.id
            }
          });
        }
      },

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

          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();
        });
      },

      handleTabChange() {
        this.$refs.searchRef.reset();
      },

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

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

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

      handleDel(row) {
        this.$confirm('确定删除当前数据？', '提示')
          .then(() => {
            del(row.id).then((res) => {
              this.reload();
              this.$message.success('删除成功');
            });
          })
          .catch(() => {});
      },
      handleSelectionChange(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 = [];
        }


      },

      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;
      },

      goDetail({ id }) {
        this.$router.push({
          path: '/productionPlan/detail',
          query: { id }
        });
      },

      //  计划分解
      disassemblePlan() {
        if (this.selection.length != 1) {
          return this.$message.warning('计划分解只能选择一个计划！');
        }

        this.$refs.disassemblePlanRef.open(this.selection[0]);
      },

      // 拆批
      toUnpack(row) {
        if (!row.batchNo) {
          return this.$message.error('请先填写批次号！');
        }
        this.$refs.unpackRef.open(row);
      },

      // 合并
      handleMerge() {
        if (this.selection.length <= 1) {
          return this.$message.warning('请先勾选二个或多个计划！');
        }
        const productCode = this.selection[0].productCode;
        const produceRoutingId = this.selection[0].produceRoutingId;

        for (var i = 0; i < this.selection.length; i++) {
          if (productCode != this.selection[i].productCode) {
            return this.$message.warning('产品编码不一致！');
          }

          if (produceRoutingId != this.selection[i].produceRoutingId) {
            return this.$message.warning('工艺路线不一致！');
          }
        }

        this.$refs.mergeRef.open(this.selection);

        console.log(this.selection);
      },

      splitDetails(type, row) {
        this.$refs.DetailsRef.open(type, row);
      },

      factAdd(type) {
        this.factoryType = type;
        this.factoryShow = true;
      },

      factoryClose(val) {
        this.factoryShow = false;
        this.factoryType= 3;
        this.factoryObj= {};
        if (val) {
          this.reload();
        }
      },

      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);
      },

      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>
  .btn_box {
    margin-bottom: 6px;
  }

  .check_box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }

  .check {
    width: 14px;
    height: 14px;
    border: 1px solid #dddddd;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .act_check {
    border: 1px solid #409eff;
    background: #409eff;

    .el-icon-check {
      color: #fff;
      font-size: 10px;
    }
  }
  .statistics {
    padding: 10px 10px 20px;
  }
  .cardItem {
    border: 1px solid rgb(225, 225, 225);
    text-align: center;
    color: white;
    background-color: rgba(24, 144, 255, 0.8);
    overflow: hidden;
    padding: 10px;
  }
  .cardText {
    font-size: 16px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .cardNum {
    font-size: 32px;
    font-style: italic;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  @media (max-width: 768px) {
    .cardText {
      font-size: 14px;
    }

    .cardNum {
      font-size: 24px;
    }
  }
  ::v-deep .el-card__body {
    padding: 17px 12px !important;
  }

  .bottom {
    flex: 1;
    width: 100%;
    .box {
      width: 15%;
      height: 69px;
      margin-right: 2%;
      margin-bottom: 10px;
      display: inline-block;
      cursor: pointer;
      .item {
        width: 100%;
        height: 100%;
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-radius: 2px;
        border: 1px solid #d9d9d9;
        .date {
          color: #202325;
        }
        .checked {
          position: absolute;
          top: 0;
          right: 0;
          width: 46px;
          height: 46px;
          > img {
            height: 100%;
            width: 100%;
          }
        }
      }
      .active {
        border-color: #2d80ee;
      }
    }
    .margin_0 {
      margin-right: 0;
    }
  }
</style>
