<!-- @desc:销售订单新建  @auth:付斌  @time:2024/02/20 15:15 -->
<template>

  <div class="main-div" style="position: relative;">
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData" style="width:100%">
          <!--订单单号-->
          <DkFormItem prop="orderNo">
            <InputPop ref="orderNo" v-model="formData.orderNo" :readonly="true"/>
          </DkFormItem>
          <!--客户电话-->
          <DkFormItem prop="cusPhone" :required="true">
            <SelectMagnifier v-model="formData.cusPhone" ref="cusPhone" :telephone="true"
                             primary-key="cusId" :input-read-only="false" :multiple="false"
                             :displayText="formData.cusPhone"
                             :type="this.$config.MagnifierType.customer"
                             :disabled="checkColumnIsEdit('cusPhone')"
                             @on-input-blur="selectCustomer"
                             @ok="selectCustomer"/>
          </DkFormItem>
          <!--客户名称-->
          <DkFormItem prop="cusName" :required="true">
            <InputPop ref="cusName" :readonly="checkColumnIsEdit('cusName')"
                      :disabled="checkColumnIsEdit('cusName')"
                      v-model="formData.cusName"/>
          </DkFormItem>
          <!--客户区域-->
          <DkFormItem prop="addressName" :required="true">
            <RegionsChoose v-model="addressArea" :options="cityData" :default-value="formData.addressName"
                           :readonly="checkColumnIsEdit('addressArea')" ref="customerDistrict"
                           :disabled="checkColumnIsEdit('addressName')"
                           @on-choose="chooseAddress"></RegionsChoose>
          </DkFormItem>
          <!--门牌号-->
          <DkFormItem prop="addressNo" :required="true">
            <InputPop ref="addressNo" :readonly="checkColumnIsEdit('addressNo')"
                      v-model="formData.addressNo"
                      :disabled="checkColumnIsEdit('addressNo')"
                      @input="setAddressFull"/>
          </DkFormItem>
          <!--详细地址-->
          <DkFormItem prop="addressFull" :required="true">
            <InputPop ref="addressFull" v-model="formData.addressFull"
                      :disabled="checkColumnIsEdit('addressFull')"/>
          </DkFormItem>
          <!--联系人-->
          <DkFormItem prop="contactName">
            <InputPop ref="contactName" :readonly="checkColumnIsEdit('contactName')"
                      v-model="formData.contactName" :disabled="checkColumnIsEdit('contactName')"/>
          </DkFormItem>
          <!--联系电话-->
          <DkFormItem prop="contactPhone">
            <InputPop :telephone="true" ref="contactPhone" :readonly="checkColumnIsEdit('contactPhone')"
                      v-model="formData.contactPhone" :disabled="checkColumnIsEdit('contactPhone')"/>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem prop="orgId" :required="true">
            <MultiSelect v-model="formData.orgList"
                         ref="org"
                         main-field="ownerFlag"
                         rate-field="allocationRatio"
                         :order-id="formData.orderId"
                         :default-value="formData.orgName"
                         @ok="orgOk($event)"
                         :type="this.$config.MagnifierType.org"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :required="true">
            <MultiSelect v-model="formData.staffList"
                         main-field="ownerFlag"
                         rate-field="allocationRatio"
                         :order-id="formData.orderId"
                         :default-value="formData.staffName"
                         @ok="staffOk($event)"
                         :type="this.$config.MagnifierType.staff"/>
          </DkFormItem>
          <!--客户来源-->
          <DkFormItem prop="cusFrom" :required="true">
            <SelectPop v-model="formData.cusFrom" ref="cusFrom" :multiple="false"
                       :options="cusFromList"
                       :disabled="checkColumnIsEdit('cusFrom')"
                       labelKey="dataValue"
                       valueKey=dataId>
            </SelectPop>
          </DkFormItem>
          <!--销售渠道-->
          <DkFormItem prop="salesChannel" :required="true">
            <SelectPop v-model="formData.salesChannel" ref="salesChannel"
                       :options="channelList"
                       :multiple="false"
                       :disabled="checkColumnIsEdit('salesChannel')"
                       labelKey="channelName"
                       valueKey="channelId">
            </SelectPop>
          </DkFormItem>
          <!--送货时间-->
          <DkFormItem prop="deliveryDate" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.deliveryDate"
                           :readonly="checkColumnIsEdit('deliveryDate')"
                           :short-cut-flag="true"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks">
            <InputPop ref="remarks" v-model="formData.remarks"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--商品信息-->
      <DkPanel prop="goodsInformation">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable ref="goodsTable" :data="formData.itemList" showFooter major-field="itemId"
                     :new-row-flag="true"
                     :add-flag="type === $config.formMode.add ? true : false"
                     :delete-flag="type === $config.formMode.add ? true : false"
                     :columns="this.type === this.$config.formMode.add ? addOrderItemColumns: editOrderItemColumns"
                     controlId="skuId" @on-choose="getTotals" @changeValue="getTotals"/>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5" name="dk-form"
                    class="form-content-class">
              <!--合计数量-->
              <DkFormItem prop="sumQuantity">
                <InputNumberPop ref="sumQuantity" v-model="goodsFootFormData.sumQuantity" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--货物金额-->
              <DkFormItem prop="sumAmount">
                <InputNumberPop ref="sumAmount" v-model="goodsFootFormData.sumAmount" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--标价总额-->
              <DkFormItem prop="sumStandard">
                <InputNumberPop ref="sumStandard" v-model="goodsFootFormData.sumStandard" :digits="2"
                                :readonly="true"/>
              </DkFormItem>
              <!--销售折扣-->
              <DkFormItem prop="saleDiscount">
                <InputNumberPop ref="saleDiscount" v-model="goodsFootFormData.saleDiscount" :digits="2"
                                :readonly="true" unit="%"/>
              </DkFormItem>
            </DkForm>
          </div>
        </div>
      </DkPanel>
      <!--客户收款-->
      <DkPanel prop="customerReceipt">
        <div id="search-cond-div-receipt-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable ref="receiptTable" :data="formData.receiptList" showFooter
                     major-field="rpId"
                     :new-row-flag="true"
                     :columns="receiptColumns"
                     controlId="macId" @on-choose="getTotals" @changeValue="getTotals"/>
        </div>
      </DkPanel>
      <!--附件-->
      <DkPanel prop="files">
        <div id="search-cond-div-files-info" ref="search-cond-div-files-info" slot="content">
          <DkPicWall v-model="formData.annexPaths" :table="$config.tables.order"
                     :accept="$config.uploadFileConfig.acceptPicType"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save(true)" @close="close"/>
  </div>
