<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <search ref="search" @search="reload"></search>

      <ele-pro-table
        ref="tableRef"
        :columns="columns"
        :datasource="datasource"
        :pageSize="20"
        :pageSizes="[20, 30, 40, 50, 100]"
        row-key="id"
        @selection-change="handleSelectionChange"
        :initLoad="false"
        @select="handleSelect"
        @done="onDone"
        @columns-change="handleColumnChange"
        :cacheKey="cacheKeyUrl"
      >
        <template v-slot:toolbar>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleEstimatedDelivery"
            >交期预估</el-button
          >
          <el-button
            style="
              background-color: #dd2c00;
              color: white;
              border-color: #dd2c00;
            "
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >批量删除</el-button
          >
          <!-- <el-button style="background-color: #ec407a;color: white;border-color: #ec407a" icon="el-icon-download"
            size="mini" :disabled="single" @click="handleExpect">交期预估</el-button> -->
          <!-- <el-button style="background-color: #cddc39;color: white;border-color: #cddc39" icon="el-icon-download"
            size="mini" :disabled="multiple" @click="handleAllExpect">全部预估</el-button> -->
          <el-button
            style="
              background-color: #ec407a;
              color: white;
              border-color: #ec407a;
            "
            icon="el-icon-download"
            size="mini"
            @click="importTemplate"
            >下载模板</el-button
          >
          <el-button
            type="info"
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            >导入</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
          <el-button
            style="
              background-color: #8bc34a;
              color: white;
              border-color: #8bc34a;
            "
            icon="el-icon-download"
            size="mini"
            :disabled="ids.length == 0"
            @click="handleSaleorder"
            >转销售订单</el-button
          >
          <!-- <el-button type="success" icon="el-icon-download" size="mini"
            @click="handleAllSaleorder">一次性转销售订单</el-button> -->
        </template>
        <template v-slot:status="{ row }">
          {{
            row.status == 0
              ? '未预估'
              : row.status == 1
              ? '已预估'
              : '已转销售单'
          }}
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          >
            修改
          </el-link>
          <!-- <el-link type="danger" :underline="false" icon="el-icon-delete" @click="handleDelete(row)">
            删除
          </el-link> -->
          <el-popconfirm
            class="ele-action"
            title="是否确认删除此数据？"
            @confirm="handleDelete(row)"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>

      <!-- 添加或修改销售订单对话框 -->
      <ele-modal
        :title="titleExpect"
        :visible.sync="openExpect"
        :before-close="cancelExpect"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
        width="70%"
        :maxable="true"
      >
        <el-table v-loading="loading" :data="salesOrderExpectList">
          <el-table-column label="序号" align="center" prop="id" />
          <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>
      </ele-modal>

      <!-- 添加或修改销售订单对话框 -->
      <ele-modal
        :title="title"
        :visible.sync="open"
        :before-close="cancel"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
        width="70%"
        :maxable="true"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="销售订单" prop="preSalesOrderNumber">
                <el-input
                  v-model="form.preSalesOrderNumber"
                  placeholder="请输入销售订单"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户代号" prop="customerCode">
                <el-input
                  v-model="form.customerCode"
                  placeholder="请输入客户代号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="customerName">
                <el-input
                  v-model="form.customerName"
                  placeholder="请输入客户名称"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="主机描述" prop="hostDescription">
                <el-input
                  v-model="form.hostDescription"
                  type="textarea"
                  placeholder="请输入主机描述"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主机编码" prop="hostCode">
                <el-input
                  v-model="form.hostCode"
                  placeholder="请输入主机编码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单数量" prop="materialQuantity">
                <el-input
                  v-model="form.materialQuantity"
                  placeholder="请输入订单数量"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="重量" prop="materialWeightKg">
                <el-input
                  v-model="form.materialWeightKg"
                  placeholder="请输入物料重量"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发货数量" prop="sendNum">
                <el-input v-model="form.sendNum" placeholder="请输入发货数量" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户交期" prop="customerDeliveryDate">
                <el-date-picker
                  clearable
                  v-model="form.customerDeliveryDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择客户交期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生产交期" prop="productionDeliveryDate">
                <el-date-picker
                  clearable
                  v-model="form.productionDeliveryDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择生产交期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交货方式" prop="deliveryMethod">
                <el-select
                  v-model="form.deliveryMethod"
                  placeholder="请选择交货方式"
                >
                  <el-option
                    v-for="item in deliveryMethodOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="材料编码" prop="materialCode">
                <el-input
                  v-model="form.materialCode"
                  placeholder="请输入材料编码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="材料描述" prop="materialDescription">
                <el-input
                  v-model="form.materialDescription"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编号" prop="productionCodes">
                <el-input
                  v-model="form.productionCodes"
                  placeholder="请输入编号,用','隔开"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="密度" prop="density">
                <el-input v-model="form.density" placeholder="请输入密度" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="图纸版本" prop="drawingVersion">
                <el-input
                  v-model="form.drawingVersion"
                  placeholder="请输入图纸版本"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单类型" prop="orderType">
                <el-select
                  v-model="form.orderType"
                  placeholder="请选择订单类型"
                >
                  <el-option
                    v-for="item in orderTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </ele-modal>

      <!-- 直报系统导入对话框 -->
      <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadFile"
          :before-upload="beforeUpload" :on-change="handleChange" ref="uploadFile">
          <el-button type="warning" size="mini">批量导入</el-button>
        </el-upload>

      </el-dialog> -->

      <ele-modal
        title="选择工厂"
        :visible.sync="factoriesVisible"
        :before-close="handleCancel"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
        width="20%"
        :maxable="true"
      >
        <el-row>
          <el-select v-model="factoriesId">
            <el-option
              v-for="item of factoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCancel">取 消</el-button>
        </div>
      </ele-modal>
    </el-card>
    <importDialog
      :defModule="upload.title"
      ref="importDialogRef"
      @success="reload"
    />
  </div>
