<template>
  <div>
    <ele-modal
      :visible.sync="visible"
      :title="title"
      width="80vw"
      append-to-body
      :maxable="true"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        class="create-form"
      >
        <el-row :gutter="24">
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="销售订单号:">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.code"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="订单类型:" prop="orderType">
              <el-select v-model="form.orderType" style="width: 100%">
                <el-option
                  v-for="item of orderTypeList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="销售类型:">
              <DictSelection
                dictName="订单类型"
                clearable
                v-model="form.saleType"
              >
              </DictSelection>
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="按单按库:">
              <DictSelection
                dictName="按单按库"
                clearable
                v-model="form.orderLibraryType"
              >
              </DictSelection>
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="客户名称:">
              <el-input
                clearable
                v-model="form.customerName"
                :disabled="form.saleType == 3"
                style="width: calc(100% - 70px)"
              />
              <!-- <el-button style="margin-left: 3px;" size="small" type="primary" @click.native="$refs.contactDialogRef.open()"
              >选择
            </el-button> -->
              <contactDialog
                style="margin-left: 3px"
                @changeParent="contactDialogSuccess"
              ></contactDialog>
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="客户简称:">
              <el-input
                clearable
                v-model="form.simpleName"
                :disabled="form.saleType == 3"
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="客户代号:">
              <el-input
                clearable
                v-model="form.serialNo"
                :disabled="form.saleType == 3"
              />
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="业务员:">
              <el-input
                clearable
                v-model="form.salesman"
                style="width: calc(100% - 70px)"
              />
              <el-button
                style="margin-left: 3px"
                type="primary"
                size="small"
                @click="selectPersonnel"
                >选择</el-button
              >
            </el-form-item>
          </el-col>

          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="交付日期:" prop="deliveryTime">
              <el-date-picker
                :picker-options="pickerOptions"
                style="width: 100%"
                v-model="form.deliveryTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="齐套状态:" prop="completeState">
              <el-select v-model="form.completeState" style="width: 100%">
                <el-option v-for="item of completeList" :key="item.code" :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="备注:">
              <el-input clearable v-model="form.notes" />
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
            <el-form-item label="交付要求:">
              <DictSelection
                dictName="紧急程度"
                clearable
                v-model="form.deliveryRequirements"
              >
              </DictSelection>
            </el-form-item>
          </el-col>
          <el-col v-bind="styleResponsive ? { lg: 5, md: 10 } : { span: 5 }">
            <el-form-item label="生产要求:" required>
              <el-input
                v-model="form.productionRequirements"
                style="width: 100%"
                placeholder=""
                type="textarea"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table :data="form.productInfoList" border height="40vh" key="id">
          <el-table-column label="序号" align="center" width="60">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="行号" align="center" prop="lineNumber">
          </el-table-column>
          <el-table-column
            label="名称"
            align="center"
            prop="productName"
            width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="编码"
            align="center"
            prop="productCode"
            width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="牌号" align="center" prop="brandNo">
          </el-table-column>
          <el-table-column label="型号" align="center" prop="model">
          </el-table-column>
          <el-table-column
            label="规格"
            align="center"
            prop="specification"
            width="150"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="单重" align="center" prop="productUnitWeight">
          </el-table-column>
          <el-table-column label="重量单位" align="center" prop="weightUnit">
          </el-table-column>
          <el-table-column
            label="机型"
            align="center"
            prop="modelKey"
            width="240"
          >
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.modelKey'"
              >
                <el-select
                  clearable
                  v-model="scope.row.modelKey"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                >
                  <el-option
                    v-for="item in modelList"
                    :key="item.label"
                    :value="item.label"
                    :label="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="颜色"
            align="center"
            prop="colorKey"
            width="240"
          >
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.colorKey'"
              >
                <el-select
                  clearable
                  v-model="scope.row.colorKey"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                >
                  <el-option
                    v-for="item in colorList"
                    :key="item.label"
                    :value="item.label"
                    :label="item.label"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="生产编号"
            align="center"
            prop="productionCodes"
            width="140"
          >
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.productionCodes'"
              >
                <el-input
                  style="width: 100%"
                  size="small"
                  v-model="scope.row.productionCodes"
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="批次号"
            align="center"
            prop="batchNo"
            width="140"
          >
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.batchNo'"
              >
                <el-input
                  style="width: 100%"
                  size="small"
                  v-model="scope.row.batchNo"
                  placeholder="请输入"
                  @input="
                    (value) =>
                      (scope.row.batchNo = value.replace(/[^a-zA-Z0-9_-]/g, ''))
                  "
                >
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="订单数量"
            width="140"
            align="center"
            prop="contractNum"
          >
            <template slot="header" slot-scope="scope">
              <div class="header_required"
                ><span class="is-required">订单数量</span></div
              >
            </template>
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.contractNum'"
                :rules="{
                  required: true,
                  message: '请输入订单数量',
                  trigger: 'blur'
                }"
              >
                <el-input
                  v-model.number="scope.row.contractNum"
                  size="small"
                  type="number"
                  style="width: 100%"
                  placeholder="输入数量"
                  @input="inputNumber(scope.row, scope.$index)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="BOM类型"
            width="140"
            align="center"
            prop="productType"
          >
            <template slot="header" slot-scope="scope">
              <div :class="isRequired ? 'header_required' : ''"
                ><span class="is-required">BOM类型</span></div
              >
            </template>
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.productType'"
              >
                <el-select
                  v-model="scope.row.productType"
                  @change="changeProductType(scope.row, scope.$index)"
                  :key="scope.$index"
                  :disabled="!isAdd"
                >
                  <el-option
                    v-for="item of scope.row.producedList"
                    :key="scope.$index + item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            :label-class-name="isRequired ? 'header_required' : ''"
            label="BOM版本"
            width="140"
            align="center"
            prop="bomCategoryId"
            v-if="clientEnvironmentId != 4"
          >
            <template slot="header" slot-scope="scope">
              <div :class="isRequired ? 'header_required' : ''"
                ><span class="is-required">BOM版本</span></div
              >
            </template>
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.bomCategoryId'"
                :key="scope.$index"
              >
                <el-select
                  v-model="scope.row.bomCategoryId"
                  @change="changeBomId(scope.row, scope.$index)"
                  :disabled="!isAdd"
                >
                  <el-option
                    v-for="item of scope.row.bomVersionList"
                    :key="item.id"
                    :label="item.name + '(V' + item.versions + '.0)'"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="工艺路线"
            width="240"
            align="center"
            prop="produceRoutingId"
            v-if="clientEnvironmentId != 4"
          >
            <template slot="header" slot-scope="scope">
              <div class="header_required"
                ><span class="is-required">工艺路线</span></div
              >
            </template>
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="'productInfoList.' + scope.$index + '.produceRoutingId'"
              >
                <div style="display: flex">
                  <el-select
                    v-model="scope.row.produceRoutingId"
                    @change="changeRoutingList(scope.row, scope.$index)"
                    v-show="isRouteSelect(scope.row)"
                  >
                    <el-option
                      v-for="item of scope.row.routingList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                  <div style="display: flex">
                    <el-input
                      v-show="!isRouteSelect(scope.row)"
                      disabled
                      v-model="scope.row.produceRoutingName"
                    ></el-input>
                    <el-button
                      v-show="isSelectShow"
                      type="primary"
                      size="mini"
                      @click="openDialog(scope.$index)"
                      >选择</el-button
                    >
                  </div>
                </div>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="工艺路线"
            align="center"
            prop="produceRoutingName"
            v-if="clientEnvironmentId == 4"
          >
            <template slot-scope="scope">
              <el-form-item
                label-width="0px"
                :prop="
                  'productInfoList.' + scope.$index + '.produceRoutingName'
                "
              >
                <el-input
                  v-model="form.produceRoutingName"
                  style="width: 100%"
                  readonly
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            label="所属工厂"
            width="140"
            align="center"
            prop="factoriesId"
          >
            <template slot="header" slot-scope="scope">
              <div class="header_required"
                ><span class="is-required">所属工厂</span></div
              >
            </template>
            <template slot-scope="scope">
              <el-form-item label-width="0px">
                <el-select
                  v-model="scope.row.factoriesId"
                  :key="scope.row.factoriesId"
                  @change="(e) => factorChange(e, scope.row)"
                >
                  <el-option
                    v-for="item of factoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="计量单位" align="center" prop="measuringUnit">
          </el-table-column>
          <el-table-column
            label="模数"
            align="center"
            width="100"
            v-if="clientEnvironmentId == '4'"
          >
            <template slot-scope="scope">
              <div>
                <el-input
                  style="width: 100%"
                  size="small"
                  v-model="scope.row.moCount"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  @input="
                    tableHandleKeyUp(scope.row, scope.$index, $event, 'moCount')
                  "
                  placeholder="请输入"
                >
                </el-input>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            width="100"
            label="块数"
            v-if="clientEnvironmentId == '4'"
          >
            <template slot-scope="scope">
              <div>
                <el-input
                  size="small"
                  style="width: 100%"
                  @input="
                    tableHandleKeyUp(
                      scope.row,
                      scope.$index,
                      $event,
                      'blockCount'
                    )
                  "
                  v-model="scope.row.blockCount"
                  placeholder="请输入"
                ></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单重量" align="center" prop="productWeight">
            <template slot-scope="{ row }">
              <span>{{ row.productWeight ? row.productWeight : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160">
            <template slot-scope="scope">
              <!-- <el-link
                type="primary"
                :underline="false"
                @click="homogeneityInspect(scope.row)"
              >
                齐套性检查
              </el-link> -->
              <el-button
                type="text"
                @click="handleDeleteItem(scope.$index)"
                v-if="!scope.row.id"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="add-product" @click="addEquipment" v-if="isAdd">
          <i class="el-icon-circle-plus-outline"></i>
        </div>
      </el-form>
      <template v-slot:footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确定
        </el-button>
      </template>
      <!-- 选择工艺路线 -->
      <ProcessRoute ref="processRouteRef" @changeParent="changeParent" />
      <!-- 选择产品 -->
      <EquipmentDialog
        ref="equipmentRefs"
        @choose="confirmChoose"
        :selectList="
          form.productInfoList.filter(
            (i) => !disabledList.find((p) => p.productCode === i.productCode)
          )
        "
      >
      </EquipmentDialog>
    </ele-modal>
    <orderHomogeneityInspectDialog
      ref="orderHomogeneityInspectDialog"
    ></orderHomogeneityInspectDialog>
    <orderHomogeneityInspectInstallDialog
      ref="orderHomogeneityInspectInstallDialog"
    >
    </orderHomogeneityInspectInstallDialog>

    <personnelDialog ref="personnelRef" @changePersonnel="changePersonnel" />
  </div>
</template>

<script>
  import { getCode } from '@/api/codeManagement';
  import EquipmentDialog from '../components/EquipmentDialog.vue';
  import orderHomogeneityInspectDialog from './orderHomogeneityInspectDialog';
  import orderHomogeneityInspectInstallDialog from './orderHomogeneityInspectInstallDialog';
  import ProcessRoute from '@/components/selectionDialog/processRoute.vue';
  import personnelDialog from './personnelDialog.vue';
  import {
    createOrUpdate,
    getOrderDetail,
    bomListByPlan,
    bomRoutingList,
    getFactoryList,
    findBomCategoryByCategoryIds
  } from '@/api/saleOrder';
  import { listBomType } from '@/api/productionPlan/index';
  import { parameterGetByCode } from '@/api/mainData/index';
  import dayjs from 'dayjs';
  import { multiply } from '@/utils/math';
  import contactDialog from '@/components/contactDialog/openContactDialog.vue';
  import { getByCode } from '@/api/system/dictionary-data';
  export default {
    name: 'CreateOrder',
    components: {
      EquipmentDialog,
      orderHomogeneityInspectDialog,
      orderHomogeneityInspectInstallDialog,
      ProcessRoute,
      contactDialog,
      personnelDialog
    },
    props: {
      isAdd: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        disabledList: [], //已保存数据不做删除
        form: {
          salesman: '',
          salesmanId: '',
          productInfoList: [],
          deliveryRequirements: 1,
          saleType: 1,
          orderLibraryType: 2,
          productType: 2,
          bomCategoryId: '',
          produceRoutingId: '',
          factoriesId: '',
          deliveryTime: dayjs(
            new Date().getTime() + 3600 * 1000 * 24 * 10
          ).format('YYYY-MM-DD'),
          orderType: 0
        },
        // 表单验证规则
        rules: {
          deliveryTime: [
            { required: true, message: '请选择交付日期', trigger: 'change' }
          ],
          orderType: [
            { required: true, message: '请选择订单类型', trigger: 'blur' }
          ]
        },
        typeList: [
          { id: 1, label: '内销订单' },
          { id: 2, label: '外销订单' },
          { id: 3, label: '预制订单' }
        ],

        producedList: [
          { code: 2, name: '加工(MBOM)' },
          { code: 3, name: '装配(ABOM)' }
        ],

        completeList: [
          { code: 1, name: '齐套' },
          { code: 2, name: '缺料' }
        ],

        routingList: [],
        factoryList: [],

        title: '创建订单',
        pickerOptions: {
          disabledDate: (time) => {
            // 禁用日期
            let nowData = new Date();
            nowData = new Date(nowData.setDate(nowData.getDate() - 1));
            return time < nowData;
          }
        },
        // 订单类型
        orderTypeList: [
          {
            id: 0,
            label: '库存性订单'
          },
          {
            id: 1,
            label: '生产性订单'
          },
          {
            id: 2,
            label: '无客户生产性订单'
          },
          {
            id: 4,
            label: '不定向订单'
          }
        ],
        selectIndex: 0, // 选择工艺路线的当前数据下标
        processingRequired: 0, // 生产类型跟BOM 版本是否必填 1:是 0:否
        sourceSalesOrderId: '', // 源销售订单ID
        modelList: [], // 机型数据
        colorList: [] // 颜色数据
      };
    },
    watch: {
      // disabledList() {
      //   console.log(this.disabledList, 'disabledList');
      // }
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 是否必填字段
      isRequired() {
        // if (this.form.planType == 5) {
        //   return false;
        // }
        return this.processingRequired == 1;
      },
      // 工艺路线 输入框展示跟选择框判断
      isRouteSelect() {
        return (row) => {
          if (this.isRequired) {
            return true;
          }
          if (!row.selectionRowShow) {
            return true;
          }

          return false;
        };
      },

      // 选择按钮的显示
      isSelectShow() {
        // if (this.form.planType == 5) {
        //   return true;
        // }
        return this.processingRequired == 0;
      }
    },
    created() {},
    mounted() {
      this.mandatoryField();
      this.getFactoryList();
      this.getCodeData();
    },
    methods: {
      selectPersonnel() {
        this.$refs.personnelRef.open(this.form.salesmanId);
      },
      changePersonnel(row) {
        this.form.salesman = row.name;
        this.form.salesmanId = row.id;
      },
      // 获取
      async getCodeData() {
        let arr1 = await this.getLevelCode('product_model_key');
        let arr2 = await this.getLevelCode('product_color_key');
        this.modelList = arr1;
        this.colorList = arr2;
      },
      async getLevelCode(code) {
        try {
          const res = await getByCode(code);
          if (res.code == 0) {
            let list = Object.values(res.data).map((el) => {
              let k = Object.keys(el)[0];
              let v = Object.values(el)[0];
              return {
                label: v,
                value: k
              };
            });
            return list;
          }
        } catch (err) {
          this.$message.error(err.message);
        }
      },
      // 是否必填
      mandatoryField() {
        parameterGetByCode({
          code: 'production_plan_code'
        }).then((res) => {
          if (res) {
            this.processingRequired = res.value;
          }
        });
      },

      factorChange(e, row) {
        let obj = this.factoryList.find((el) => el.id === e);
        if (obj) {
          row.factoriesIdName = obj.name;
        }
        // factoriesIdName
      },
      // filterInput(value) {
      //   let aaa = value.replace(/[^a-zA-Z0-9]/g, '');
      //   console.log('cccaaaaaaaccc', aaa);
      // },
      changeRoutingList(row, index) {
        const obj = row.routingList?.find(
          (item) => item.id === row.produceRoutingId
        );
        if (obj) {
          row.produceRoutingName = obj.name;
        }
      },
      async getFactoryList() {
        this.factoryList = await getFactoryList();
      },
      open(row) {
        this.visible = true;
        if (row) {
          this.title = '修改订单';
          this.getDetail(row.code);
        } else {
          this.title = '创建订单';
          this.getSaleCode();
        }
      },
      getDetail(code) {
        getOrderDetail(code).then(async (res) => {
          console.log(res, 'res');
          if (res.productInfoList) {
            for (let item of res.productInfoList) {
              if (!item.bomCategoryId) {
                item.productType = '';
                item.selectionRowShow = true;
              } else {
                item.selectionRowShow = false;
              }
              if (item.productType) {
                item.productType = parseInt(item.productType);
              }
            }
          }
          if (res.productInfoList && res.productInfoList.length != 0) {
            res.productInfoList.forEach((item, index) => {
              if (item.colorKey && typeof item.colorKey == 'string') {
                this.$set(
                  res.productInfoList[index],
                  'colorKey',
                  item.colorKey.split(',')
                );
              }
              if (item.modelKey && typeof item.modelKey == 'string') {
                this.$set(
                  res.productInfoList[index],
                  'modelKey',
                  item.modelKey.split(',')
                );
              }
              item.lackNum = null;
              if(item.bomVersionList?.length&&item.productType){
                  item.bomVersionList=item.bomVersionList.filter(el=>el.bomType==item.productType)
              }
            });
          }
          // this.disabledList = res.productInfoList;
          if (res.productInfoList.length > 0) {
            const promiselist = [];
            res.productInfoList.forEach(async (el, index) => {
              promiselist.push(this.getBomInfo(el));
            });
            await Promise.all(promiselist);

            console.log(this.disabledList, '3333');
            // let ids = res.productInfoList.map((item) => item.categoryId);
            // const data = await findBomCategoryByCategoryIds(ids);
            // this.handleResult(res.productInfoList, data, 'init');
          }

          this.disabledList = res.productInfoList;
          this.form = res;
          const promiseProduct = [];
          this.form.productInfoList.forEach(async (el, index) => {
            let lis = el.producedList;
            if (!el.bomCategoryId && lis && lis.length > 0) {
              el.productType = el.producedList[0].code;
              promiseProduct.push(this.changeProductType(el, index));
            }
          });
          await Promise.all(promiseProduct);
          // // 如果没有bom版本的选择的话
        });
      },
      // 获取bom信息
      async getBomInfo(data) {
        let params = { categoryId: data.categoryId };
        const res = await listBomType(params);
        if (!res || res.length == 0) return;
        let bomMap = {
          1: { code: 1, name: 'PBOM' },
          2: { code: 2, name: 'MBOM' },
          3: { code: 3, name: 'ABOM' }
        };
        let arr = [];
        res.map((item) => {
          if (bomMap[item.bomType]) {
            arr.push(bomMap[item.bomType]);
            delete bomMap[item.bomType];
          }
        });
        console.log('什么时候进来');
        // this.$set(data, 'producedList', arr);
        data.producedList = arr;
        console.log(arr, 'arr');
      },

      cancel() {
        this.form = {
          salesmanId: '',
          salesman: '',
          productInfoList: [],
          deliveryRequirements: 1,
          saleType: 1,
          orderLibraryType: 2,
          deliveryTime: dayjs(
            new Date().getTime() + 3600 * 1000 * 24 * 10
          ).format('YYYY-MM-DD')
        };
        this.$refs.form.clearValidate();
        this.visible = false;
      },

      contactDialogSuccess(data) {
        this.$set(this.form, 'customerName', data.name);
        this.$set(this.form, 'simpleName', data.simpleName);
        this.$set(this.form, 'serialNo', data.serialNo);
        this.$set(this.form, 'simpleName', data.simpleName);
      },
      // 表格：模数、数量(方)、块数输入框 输入事件
      tableHandleKeyUp(row, index, e, name) {
        let modelArr = row.specification.split('*');
        let modelLong = modelArr[0]; // model规格长度
        let modeWide = modelArr[1]; // model规格宽度
        let modeHight = modelArr[2].substr(0, modelArr[2].indexOf('cm')); // model规格高度
        modeHight = Number(modeHight);
        if (name === 'moCount') {
          // 模数
          row.moCount = e;
          // 计算块数的公式：
          // (一模6米长度 / model规格长度) * (一模1.2米宽度 / model规格宽度) = 每一模的块数
          // 每一模的块数*模数moCount = 总块数
          if (row.productName.includes('板材')) {
            row.blockCount =
              Math.floor(600 / modelLong) *
              Math.floor(120 / modeHight) *
              Math.floor(60 / modeWide) *
              row.moCount;
          } else if (row.productName.includes('砌块')) {
            let modelLongFixed = (600 / modelLong).toFixed(2);
            modelLongFixed = modelLongFixed.substring(
              0,
              modelLongFixed.length - 1
            );
            let modeWideFixed = (120 / modeWide).toFixed(2);
            modeWideFixed = modeWideFixed.substring(
              0,
              modeWideFixed.length - 1
            );
            let modeHightFixed = (60 / modeHight).toFixed(2);
            modeHightFixed = modeHightFixed.substring(
              0,
              modeHightFixed.length - 1
            );
            row.blockCount =
              Math.floor(modelLongFixed * modeWideFixed * modeHightFixed) *
              row.moCount;
          }

          row.contractNum =
            ((modelLong * modeWide * modeHight) / 1000000).toFixed(5) *
            row.blockCount;
        } else if (name === 'sum') {
          //方数
          row.contractNum = e;

          row.blockCount = Math.floor(
            e / ((modelLong * modeWide * modeHight) / 1000000)
          );
          if (row.productName.includes('板材')) {
            row.moCount = Math.ceil(
              row.blockCount /
                (Math.floor(600 / modelLong) *
                  Math.floor(120 / modeHight) *
                  Math.floor(60 / modeWide))
            );
          } else if (row.productName.includes('砌块')) {
            row.moCount = Math.ceil(
              row.blockCount /
                Math.floor(
                  (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
                )
            );
          }
        } else if (name === 'blockCount') {
          //块数
          row.blockCount = e;

          if (row.productName.includes('板材')) {
            row.moCount = Math.ceil(
              row.blockCount /
                (Math.floor(600 / modelLong) *
                  Math.floor(120 / modeHight) *
                  Math.floor(60 / modeWide))
            );
          } else if (row.productName.includes('砌块')) {
            row.moCount = Math.ceil(
              row.blockCount /
                Math.floor(
                  (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
                )
            );
          }
          row.contractNum =
            (Number(e) * modelLong * modeWide * modeHight) / 1000000;
        }
        row.contractNum = Number(row.contractNum.toFixed(5));
      },

      // 删除产品
      handleDeleteItem(index) {
        this.form.productInfoList.splice(index, 1);
        this.changeLineNumber();
      },
      addEquipment() {
        this.$refs.equipmentRefs.open();
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }

          if (!this.form.productInfoList.length) {
            return this.$message.warning('产品列表不能为空！');
          }
          let flag = this.parameterVerification();
          // 必填参数校验
          if (!flag) return;
          console.log(this.form, '33333333333');
          this.loading = true;
          let params = {
            ...this.form,
            sourceType: this.isAdd ? 1 : 2
          };
          if (!this.isAdd) {
            params.sourceSalesOrderId = this.sourceSalesOrderId;
            params.productInfoList.forEach((el) => delete el.id);
          }
          params.productInfoList.forEach((item) => {
            item.colorKey = item.colorKey.toString();
            item.modelKey = item.modelKey.toString();
          });

          createOrUpdate(params)
            .then((res) => {
              this.loading = false;
              this.$message.success('成功');
              this.cancel();
              this.$emit('refresh');
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },
      // 参数校验
      parameterVerification() {
        let flag = true;
        for (let i = 0; i < this.form.productInfoList.length; i++) {
          let v = this.form.productInfoList[i];
          if (this.isRequired) {
            if (!v.productType) {
              flag = false;
              this.$message.warning('请选择生产类型');
              break;
            }

            if (!v.productType) {
              flag = false;
              this.$message.warning('请选择BOM版本');
              break;
            }
          }

          if (!v.contractNum) {
            flag = false;
            this.$message.warning('请输入订单数量且订单数量不能为0');
            break;
          }

          //contractNum

          if (!v.produceRoutingId) {
            flag = false;
            this.$message.warning('请选择工艺路线');
            break;
          }

          if (!v.factoriesId) {
            flag = false;
            this.$message.warning('请选择所属工厂');
            break;
          }
        }
        // this.form.productInfoList.forEach((v) => {
        //   if (this.isRequired) {
        //     if (!v.productType) {
        //       flag = false;
        //       this.$message.warning('请选择生产类型');
        //       return;
        //     }

        //     if (!v.productType) {
        //       flag = false;
        //       this.$message.warning('请选择BOM版本');
        //       return;
        //     }
        //   }

        //   if (!v.produceRoutingId) {
        //     flag = false;
        //     this.$message.warning('请选择工艺路线');
        //     return;
        //   }
        // });
        return flag;
      },
      // 选择订单类型
      chooseType(val) {
        if (val == 2) {
          this.$set(this.form, 'orderLibraryType', 1);
        } else {
          this.$set(this.form, 'orderLibraryType', 2);
        }
        this.$set(this.form, 'customerName', '');
      },

      async getSaleCode() {
        const res = await getCode('order_sale_code');
        if (res) {
          this.$set(this.form, 'code', res);
        }
      },
      // 确定选择
      async confirmChoose(list) {
        list.map((el) => (el.selectionRowShow = false));
        list = list
          .filter(
            (i) =>
              !this.disabledList.find(
                (p) => p.productCode == i.code || p.productCode == i.productCode
              )
          )
          .map((item, index) => {
            if (item.productCode) {
              return item;
            } else {
              return {
                categoryId: item.id,
                productCode: item.code,
                productName: item.name,
                productUnitWeight: item.netWeight,
                weightUnit: item.weightUnit,
                model: item.modelType,
                specification: item.specification,
                brandNo: item.brandNum,
                measuringUnit: item.measuringUnit
              };
            }
          })
          .concat(this.disabledList);
        // 取出在弹窗中选中并且不在表格中的数据
        const result = list.filter(
          (i) =>
            this.form.productInfoList.findIndex(
              (p) => p.productCode === i.productCode
            ) === -1
        );
        // 取出在表格中并且不在弹窗中选中的数据 即取消选中的数据
        const del = this.form.productInfoList.filter(
          (i) => list.findIndex((p) => p.productCode === i.productCode) === -1
        );
        for (let i = this.form.productInfoList.length - 1; i >= 0; i--) {
          for (let j in del) {
            if (
              this.form.productInfoList[i].productCode === del[j].productCode
            ) {
              this.form.productInfoList.splice(i, 1);
              break;
            }
          }
        }

        if (result.length > 0) {
          // let ids = result.map((item) => item.categoryId);
          // const res = await findBomCategoryByCategoryIds(ids);
          // let datas = JSON.parse(JSON.stringify(result));
          // console.log(datas, 'datas 00000');
          // datas = await this.handleResult(datas, res);
          let datas = JSON.parse(JSON.stringify(result));
          const promiselist = [];
          datas.forEach(async (el) => {
            promiselist.push(this.getBomInfo(el));
            this.getBomInfo(el);
          });
          await Promise.all(promiselist);
          this.form.productInfoList = this.form.productInfoList.concat(datas);
          const promiseProduct = [];
          this.form.productInfoList.forEach(async (el, index) => {
            let lis = el.producedList;
            if (!el.bomCategoryId && lis && lis.length > 0) {
              el.productType = el.producedList[0].code;
              promiseProduct.push(this.changeProductType(el, index));
            }
          });
          await Promise.all(promiseProduct);
        } else {
          this.form.productInfoList = this.form.productInfoList.concat(result);
        }
        this.changeLineNumber();
      },

      // 计算生产类型数据
      calculationType(data) {
        console.log(data, 'data 99955');
        let list = [];
        let listMap = {
          1: { code: 1, name: 'PBOM' },
          2: { code: 2, name: 'MBOM' },
          3: { code: 3, name: 'ABOM' }
        };
        data.forEach((el) => {
          if (listMap[el.bomType]) {
            list.push(listMap[el.bomType]);
            delete listMap[el.bomType];
          }
        });
        return list;
      },
      //
      async handleResult(result, res, type) {
        result.forEach((item) => {
          if (!res[item.categoryId]) {
            return;
          }
          let val = res[item.categoryId];
          if (!val || val.length == 0) {
            return;
          }
          let arr = [];
          let first = val[0];
          arr = val.filter((item) => item.bomType == first.bomType);
          if (!item.productType) {
            item.productType = first.bomType - 0;
          }
          console.log(arr, 'arr');
          let list = this.calculationType(val);
          item.producedList = list;
          if (!type) {
            item.bomVersionList = arr;
            // arr.map((el) => (el.bomCategoryId = el.id));
            item.bomCategoryId = arr[0].id;
          }

          // if (type) {
          //   let obj = item.bomVersionList.find(
          //     (el) => el.id == item.bomCategoryId
          //   );
          //   if (obj) return;
          //   this.changeBomId(item.bomVersionList[0],0)
          //   console.log(obj,'obj 11')
          // }
        });
        result.forEach(async (ele) => {
          ele = await this.getFindRoutingListByBomId(ele);
          console.log(ele, 'ele');
        });
        return result;
      },
      // 获取工艺路线
      async getFindRoutingListByBomId(ele) {
        let proArr = ele.bomVersionList;
        if (!proArr || proArr.length == 0) {
          return ele;
        }
        console.log(proArr, 'proArr');
        const res = await bomRoutingList(proArr[0].id);
        let arr = res || [];
        if (arr.length > 0) {
          this.$set(ele, 'routingList', arr);
          ele.produceRoutingName = arr[0].name;
          this.$set(ele, 'produceRoutingId', arr[0].id);
        }
        return ele;
      },
      // // await this.changeBomId(arr[0], 0);
      changeLineNumber() {
        this.form.productInfoList.map((item, index) => {
          item.lineNumber = 10 * (index + 1);
        });
      },

      inputNumber(row, index) {
        const pos = this.form.productInfoList;
        if (pos[index].productUnitWeight) {
          const number = multiply(row.contractNum, row.productUnitWeight);

          this.$set(pos[index], 'productWeight', number);
        }
        if (this.clientEnvironmentId == 4) {
          this.tableHandleKeyUp(row, '', row.contractNum, 'sum');
        }
      },

      getProcessRouteData(list, sourceSalesOrderId) {
        this.sourceSalesOrderId = sourceSalesOrderId;
        list.map(async (row, index) => {
          await this.changeBomId(row, index);
        });

        this.changeLineNumber();
      },

      // 清空BOM 跟工艺路线
      wipeData(index) {
        let row = this.form.productInfoList[index];
        row.bomCategoryId = '';
        row.routingList = [];
        row.bomVersionList = [];
        row.produceRoutingId = '';
        row.produceRoutingName = '';
        // row.produceVersionName = '';
        row.selectionRowShow = false;
        // this.selectionRowShow = false;
      },

      // 选择生产类型
      async changeProductType(row, index) {
        let param = {
          bomType: row.productType,
          categoryId: row.categoryId
        };
        this.wipeData(index);
        const res = await bomListByPlan(param);
        console.log(res, 'res 3333');
        let arr = res || [];
        let data = this.form.productInfoList[index];
        if (arr.length) {
          this.form.productInfoList[index].bomVersionList = arr;
          row.bomCategoryId = arr[0].id;
          await this.changeBomId(row, index);
          let arrAll = JSON.parse(JSON.stringify(this.form));
          this.$set(this, 'form', arrAll);
        }
        this.$forceUpdate();

        // let arr = res || [];
        // if (arr.length == 0) {
        //   row.bomCategoryId = '';
        // }

        // this.$set(this.form.productInfoList[index], 'bomVersionList', arr);
        // this.$forceUpdate();

        // console.log(this.form,'this.formthis.form')
      },

      // 选择BOM
      async changeBomId(row, index) {
        console.log(row, '这里看看吧');
        const res = await bomRoutingList(row.bomCategoryId);
        let arr = res || [];
        // if (arr.length == 0) {
        //   row.produceRoutingId = '';
        // }
        console.log(arr, 'arr');
        if (arr.length > 0) {
          this.$set(this.form.productInfoList[index], 'routingList', arr);
          row.produceRoutingName = arr[0].name;
          this.$set(
            this.form.productInfoList[index],
            'produceRoutingId',
            arr[0].id
          );
        }
        this.$forceUpdate();
      },

      homogeneityInspect(row) {
        if (!row.productType) {
          this.$message.warning('请选择生产类型');
          return;
        }
        if (!row.bomCategoryId) {
          this.$message.warning('请选择BOM版本');
          return;
        }
        if (!row.contractNum) {
          this.$message.warning('请输入订单数量且订单数量不能为0');
          return;
        }
        console.log(row, 'row');
        console.log(this.form, 'form +++');
        this.$refs.orderHomogeneityInspectDialog.open([row], this.form, 'new');
        // if (row.productType == 2) {
        //   let data = [];
        //   data.push(row);
        //   this.$refs.orderHomogeneityInspectDialog.open(data, this.form, 'new');
        // } else if (row.productType == 3) {
        //   this.$refs.orderHomogeneityInspectInstallDialog.open([row.id]);
        // } else {
        //   this.$message.warning('请确认生产类型！');
        // }
      },

      // 打开工艺路线
      openDialog(index) {
        this.selectIndex = index;
        this.$refs.processRouteRef.open();
      },

      // 选择工艺路线
      changeParent(item) {
        let data = this.form.productInfoList[this.selectIndex];
        this.$set(data, 'bomVersionList', []);
        this.$set(data, 'bomCategoryId', '');
        this.$set(data, 'model', '');
        this.$set(data, 'routingList', []);
        this.$set(data, 'productType', '');
        this.$set(data, 'produceRoutingName', item.name);
        this.$set(data, 'produceRoutingId', item.id);
        this.$set(data, 'selectionRowShow', true);
        // this.selectionRowShow = true;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .basic-details-title {
    margin: 10px 0;
  }

  .add-product {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 30px;
    color: #1890ff;
    margin: 10px 0;
    cursor: pointer;
  }

  .create-form .el-form-item {
    margin-bottom: 15px !important;
  }

  .header_required {
    .is-required:before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
    }
  }
</style>