</template>

<script>
import {formMixin} from '@/mixins/form'

export default {
  components: {},
  mixins: [formMixin],
  data() {
    let self = this
    return {
      formData: {
        orderId: null,
        orderNo: null,
        cusId: null,
        cusName: null,
        cusPhone: null,
        contactName: null,
        contactPhone: null,
        customerDistrict: null,   // 客户区域
        addressArea: null,        // 行政区划
        addressGcj02: null,       // 经纬度
        addressName: null,        // 小区
        addressNo: null,          // 门牌号
        addressFull: null,        // 详细地址
        salesChannel: null,       //销售渠道
        cusFrom: null,            //客户来源
        deliveryDate: new Date().addDays(1),//送货时间
        annexPaths: null,
        remarks: null,
        itemList: [],
        deleteItemList: [],
        receiptList: [],
        staffList: [],    //存放从业务员id和分配百分比
        orgList: [],      //存放从业务部门id和分配百分比
        orderStatus: self.$config.orderStatus.done, //订单状态
        outStatus: self.$config.outStatus.daiChuKu,
        staffId: self.$store.state.user.id,
        staffName: self.$store.state.user.staffName,
        orgId: self.$store.state.user.orgId,
        orgName: self.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
      },
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
        sumStandard: 0,
        saleDiscount: 0,
      },
      //客户收款
      receiptFormData: {
        receiptAmt: 0, //应收金额金额
        remarks: null,
        annexPaths: null,
      },
      addressArea: [],
      cityData: [],
      channelList: [],
      cusFromList: [],
      canUseWhList: [],     // 可用仓库列表
      defaultWh: null,      // 默认仓库
      addOrderItemColumns: [
        {
          field: 'skuModel',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.goodsForOrder,
          fieldUpdate: self.$updateColumns.orderChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.goodsForOrder,
          fieldUpdate: self.$updateColumns.orderChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        //价格
        {
          field: 'priceSale',
          type: 'number',
          digits: 2,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            priceDiscount: ['priceSale/priceStd*100', 'priceSale', 'priceStd'],
          },
        },
        //数量
        {
          field: 'itemQty',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            amtStd: ['itemQty*priceStd', 'itemQty', 'priceStd'],
            priceDiscount: ['priceSale/priceStd*100', 'priceSale', 'priceStd'],
          },
        },
        // 仓库
        {
          field: 'whName',
          type: 'tableSelect',
          multiple: false,
          sortBoolean: false,
          dataType: self.$config.tableSelectType.warehouse,
          otherSearchParam: () => {
            return {
              skuId: self.currentRow?.skuId,
              nonStdCode: self.currentRow?.nonStdCode,
              orgId: self.formData.orgId,
            }
          },
          fieldUpdate: [
            {updateField: 'whId', valueFiled: 'whId'},
            {updateField: 'whName', valueFiled: 'whName'},
          ],
          searchDetailFlag: true
        },
        //金额
        {
          field: 'itemAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            priceSale: ['itemAmt/itemQty', 'itemAmt', 'itemQty'],
            priceDiscount: ['itemAmt/itemQty/priceStd*100', 'itemAmt', 'itemQty', 'priceStd'],
          },
        },
        //商品标价
        {
          field: 'priceStd',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //标价折扣
        {
          field: 'priceDiscount',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //非标号
        {
          field: 'nonStdCode', type: 'text', equal: true,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      editOrderItemColumns: [
        {
          field: 'skuModel',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.goods,
          fieldUpdate: self.$updateColumns.orderChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuName',
          controlId: 'skuId',
          type: 'tableSelect',
          width: 300,
          dataType: self.$config.tableSelectType.goods,
          fieldUpdate: self.$updateColumns.orderChooseGoods,
          searchDetailFlag: true
        },
        {
          field: 'skuCode',
          type: 'disabled',
        },
        //价格
        {
          field: 'priceSale',
          type: 'number',
          digits: 2,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            priceDiscount: ['priceSale/priceStd*100', 'priceSale', 'priceStd'],
          },
        },
        //数量
        {
          field: 'itemQty',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            amtStd: ['itemQty*priceStd', 'itemQty', 'priceStd'],
            priceDiscount: ['priceSale/priceStd*100', 'priceSale', 'priceStd'],
          },
        },
        // 仓库
        {
          field: 'whName',
          type: 'tableSelect',
          multiple: false,
          sortBoolean: false,
          dataType: self.$config.tableSelectType.warehouse,
          otherSearchParam: () => {
            return {
              skuId: self.currentRow?.skuId,
              nonStdCode: self.currentRow?.nonStdCode,
              orgId: self.formData.orgId,
            }
          },
          fieldUpdate: [
            {updateField: 'whId', valueFiled: 'whId'},
            {updateField: 'whName', valueFiled: 'whName'},
          ],
          searchDetailFlag: true
        },
        //金额
        {
          field: 'itemAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formula: {
            priceSale: ['itemAmt/itemQty', 'itemAmt', 'itemQty'],
            priceDiscount: ['itemAmt/itemQty/priceStd*100', 'itemAmt', 'itemQty', 'priceStd'],
          },
        },
        //商品标价
        {
          field: 'priceStd',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //标价折扣
        {
          field: 'priceDiscount',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //非标号
        {
          field: 'nonStdCode', type: 'text', equal: true,
        },
        //出库中数量
        {
          field: 'outingQty',
          type: 'disabled',
          number: true,
          digits: 0,
        },
        //已出库数量
        {
          field: 'outQty',
          type: 'disabled',
          number: true,
          digits: 0,
        },
        //退货数量
        {
          field: 'returnQty',
          type: 'disabled',
          number: true,
          digits: 0,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      receiptColumns: [
        {
          field: 'macName',
          controlId: 'macId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.moneyAccount,
          fieldUpdate: self.$updateColumns.receiptChooseMac,
          searchDetailFlag: true
        },
        //收款金额
        {
          field: 'amtRec',
          type: 'number',
          digits: 2,
          negative: () => self.negativeFlag,
          sum: true,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
    }
  },

  methods: {
    /**
     * @desc   : 加载数据
     * @author : 付斌
     * @date   : 2024-02-20 15:53
     */
    initData() {
      // 获取渠道
      this.getChannel();
      // 获取数据字典
      this.getDictionaryData();
      // 获取可用的仓库列表及默认仓库
      this.getCanUseWh();

      // 设置默认业务员业务部门
      this.formData.staffList = []
      let staff = {}
      staff.staffId = this.$store.state.user.staffId
      staff.staffCode = this.$store.state.user.staffCode
      staff.staffName = this.$store.state.user.staffName
      staff.allocationRatio = 100;
      staff.ownerFlag = true;
      this.formData.staffList.push(staff);

      this.formData.orgList = []
      let org = {}
      org.orgId = this.$store.state.user.orgId
      org.orgName = this.$store.state.user.orgName
      org.allocationRatio = 100;
      org.ownerFlag = true;
      this.formData.orgList.push(org);
    },
    /**
     * @desc   : 获取渠道
     * @author : 付斌
     * @date   : 2024-03-02 10:15
     */
    getChannel() {
      this.excute(this.$service.commonService, this.$service.commonService.getChannel, {}, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.channelList = res.data
        }
      })
    },
    /**
     * @desc   : 获取数据字典
     * @author : 付斌
     * @date   : 2024-03-02 11:15
     */
    getDictionaryData() {
      let params = {
        dictCode: this.$config.dictCode.cusFrom,
      }
      this.excute(this.$service.commonService, this.$service.commonService.getDictionaryData, params, false).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.cusFromList = res.data
        }
      })
    },
    /**
     *   @desc   : 业务部门OK
     *   @date   : 2022/5/28 10:43
     *   @author : 付斌
     */
    orgOk(rows) {
      if (rows && rows.length > 0) {
        this.formData.orgList = []
        for (let i of rows) {
          //找到主部门
          if (i.ownerFlag) {
            this.formData.orgId = i.orgId
            this.formData.orgCode = i.orgCode
            this.formData.orgName = i.orgName
            this.formData.allocationRatio = i.allocationRatio
            // 获取可用的仓库列表及默认仓库
            this.getCanUseWh(i.orgId);
          }
          //存放从部门id和分配比
          this.formData.orgList.push({
            orgId: i.orgId,
            orgCode: i.orgCode,
            orgName: i.orgName,
            allocationRatio: i.allocationRatio,
            ownerFlag: i.ownerFlag
          })
        }
      }
    },
    /**
     *   @desc   : 业务员OK
     *   @date   : 2022/5/28 10:43
     *   @author : 付斌
     */
    staffOk(rows) {
      if (rows && rows.length > 0) {
        this.formData.staffList = []
        for (let i of rows) {
          //找到主业务员
          if (i.ownerFlag) {
            this.formData.staffId = i.staffId
            this.formData.staffCode = i.staffCode
            this.formData.staffName = i.staffName
            this.formData.allocationRatio = i.allocationRatio

          }
          //存放从业务员id和分配比
          this.formData.staffList.push({
            staffId: i.staffId,
            staffCode: i.staffCode,
            staffName: i.staffName,
            allocationRatio: i.allocationRatio,
            ownerFlag: i.ownerFlag
          })
        }
      }
    },
    /**
     *   @desc   : 获取客户资料并且监听每一次的客户修改
     *   @date   : 2022/5/24 15:04
     *   @author : 付斌
     */
    selectCustomer(val) {
      if (val && val.length > 0) {
        this.formData.cusId = val[0].cusId
        this.formData.cusPhone = val[0].cusPhone
        this.formData.cusName = val[0].cusName
        this.formData.contactName = val[0].contactName
        this.formData.contactPhone = val[0].contactPhone

        // this.formData.orgId = val[0].orgId
        // this.formData.orgName = val[0].orgName
        // this.formData.staffId = val[0].staffId
        // this.formData.staffName = val[0].staffName
        this.formData.salesChannel = val[0].channelId
        this.formData.cusFrom = val[0].cusFrom

        this.formData.addressArea = val[0].addressArea
        this.formData.addressName = val[0].addressName
        this.formData.addressGcj02 = val[0].addressGcj02
        this.formData.addressFull = val[0].addressFull
        this.formData.addressNo = val[0].addressNo

        this.formData.customerDistrict = {
          "addressArea": val[0].addressArea,
          "addressName": val[0].addressName,
          "addressGcj02": val[0].addressGcj02,
          // 门牌号去掉
          "addressFull": val[0].addressFull.replace(val[0].addressNo, ""),
        }

        // var city = JSON.parse(val[0].addressArea.value).city
        // this.cityData.unshift({key: city, value: city})
      }
    },
    /**
     *   @desc   : 选择地址
     *   @date   : 2022/6/9 19:15
     *   @author : 付斌
     */
    chooseAddress(value) {
      this.formData.customerDistrict = value;
      // 说明是清空
      if (!value) {
        this.formData.addressName = null;
        this.formData.addressArea = {};
        this.formData.addressFull = null;
        this.formData.addressGcj02 = {};
      } else {
        //按照title进行
        this.formData.addressName = value.addressName;
        this.formData.addressArea = value.addressArea;
        this.formData.addressGcj02 = value.addressGcj02;
        this.formData.addressFull = value.addressFull + (this.formData.addressNo ? this.formData.addressNo : '');
      }
    }
    ,
    /**
     *   @desc   : 拼写详细地址
     *   @date   : 2022/6/9 10:08
     *   @author : 付斌
     */
    setAddressFull(e) {
      // 客户区域有值才会拼接详细地址
      if (this.formData.customerDistrict && this.formData.customerDistrict.addressFull) {
        this.formData.addressFull = this.formData.customerDistrict.addressFull + (this.formData.addressNo ? this.formData.addressNo : '')
      }
    },
    /**
     * @desc   : 清空客户信息
     * @author : 付斌
     * @date   : 2024-02-27 10:36
     */
    clearCutomer() {
      this.formData.customerDistrict = null;
      this.formData.cusId = null
      this.formData.cusCode = null
      this.formData.cusName = null
      this.formData.contactName = null
      this.formData.contactPhone = null
      this.formData.addressArea = {}
      //新增选择省市区也顺带清空了
      this.addressArea = []
      this.formData.addressName = null
      this.formData.addressNo = null
      this.formData.latitude = null
      this.formData.longitude = null
      this.formData.cusFrom = null;

      // 清空客户区域
      if (this.$refs.customerDistrict) {
        this.$refs.customerDistrict.clear();
      }
      this.formData.addressFull = null;
    },
    /**
     *   @desc   : 获取商品表格中数量、金额后计算总单信息
     *   @date   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals(field, row, rowIndex) {
      let table = this.$refs['goodsTable'].tableData
      let sumQuantity = 0;  // 合计数量
      let sumAmount = 0;    // 货物金额
      let sumStandard = 0;  // 标价总额
      if (table && table.length > 0) {
        table.forEach(row => {
          if (!row["itemQty"] || row["itemQty"] == '') {
            this.$set(row, 'itemQty', 0);
          }
          if (!row["itemAmt"] || row["itemQty"] == '') {
            this.$set(row, 'itemAmt', 0);
          }
          sumQuantity += parseFloat(row["itemQty"]);
          sumAmount += parseFloat(row["itemAmt"]);
          this.$set(row, 'amtStd', parseFloat(row["itemQty"]) * parseFloat(row["priceStd"]));
          sumStandard += parseFloat(row["amtStd"]);

          if (!row["whId"] || row["whId"] == '') {
            this.$set(row, 'whId', this.defaultWh.whId);
            this.$set(row, 'whName', this.defaultWh.whName);
          }
        })
      }
      this.goodsFootFormData.sumQuantity = sumQuantity;
      this.goodsFootFormData.sumAmount = sumAmount;
      this.goodsFootFormData.sumStandard = sumStandard;
      this.goodsFootFormData.saleDiscount = (sumAmount / sumStandard * 100).toFixed(2);
    },
    /**
     * @desc   : 通过id查询
     * @author : 付斌
     * @date   : 2022/03/04 13:17
     */
    detail(id) {
      return this.excuteNoParam(this.$service.orderService, this.$service.orderService.getOrderForUpdate, [id]);
    },
    /**
     * @desc   : 编辑页面赋值
     * @author : 付斌
     * @date   : 2024-03-03 9:33
     */
    setValuesByEdit(data) {
      if (data) {
        this.formData = data["data"];
        this.formData.itemList = data["dataItem"];
        this.formData.receiptList = data["receiptItem"];

        this.goodsFootFormData.sumQuantity = this.formData.sumQuantity;
        this.goodsFootFormData.sumAmount = this.formData.sumAmount;
        this.goodsFootFormData.sumStandard = this.formData.sumStandard;
        this.goodsFootFormData.saleDiscount = this.formData.saleDiscount;
      }
    },
    /**
     * @desc   : 校验数据
     * @author : 付斌
     * @date   : 2024-03-11 14:37
     */
    validData() {
      if (this.formData.staffList.length == 0) {
        this.$message.error(this.$t('W_061', {'param': this.$t('staffId')}))
        return false;
      }
      if (this.formData.orgList.length == 0) {
        this.$message.error(this.$t('W_061', {'param': this.$t('orgId')}))
        return false;
      }
      //业务部门中没有主业务部门
      if (this.formData.orgList && this.formData.orgList.length > 0) {
        var list = this.formData.orgList.filter(it => it.ownerFlag);
        if (list.length == 0) {
          this.$message.error(this.$t('W_099'))
          return false;
        }
      }
      //业务员中没有主业务员
      if (this.formData.staffList && this.formData.staffList.length > 0) {
        var list = this.formData.staffList.filter(it => it.ownerFlag);
        if (list.length == 0) {
          this.$message.error(this.$t('W_100'))
          return false;
        }
      }

      let itemTable = this.$refs['goodsTable'].getTableDataFilter();
      if (!itemTable || itemTable.length == 0) {
        this.$Message.warning(this.$t('W_012'))
        return false;
      }
      for (let it of itemTable) {
        if (!it.itemQty || it.itemQty === '' || it.itemQty === 0) {
          this.$Message.warning(this.$t('W_042', {'param': '明细数量不能'}))
          return false;
        }
      }
      return true;
    },
    /**
     * @desc   : 给参数赋值
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    setParams(arg) {
      if (this.type === this.$config.formMode.edit) {
        // 删除的表数据
        let deleteItemTable = this.$refs['goodsTable'].getDeleteData();
        this.formData.deleteItemList = deleteItemTable
      }
      // 修改新增的表数据
      let itemTable = this.$refs['goodsTable'].getTableDataFilter();
      itemTable.forEach((it, index) => {
        if (!it.nonStdCode || it.nonStdCode === '') {
          this.$set(it, 'nonStdCode', '-');
        }
      });
      this.formData.itemList = itemTable;
      this.formData.receiptList = this.$refs['receiptTable'].getTableDataFilter();
      Object.assign(this.params, this.formData, this.goodsFootFormData)
      this.params.deliveryDate = new Date(this.formData.deliveryDate).toDateStr();
    },
    /**
     * @desc   : 保存数据
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    saveData() {
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.orderService, this.$service.orderService.insert, this.params);
      } else if (this.type === this.$config.formMode.edit) {
        return this.excute(this.$service.orderService, this.$service.orderService.update, this.params)
      }
    },
    /**
     * @desc   :新建完毕后清空窗体
     * @author : 付斌
     * @date   : 2024-02-27 10:33
     */
    clear() {
      let self = this
      this.formData = {
        orderId: null,
        orderNo: null,
        cusId: null,
        cusName: null,
        cusPhone: null,
        contactName: null,
        contactPhone: null,
        customerDistrict: null,   // 客户区域
        addressArea: null,        // 行政区划
        addressGcj02: null,       // 经纬度
        addressName: null,        // 小区
        addressNo: null,          // 门牌号
        addressFull: null,        // 详细地址
        salesChannel: null,       //销售渠道
        cusFrom: null,            //客户来源
        deliveryDate: new Date().addDays(1),//送货时间
        annexPaths: null,
        remarks: null,
        itemList: [],
        deleteItemList: [],
        receiptList: [],
        staffList: [],    //存放从业务员id和分配百分比
        orgList: [],      //存放从业务部门id和分配百分比
        orderStatus: self.$config.orderStatus.done, //订单状态
        outStatus: self.$config.outStatus.daiChuKu,
        staffId: self.$store.state.user.id,
        staffName: self.$store.state.user.staffName,
        orgId: self.$store.state.user.orgId,
        orgName: self.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
      }

      // 设置默认业务员业务部门
      this.formData.staffList = []
      let staff = {}
      staff.staffId = this.$store.state.user.staffId
      staff.staffCode = this.$store.state.user.staffCode
      staff.staffName = this.$store.state.user.staffName
      staff.allocationRatio = 100;
      staff.ownerFlag = true;
      this.formData.staffList.push(staff);

      this.formData.orgList = []
      let org = {}
      org.orgId = this.$store.state.user.orgId
      org.orgName = this.$store.state.user.orgName
      org.allocationRatio = 100;
      org.ownerFlag = true;
      this.formData.orgList.push(org);

      // 清空客户区域
      if (this.$refs.customerDistrict) {
        this.$refs.customerDistrict.clear();
      }
    },
    /**
     * @desc   : 判断列是否可以编辑
     * @author : 付斌
     * @date   : 2022/6/21 16:42
     */
    checkColumnIsEdit(field) {
      if (this.type === this.$config.formMode.edit) {
        return true;
      }
    },

    // region 私有方法
    /**
     * @desc   : 获取可用的仓库列表及默认仓库
     * @author : 付斌
     * @date   : 2024-03-02 11:15
     */
    getCanUseWh(orgId) {
      if (!orgId) {
        orgId = this.$store.state.user.orgId
      }
      let params = {orgId: orgId}
      this.excute(this.$service.commonService, this.$service.commonService.getOrgWh, params, false).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.canUseWhList = [...res.data]
            let list = res.data.filter(it => it.flgDefault)
            if (list.length > 0) {
              this.defaultWh = list[0]
              // 设置默认仓库
              this.setDefaultWh()
            } else {
              this.excute(this.$service.commonService, this.$service.commonService.getWarehouse, {}, false).then(res => {
                if (res.code === this.$config.SUCCESS_CODE) {
                  this.canUseWhList = [...res.data]
                  let list = res.data.filter(it => it.flgDefault)
                  if (list.length > 0) {
                    this.defaultWh = list[0]
                    // 设置默认仓库
                    this.setDefaultWh()
                  }
                }
              })
            }
          }
        }
      )
    },
    /**
     * @desc   : 设置默认仓库
     * @author : 付斌
     * @date   : 2024-04-11 13:56
     */
    setDefaultWh() {
      let table = this.$refs['goodsTable'].tableData
      if (table && table.length > 0) {
        table.forEach(row => {
          if (row.skuId) {
            if (row.whId) {
              let list2 = this.canUseWhList.filter(it => it.whId === row.whId)
              if (list2.length == 0) {
                this.$set(row, 'whId', this.defaultWh.whId);
                this.$set(row, 'whName', this.defaultWh.whName);
              }
            } else {
              this.$set(row, 'whId', this.defaultWh.whId);
              this.$set(row, 'whName', this.defaultWh.whName);
            }
          }
        })
      }
    },
    // endregion 私有方法
  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 付斌
   * @date   : 2022/3/3 10:32
   */
  created() {
    console.log('this.$route', this.$route)
    console.log('this.$store.state.user', this.$store.state.user)

    this.focusItem = 'orderId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'orderId'  // 设置主键Id
  }
}
</script>