</template>

<script>
  import {
    estimateDeliveryDates,
    createAll,
    convertToSalesOrder,
    importTemplate,
    exportFile,
    importFile,
    listSalesorder,
    getSalesOrder,
    delSalesorder,
    addSalesorder,
    updateSalesorder,
    listSalesOrderExpect,
    occupyRes,
    listSalesOrderOccupyRes,
    listSalesorderExpectAll,
    occupyAllRes,
    getQueryFactory
  } from '@/api/aps/presalesorder';
  import { API_BASE_URL } from '@/config/setting';

  import modalTitle from '@/components/modalTitle.vue';
  import search from './search.vue';
  import importDialog from './import-dialog.vue';
  import tabMixins from '@/mixins/tableColumnsMixin';

  export default {
    name: 'PreSalesorder',
    mixins: [tabMixins],
    components: { modalTitle, search, importDialog },
    data() {
      return {
        fullscreen: false,
        fileList: [],
        isSubmitting: true,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          // headers: {
          // 	Authorization: "Bearer " +getToken()
          // },
          // 上传的地址
          url: API_BASE_URL + '/aps/presalesorder/importData'
        },
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        selectionData: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 销售订单表格数据
        salesorderList: [],
        // 销售订单交期预估表格数据
        salesOrderExpectList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        titleExpect: '交期确定',
        // 是否显示弹出层
        openExpect: false,
        cacheKeyUrl: 'c32a9c7d-aps-presalesorder-index',

        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            reserveSelection: true
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'orderType',
            label: '订单类型',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'preSalesOrderNumber',
            label: '预销售订单号',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'customerCode',
            label: '客户代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'customerName',
            label: '客户名称',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'hostDescription',
            label: '主机描述',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'hostCode',
            label: '主机编码',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          // {
          //   prop: 'orderQuantity',
          //   label: '订单数量',
          //   showOverflowTooltip: true,
          //   align: 'center',
          // },
          // {
          //   prop: 'unit',
          //   label: '单位',
          //   showOverflowTooltip: true,
          //   align: 'center',
          // },
          // {
          //   prop: 'weightKg',
          //   label: '重量',
          //   showOverflowTooltip: true,
          //   align: 'center',
          // },
          {
            prop: 'deliveryMethod',
            label: '交货方式',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'customerDeliveryDate',
            label: '客户交期',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'productionDeliveryDate',
            label: '生产交期',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'materialCode',
            label: '材料编码',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'materialDescription',
            label: '材料描述',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'productionCodes',
            label: '生产编号',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'factoriesName',
            label: '工厂名称',
            showOverflowTooltip: true,
            align: 'center',
            width: 120
          },
          {
            prop: 'sendNum',
            label: '发货数量',
            showOverflowTooltip: true,
            align: 'center',
            width: 140
          },
          {
            prop: 'materialQuantity',
            label: '订单数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'materialWeightKg',
            label: '重量(kg)',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'materialUnit',
            label: '单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'status',
            slot: 'status',
            width: 120,
            label: '订单状态',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'density',
            width: 120,
            label: '密度',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'drawingVersion',
            width: 120,
            label: '图纸版本',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right'
          }
        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          preSalesOrderNumber: [
            { required: true, message: '销售订单不能为空', trigger: 'blur' }
          ]
        },
        selDataIds: [],
        whereForm: {},
        factoriesId: '',
        factoriesVisible: false,
        factoryList: [],
        orderTypeOptions: [
          {
            value: '库存式订单',
            label: '库存式订单'
          },
          {
            value: '生产性订单',
            label: '生产性订单'
          }
        ],
        deliveryMethodOptions: [
          {
            value: '一次性交货',
            label: '一次性交货'
          },
          {
            value: '分批交货',
            label: '分批交货'
          }
        ]
      };
    },
    async created() {
      await this.reload();
      await this.getFactoryList();
    },
    methods: {
      handleSelect(selection, row) {
        const matchField = 'preSalesOrderNumber';
        const isSelected = selection.some((item) => item.id === row.id);
        const list = this.$refs.tableRef.getData();
        const matchedRows = list.filter(
          (item) => item[matchField] === row[matchField]
        );

        // 批量设置选择状态
        this.$nextTick(() => {
          matchedRows.forEach((item) => {
            this.$refs.tableRef.toggleRowSelection(item, isSelected);
          });
        });
      },

      async getFactoryList() {
        const res = await getQueryFactory();
        console.log(res, 'data工厂');
        this.factoryList = res.data;
      },
      datasource({ page, where, limit }) {
        let pageNum = page;
        let size = limit;
        where.queryType = 1; //查询类型（1：预销售单页面查询；2：已转销售单页面查询)
        const res = listSalesorder({ ...where, pageNum, size });
        return res;
      },
      reload(where) {
        console.log(where, 'where22222');
        this.whereForm = where;
        this.$nextTick(() => {
          if (this.$refs.tableRef && this.$refs.tableRef.reload)
            this.$refs.tableRef.reload({ page: 1, where: where });
        });
      },
      onDone() {
        this.$nextTick(() => {
          this.$refs.tableRef.setSelectedRowKeys(this.selDataIds);
        });
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.resetForm();
        const id = row.id || this.ids;
        getSalesOrder(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = '修改销售订单';
        });
      },
      /** 删除 */
      handleDelete(row) {
        let ids = [];
        if (row.id) {
          ids = [row.id];
        } else {
          ids = this.ids;
        }
        this.$confirm(`是否确认删除该数据？`, '提示')
          .then(() => {
            delSalesorder({ ids: ids })
              .then(() => {
                this.reload();
                this.$message.success('删除成功');
              })
              .catch((e) => {
                console.log(e);
              });
          })
          .catch(() => {});
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.selectionData = selection;
        console.log(this.ids, 'selection');
        this.single = selection.length !== 1;
        this.multiple = !selection.length;

        // if (selection.length == 1) {
        //   const selSalesOrderNumber = selection[0].preSalesOrderNumber;
        //   const list = this.$refs.tableRef.getData();
        //   const data = []
        //   for (let i = 0; i < list.length; i++) {
        //     if (list[i].preSalesOrderNumber == selSalesOrderNumber) {

        //       data.push(list[i].id);
        //     }
        //   }

        //   this.selDataIds = data;

        // }
        // console.log(this.selDataIds, '勾选')
        // if (this.selDataIds.length > 0) {
        //   this.$refs.tableRef.setSelectedRowKeys(this.selDataIds);
        // }
      },

      async handleEstimatedDelivery() {
        if (this.ids.length === 0) {
          this.$message.warning('请选择');
          return;
        }
        this.factoriesId = '';
        this.factoriesVisible = true;
      },

      async handleSubmit() {
        const res = await estimateDeliveryDates({
          ids: this.ids,
          factoriesId: this.factoriesId
        });
        if (res.code == 0) {
          this.$message.success('操作成功');
          this.factoriesVisible = false;
          this.reload();
        }
      },
      handleCancel() {
        this.factoriesVisible = false;
      },
      /*交期预估*/
      async handleExpect(row) {
        if (this.ids.length === 0) {
          this.$message.warning('请选择');
          return;
        }

        const id = row.id || this.ids;

        const response = await getSalesOrder(id);
        const saleOrder = response.data;
        this.form = response.data;

        //如果是已经占用资源，则显示已经占用的资源,不能重复
        if (saleOrder.status === '1' || saleOrder.status === '2') {
          const occupyRes = await listSalesOrderOccupyRes(saleOrder);
          this.salesOrderExpectList = occupyRes;
          this.single = true;
          this.multiple = true;
        } else if (saleOrder.status === '0') {
          const expectRes = await listSalesOrderExpect(saleOrder);
          this.salesOrderExpectList = expectRes;
          this.single = false;
          this.multiple = true;
        }
        console.log(
          this.salesOrderExpectList.length,
          'this.salesOrderExpectList.length'
        );
        if (this.salesOrderExpectList.length > 0) {
          this.submitFormAllExpect();
        }
      },
      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.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, 'arr');
        occupyAllRes(arr).then((response) => {
          //console.log(response)
          // this.openExpect = false;
          this.reload();

          this.$message.success('占用成功');
        });
      },
      //全部预估
      // handleAllExpect() {

      //   listSalesorderExpectAll().then(response => {

      //     this.salesOrderExpectList = response;
      //     this.openExpect = true;
      //     this.single = true;
      //     this.multiple = false;
      //   });
      // },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = '销售订单数据导入';
        // this.upload.open = true;
        this.$refs.importDialogRef.open();
      },
      //文件上传
      uploadFile(param) {
        let fd = new FormData();
        this.fileList.forEach((item) => {
          fd.append('importExcel', item.raw);
        });
        importFile(fd)
          .then((res) => {
            this.$refs.uploadFile.clearFiles();

            this.upload.open = false;
            this.reload();
          })
          .catch((data) => {
            if (data.code != -1) {
              this.$message.error(data.message);
            }
          })
          .finally(() => {
            this.$refs.uploadFile.clearFiles();
          });
      },
      //上传限制
      beforeUpload(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('上传文件大小不能超过 10MB!');
        }
        return isLt10M;
      },
      handleChange(file, fileList) {
        this.fileList = fileList;
        console.log(fileList);
      },
      /** 导出按钮操作 */
      handleExport() {
        console.log(this.whereForm, 'this.whereForm');

        this.loading = true;
        let params = this.whereForm ? this.whereForm : {};
        params.queryType = 1;
        exportFile(params).then((res) => {
          this.loading = false;
        });
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate(this.whereForm).then((res) => {
          this.$message.success('模板下载成功');
        });
      },

      /** 转销售单按钮操作 */
      handleSaleorder(row) {
        if (this.ids.length == 0) {
          this.$message.warning('请选择');
          return;
        }

        const filteredData = this.selectionData.filter(
          (item) => item.status == 1
        );
        console.log(filteredData, 'filteredData');
        if (filteredData.length > 0) {
          const ids = filteredData.map((item) => item.id);
          convertToSalesOrder({ ids: ids }).then((response) => {
            this.$message.success('转换成功');
            this.reload();
          });
        } else {
          this.$message.warning('请选择订单状态为已预估的数据！');
          return;
        }

        // const id = row.id || this.ids

        // getSalesOrder(id).then(response => {
        //   let saleorder = response.data;
        //   this.form = response.data;
        //   console.log(saleorder);
        //   //如果是已经占用资源，则显示已经占用的资源,不能重复
        //   if (saleorder.status == "1") {
        //     convertToSalesOrder(this.ids).then(response => {
        //       this.$message.success("转换成功");
        //     });
        //     return;
        //   }
        //   else if (saleorder.status == "0") {
        //     //如果没有
        //     this.$message.success("没有交期预估");
        //   } else if (saleorder.status == "2") {
        //     //如果没有
        //     this.$message.success("已经转换过了");
        //   }
        // });
      },
      // 表单重置
      resetForm() {
        this.form = {
          id: null,
          preSalesOrderNumber: null,
          customerCode: null,
          customerName: null,
          productDescription: null,
          productCode: null,
          orderQuantity: null,
          unit: null,
          weightKg: null,
          customerDeliveryDate: null,
          productionDeliveryDate: null,
          materialCode: null,
          materialDescription: null,
          materialQuantity: null,
          materialUnit: null,
          materialWeightKg: null,
          status: null
        };
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.resetForm();
      },
      // 取消按钮
      cancelExpect() {
        this.openExpect = false;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              if (this.form.productionCodes) {
                this.form.productionCodes = this.form.productionCodes.replace(
                  /，/g,
                  ','
                );
              }

              this.form.materialQuantity = this.form.materialQuantity
                ? this.form.materialQuantity
                : 0;

              this.form.materialWeightKg = this.form.materialWeightKg
                ? this.form.materialWeightKg
                : 0;

              this.form.sendNum = this.form.sendNum ? this.form.sendNum : 0;

              updateSalesorder(this.form).then((response) => {
                this.$message.success('修改成功');
                this.open = false;
                this.reload();
              });
            } else {
              addSalesorder(this.form).then((response) => {
                this.$message.success('新增成功');
                this.open = false;
                this.reload();
              });
            }
          }
        });
      },
      /** 提交交期确定按钮 */
      submitFormExpect() {
        const id = this.ids;
        getSalesOrder(id).then((response) => {
          // console.log(response);
          let saleorder = response.data;
          if (saleorder.status == '1' || saleorder.status == '2') {
            this.$message.success('已经分配过资源');
            return;
          }
          var i = 0;
          this.salesOrderExpectList.forEach((item) => {
            i++;
            item.plannedOrder =
              saleorder.preSalesOrderNumber + '-' + saleorder.materialCode + '';
            item.plannedOrderCapacity = item.currenPlannedSumCapacity;
            item.plannedSumCapacity = item.currenPlannedSumCapacity;
          });

          var lastNode =
            this.salesOrderExpectList[this.salesOrderExpectList.length - 1];
          console.log(lastNode, '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.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.currenPlannedSumCapacity = item.currenPlannedSumCapacity;
            node.plannedSumCapacity = item.plannedSumCapacity;
            node.plannedOrder = item.plannedOrder;
            node.plannedOrderCapacity = item.plannedOrderCapacity;
            node.plannedOrderDate = item.plannedOrderDate;
            arr.push(node);
          });
          occupyRes(arr).then((response) => {
            this.$message.success('占用成功');

            saleorder.status = '1';
            console.log(saleorder);
            updateSalesorder(saleorder).then((response) => {
              this.$message.success('修改成功');
              this.openExpect = false;
              this.reload();
            });
          });
        });
      },

      /** 转销售单按钮操作 */
      handleAllSaleorder() {
        this.loading = true;
        let saleorder = {};
        //如果是已经占用资源，则显示已经占用的资源,不能重复
        createAll(saleorder).then((response) => {
          this.$message.success('转换成功');
          this.loading = false;
        });
      }

      // // 提交上传文件
      // submitFileForm() {
      //   this.$refs.upload.submit();
      // },
      // // 文件上传中处理
      // handleFileUploadProgress(event, file, fileList) {
      //   this.upload.isUploading = true;
      // },
      // // 文件上传成功处理
      // handleFileSuccess(response, file, fileList) {
      //   this.upload.open = false;
      //   this.upload.isUploading = false;
      //   this.$refs.upload.clearFiles();
      //   this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      //     response.msg + "</div>", "导入结果", {
      //     dangerouslyUseHTMLString: true
      //   });
      //   this.reload();
      // },
    }
  };
</script>
