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

  <div class="main-div">
    <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="outboundProcessingFlag"  v-if="formData.flgAutoHandle">
            <DkSwitch prop="outboundProcessingFlag" v-model="formData.outboundProcessingFlag" :readonly="type === $config.formMode.edit" ref="outboundProcessingFlag"></DkSwitch>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks" :span="18">
            <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">
          <DkTabs v-model="detailModel" :options="detailOptions" @on-click="detailTabsClick"></DkTabs>
          <!--普通商品-->
          <div v-show="ordinaryGoodsFlag">
          <EditTable ref="goodsTable" :data="formData.itemList" showFooter major-field="itemId"
                     :new-row-flag="true"
                     :delete-flag="canBigEditFlag"
                     :columns="this.type === this.$config.formMode.add ? addOrderItemColumns: editOrderItemColumns"
                     @changeNonStandard="changeNonStandard"
                     controlId="skuId"
                     @on-choose="getTotals"
                     @changeValue="getTotals"
                     @delRow='delRow'/>
          </div>
          <!--外协商品-->
          <div v-show="outsourcedGoodsFlag">
            <EditTable ref="outsourcedGoodsTable" :data="formData.outsourcedItemList" showFooter major-field="itemId"
                       :new-row-flag="true"
                       :delete-flag="canBigEditFlag"
                       :columns="this.type === this.$config.formMode.add ? addOutsourcedItemColumns: editOutsourcedItemColumns"
                       controlId="supId"
                       @on-choose="getTotalsOutsourced"
                       @changeValue="getTotalsOutsourced"
                       @delRow='delRowOutsourced'/>
          </div>
          <!--底部总单合计-->
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5" name="dk-form"
                    class="read-only-form">
              <!--合计数量-->
              <DkFormItem prop="sumQuantity">
                <InputNumberPop ref="sumQuantity" v-model="goodsFootFormData.sumQuantity" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--合计金额-->
              <DkFormItem prop="sumAmount" class="amount">
                <InputNumberPop ref="sumAmount" v-model="goodsFootFormData.sumAmount" :clearable="false"
                                :digits="2" :readonly="true"/>
              </DkFormItem>
              <!--实收金额-->
              <DkFormItem prop="factAmt" class="amount" :label="$t('totalFactAmt')">
                <InputNumberPop ref="factAmt" v-model="goodsFootFormData.factAmt" :digits="2" :clearableFlag="false"
                                :readonly="updateTotalFootMessageFlag"
                                @on-blur="(val)=>changeDiscountOrAmount(val, 1)"/>
              </DkFormItem>
              <!--折扣-->
              <DkFormItem prop="discount" class="amount">
                <InputNumberPop ref="discount" v-model="goodsFootFormData.discount" :digits="0" :clearableFlag="false"
                                :readonly="updateTotalFootMessageFlag" unit="%"
                                @on-blur="(val)=>changeDiscountOrAmount(val, 2)"/>
              </DkFormItem>
              <!--优惠金额-->
              <DkFormItem prop="discAmt"  class="amount">
                <InputNumberPop ref="discAmt" v-model="goodsFootFormData.discAmt" :digits="2" :clearableFlag="false"
                                :readonly="updateTotalFootMessageFlag"
                                @on-blur="(val)=>changeDiscountOrAmount(val, 3)"/>
              </DkFormItem>
              <!--标价总额-->
              <DkFormItem prop="sumStandard" class="amount">
                <InputNumberPop ref="sumStandard" v-model="goodsFootFormData.sumStandard" :digits="2"
                                :readonly="true"/>
              </DkFormItem>
              <!--销售折扣-->
              <DkFormItem prop="saleDiscount" class="amount">
                <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 {
      detailModel: 'ordinaryGoods',
      detailOptions: [
        {label: self.$t('ordinaryGoods'), name: 'ordinaryGoods'}, //普通商品
        {label: self.$t('outsourcedGoods'), name: 'outsourcedGoods'},//外协商品
      ],
      ordinaryGoodsFlag: true,//普通商品标识
      outsourcedGoodsFlag: false,//外协商品标识
      //小数位数
      decimalPlaces:0,
      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,
        outsourcedItemList:[],//外协明细
        outboundProcessingFlag:true,//开单并出库办理
        flgAutoHandle : self.$store.state.user.setting[self.$config.settingCode.IVT001] ? true : false ,//自动办理标识
        flgHandleSetting: self.$store.state.user.setting[self.$config.settingCode.IVT002] ? true : false,//欠货出库标识
      },
      //商品合计信息
      goodsFootFormData: {
        sumQuantity: 0,
        sumAmount: 0,
        sumStandard: 0,
        saleDiscount: 0,
        discount: 0,//整单折扣
        factAmt: 0,//实收金额
        discAmt: 0,//总单优惠
      },
      oldSumFactAmt: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: 'itemQty',
          type: 'number',
          digits: this.decimalPlaces,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            amtStd: ['itemQty*priceStd', 'itemQty', 'priceStd'],
            box: ['itemQty/packBox', 'itemQty', 'packBox'],
            piece: ['itemQty%packBox', 'itemQty', 'packBox'],
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            discount: ['(factPrice / priceSale) * 100 ', 'factPrice', 'priceSale'],
          },
        }, //数量
        {
          field: 'priceSale',
          type: 'disabled',
          number: true,
          digits: 2,
        }, //售价
        {
          field: 'itemAmt',
          type: 'disabled',
          digits: 2,
          number: true,
          sum: true,
        }, //售价金额
        {
          field: 'factPrice',
          type: 'number',
          digits: 2,
          formula: {
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            //标价折扣 =  售价 / 标价 * 100
            priceDiscount: ['factPrice/priceStd*100', 'factPrice', 'priceStd'],
            //折扣 = 实际单价/ 售价 *100
            discount: ['factPrice / priceSale * 100 ', 'factPrice', 'priceSale'],
          },
        },//优惠后单价
        {
          field: 'factAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //实际单价 =  金额 / 数量
            factPrice: ['factAmt / itemQty  ', 'priceSale', 'discount'],
            //折扣 = 实际金额 / 金额
            discount: ['factAmt /  itemAmt * 100 ', 'factAmt', 'itemAmt'],
          },
        },//优惠后金额
        {
          field: 'discount',
          type: 'number',
          number: true,
          digits: 0,
          formulaLate: true,
          formula: {
            //实际单价 =  售价 * 折扣 / 100 - 优惠金额
            factPrice: ['priceSale * discount /100 ', 'priceSale', 'discount'],
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty * factPrice', 'itemQty', 'factPrice'],
          },
        },//折扣
        //商品标价
        {
          field: 'priceStd',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //标价折扣
        {
          field: 'priceDiscount',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        // //包装
        // {
        //   field: 'packBox',
        //   type: 'disabled',
        // },
        //基本单位
        {
          field: 'unitName',
          title: self.$t('piece'),
          type: 'disabled',
        },
        // //箱
        // {
        //   field: 'box',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox', 'box', 'packBox'],
        //     amtStd: ['box*packBox*priceStd', 'priceStd', 'box', 'packBox'],
        //   },
        // },
        // //片
        // {
        //   field: 'piece',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox+piece', 'piece','box','packBox'],
        //     box: ['(box*packBox+piece)/packBox', 'piece', 'box' , 'packBox','packBox'],
        //     piece: ['(box*packBox+piece)%packBox', 'piece','box', 'packBox', 'packBox'],
        //     amtStd: ['(box*packBox+piece)*priceStd', 'piece','box', 'packBox', 'priceStd'],
        //   },
        // },
        {
          field: 'unitInfo',
          type: 'nonStandard',
        },
        // 仓库
        {
          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: '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: 'primaryQty',
          type: 'disabled',
        }, //可编辑数量
        {
          field: 'itemQty',
          type: 'number',
          digits: this.decimalPlaces,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            amtStd: ['itemQty*priceStd', 'itemQty', 'priceStd'],
            box: ['itemQty/packBox', 'itemQty', 'packBox'],
            piece: ['itemQty%packBox', 'itemQty', 'packBox'],
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            discount: ['(factPrice / priceSale) * 100 ', 'factPrice', 'priceSale'],
          },
        }, //数量
        {
          field: 'priceSale',
          type: 'disabled',
          number: true,
          digits: 2,
        }, //售价
        {
          field: 'itemAmt',
          type: 'disabled',
          digits: 2,
          number: true,
          sum: true,
        }, //售价金额
        {
          field: 'factPrice',
          type: 'number',
          digits: 2,
          formula: {
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            //标价折扣 =  售价 / 标价 * 100
            priceDiscount: ['factPrice/priceStd*100', 'factPrice', 'priceStd'],
            //折扣 = 实际单价/ 售价 *100
            discount: ['factPrice / priceSale * 100 ', 'factPrice', 'priceSale'],
          },
        },//优惠后单价
        {
          field: 'factAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //实际单价 =  金额 / 数量
            factPrice: ['factAmt / itemQty  ', 'priceSale', 'discount'],
            //折扣 = 实际金额 / 金额
            discount: ['factAmt /  itemAmt * 100 ', 'factAmt', 'itemAmt'],
          },
        },//优惠后金额.
        {
          field: 'discount',
          type: 'number',
          number: true,
          digits: 0,
          formulaLate: true,
          formula: {
            //实际单价 =  售价 * 折扣 / 100 - 优惠金额
            factPrice: ['priceSale * discount /100 ', 'priceSale', 'discount'],
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty * factPrice', 'itemQty', 'factPrice'],
          },
        },//折扣
        //商品标价
        {
          field: 'priceStd',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        //标价折扣
        {
          field: 'priceDiscount',
          type: 'disabled',
          number: true,
          digits: 2,
        },
        // //包装
        // {
        //   field: 'packBox',
        //   type: 'disabled',
        // },
        //基本单位
        {
          field: 'unitName',
          title: self.$t('piece'),
          type: 'disabled',
        },
        // //箱
        // {
        //   field: 'box',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox', 'box', 'packBox'],
        //     amtStd: ['box*packBox*priceStd', 'priceStd', 'box', 'packBox'],
        //   },
        // },
        // //片
        // {
        //   field: 'piece',
        //   type: 'number',
        //   digits: 0,
        //   sum: true,
        //   formula: {
        //     itemQty: ['box*packBox+piece', 'piece','box','packBox'],
        //     box: ['(box*packBox+piece)/packBox', 'piece', 'box' , 'packBox','packBox'],
        //     piece: ['(box*packBox+piece)%packBox', 'piece','box', 'packBox', 'packBox'],
        //     amtStd: ['(box*packBox+piece)*priceStd', 'piece','box', 'packBox', 'priceStd'],
        //   },
        // },
        {
          field: 'unitInfo',
          title: self.$t('boxPiece'),
          type: 'nonStandard',
        },
        // 仓库
        {
          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: '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,
        },
      ],
      addOutsourcedItemColumns:[
        {
          field: 'supName',
          controlId: 'supId',
          type: 'tableSelect',
          multiple:false,
          title:this.$t('supplierName'),
          otherSearchParam: () => {
            return {
              supplierType: self.$config.kindCode.supplierOutsourced,
            }
          },
          width: 200,
          dataType: self.$config.tableSelectType.supplier,
          fieldUpdate: self.$updateColumns.saleOrderChooseSupplier,
          searchDetailFlag: true
        },
        {
          field: 'skuModel',
          type: 'text',
          width: 200,
        },
        {
          field: 'skuName',
          type: 'text',
          width: 200,
        },
        {
          field: 'itemQty',
          type: 'number',
          digits: this.decimalPlaces,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            discount: ['(factPrice / priceSale) * 100 ', 'factPrice', 'priceSale'],
          },
        }, //数量
        {
          field: 'costPrice',
          title:this.$t('costPriceSaleOrder'),
          type: 'number',
          number: true,
          digits: 2,
        }, //成本单价
        {
          field: 'priceSale',
          type: 'number',
          number: true,
          digits: 2,
          formulaLate: true,
          formula: {
            //售价 =  金额 *  数量
            itemAmt: ['priceSale * itemQty  ', 'priceSale', 'itemQty'],
          },
        }, //售价
        {
          field: 'itemAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //售价 =  金额 /  数量
            priceSale: ['itemAmt / itemQty  ', 'itemAmt', 'itemQty'],
          },
        }, //实际金额
        {
          field: 'factPrice',
          type: 'number',
          digits: 2,
          formula: {
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            //标价折扣 =  售价 / 标价 * 100
            priceDiscount: ['factPrice/priceStd*100', 'factPrice', 'priceStd'],
            //折扣 = 实际单价/ 售价 *100
            discount: ['factPrice / priceSale * 100 ', 'factPrice', 'priceSale'],
          },
        },//优惠后单价
        {
          field: 'factAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //实际单价 =  金额 / 数量
            factPrice: ['factAmt / itemQty  ', 'priceSale', 'discount'],
            //折扣 = 实际金额 / 金额
            discount: ['factAmt /  itemAmt * 100 ', 'factAmt', 'itemAmt'],
          },
        },//优惠后金额.
        {
          field: 'discount',
          type: 'number',
          number: true,
          digits: 0,
          formulaLate: true,
          formula: {
            //实际单价 =  售价 * 折扣 / 100 - 优惠金额
            factPrice: ['priceSale * discount /100 ', 'priceSale', 'discount'],
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty * factPrice', 'itemQty', 'factPrice'],
          },
        },//折扣
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      editOutsourcedItemColumns:[
        {
          field: 'supName',
          controlId: 'supId',
          type: 'tableSelect',
          multiple:false,
          title:this.$t('supplierName'),
          otherSearchParam: () => {
            return {
              supplierType: self.$config.kindCode.supplierOutsourced,
            }
          },
          width: 200,
          dataType: self.$config.tableSelectType.supplier,
          fieldUpdate: self.$updateColumns.saleOrderChooseSupplier,
          searchDetailFlag: true
        },
        {
          field: 'skuModel',
          type: 'text',
          width: 200,
        },
        {
          field: 'skuName',
          type: 'text',
          width: 200,
        },
        {
          field: 'primaryQty',
          type: 'disabled',
        }, //可编辑数量
        {
          field: 'itemQty',
          type: 'number',
          digits: this.decimalPlaces,
          sum: true,
          formula: {
            itemAmt: ['itemQty*priceSale', 'itemQty', 'priceSale'],
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            discount: ['(factPrice / priceSale) * 100 ', 'factPrice', 'priceSale'],
          },
        }, //数量
        {
          field: 'costPrice',
          title:this.$t('costPriceSaleOrder'),
          type: 'number',
          number: true,
          digits: 2,
        }, //成本单价
        {
          field: 'priceSale',
          type: 'number',
          number: true,
          digits: 2,
          formulaLate: true,
          formula: {
            //售价 =  金额 *  数量
            itemAmt: ['priceSale * itemQty  ', 'priceSale', 'itemQty'],
          },
        }, //售价
        {
          field: 'itemAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //售价 =  金额 /  数量
            priceSale: ['itemAmt / itemQty  ', 'itemAmt', 'itemQty'],
          },
        }, //实际金额
        {
          field: 'factPrice',
          type: 'number',
          digits: 2,
          formula: {
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty*factPrice', 'itemQty', 'factPrice'],
            //标价折扣 =  售价 / 标价 * 100
            priceDiscount: ['factPrice/priceStd*100', 'factPrice', 'priceStd'],
            //折扣 = 实际单价/ 售价 *100
            discount: ['factPrice / priceSale * 100 ', 'factPrice', 'priceSale'],
          },
        },//优惠后单价
        {
          field: 'factAmt',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formulaLate: true,
          formula: {
            //实际单价 =  金额 / 数量
            factPrice: ['factAmt / itemQty  ', 'priceSale', 'discount'],
            //折扣 = 实际金额 / 金额
            discount: ['factAmt /  itemAmt * 100 ', 'factAmt', 'itemAmt'],
          },
        },//优惠后金额.
        {
          field: 'discount',
          type: 'number',
          number: true,
          digits: 0,
          formulaLate: true,
          formula: {
            //实际单价 =  售价 * 折扣 / 100 - 优惠金额
            factPrice: ['priceSale * discount /100 ', 'priceSale', 'discount'],
            //实际金额 =  数量 *  实际金额
            factAmt: ['itemQty * factPrice', 'itemQty', 'factPrice'],
          },
        },//折扣
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      updateTotalFootMessageFlag:false,
      canBigEditFlag:true,//可以大编辑标识
    }
  },

  methods: {
    /**
     *   @desc   : 点击Tab进行切换
     *   @date   : 2024/6/18 10:27
     *   @author : 寇珊珊
     */
    detailTabsClick(val) {
      //普通商品
      if (val === 'ordinaryGoods') {
        //普通商品标识
        this.ordinaryGoodsFlag = true
        //外协商品标识
        this.outsourcedGoodsFlag = false
      }
      //外协商品
      else if (val === 'outsourcedGoods') {
        //普通商品标识
        this.ordinaryGoodsFlag = false
        //外协商品标识
        this.outsourcedGoodsFlag = true
      }
    },
    /**
     * @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   : 修改包装数
     * @author : 周兴
     * @date   : 2024/5/24 15:02
     */
    changeNonStandard({row,rowIndex,field}){
      let table = this.$refs['goodsTable'].tableData
      table[rowIndex][field] = (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0)
        + row['subUnitName']
        +(row['nonStandardForm']['piece'] == 0 || row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:'')
        +(row['unitName']?(row['nonStandardForm']['piece']?row['unitName']:''):'')
      table[rowIndex]['itemQty'] = row['packBox'] * (row['nonStandardForm']['box']?row['nonStandardForm']['box']:0) + (row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0)
      table[rowIndex]['itemAmt'] = table[rowIndex]['itemQty'] * table[rowIndex]['priceSale']
      table[rowIndex]['factAmt'] = table[rowIndex]['itemQty'] * table[rowIndex]['factPrice']
      table[rowIndex]['box'] = row['nonStandardForm']['box']?row['nonStandardForm']['box']:0
      table[rowIndex]['piece'] = row['nonStandardForm']['piece'] ?row['nonStandardForm']['piece']:0
      this.getTotale(table)
    },
    /**
     *   @desc   : 获取商品表格中数量、金额后计算总单信息
     *   @date   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals(field, row, rowIndex) {
      let table = this.$refs['goodsTable'].tableData.filter(it=>it.skuId)
      if (table && table.length > 0) {
        //计算合计
        this.getTotale()
        table.forEach(row => {
          //数量
          if (!row["itemQty"] || row["itemQty"] == '') {
            this.$set(row, 'itemQty', 0);
          }
          //金额
          if (!row["itemAmt"] || row["itemQty"] == '') {
            this.$set(row, 'itemAmt', 0);
          }
          //实际金额
          if (!row["factAmt"] || row["itemQty"] == '') {
            this.$set(row, 'factAmt', 0);
          }
          //折扣
          if (!row["discount"] || row["discount"] == '') {
            this.$set(row, 'discount', 0);
          }

          this.decimalPlaces = row['decimalPlaces']

          if(row['subUnitId']){
            row.nonStandardForm = {
              formula: (row['subUnitName']?'1'+row['subUnitName']+ '=':'' ) + row['packBox'] + row['unitName'],
              box:(row['itemQty']/row['packBox'] >= 1 ? Math.floor(row['itemQty']/row['packBox']):0),
              piece:row['itemQty']%row['packBox'],
            }
            row.nonStandardItems = [
              {code:'formula',label:'计算公式',type:'text',readonly:true},
              {code:'box',label:row['subUnitName'],type:'number' },
              {code:'piece',label:row['unitName'],type:'number',digits:this.decimalPlaces}
            ]
            row['unitInfo'] = (row['itemQty']/row['packBox'] >= 1 ? Math.floor(row['itemQty']/row['packBox']):0) + row['subUnitName'] + (row['itemQty']%row['packBox']).toFixed(this.decimalPlaces) + row['unitName']
          }else{
            row.nonStandardForm = {
              formula: (row['subUnitName']?'1'+row['subUnitName']+ '=':'' ) + row['packBox'] + row['unitName'],
              piece:row['itemQty'],
            }
            row.nonStandardItems = [
              {code:'formula',label:'计算公式',type:'text',readonly:true},
              {code:'piece',label:row['unitName'],type:'number',digits: this.decimalPlaces}
            ]
            row['unitInfo'] = row['itemQty'] + row['unitName']
          }
          row['box'] = row['nonStandardForm']['box']
          row['piece'] = row['nonStandardForm']['piece']
          if (!row["whId"] || row["whId"] == '') {
            this.$set(row, 'whId', this.defaultWh.whId);
            this.$set(row, 'whName', this.defaultWh.whName);
          }
        })
      }

      //过滤有商品并且不是赠品数据
      let tableLength = this.$refs['goodsTable'].tableData.filter(it => it.skuId && !it.flgGift).length
      //region 有价格
      let hasPriceTable = this.$refs['goodsTable'].tableData.filter(it => it.skuId && it.priceSale > 0 && !it.flgGift)
      //endregion

      //region  无价格
      let noPriceTable = this.$refs['goodsTable'].tableData.filter(it => it.skuId && (!it.priceSale || it.priceSale == 0) && !it.flgGift)
      if (noPriceTable && noPriceTable.length > 0 && noPriceTable.length == tableLength) {
        this.updateTotalFootMessageFlag = true
        for (let i = 0; i < noPriceTable.length; i++) {
          //折扣禁用
          noPriceTable[i].readOnly = ['discount']
        }
        this.$refs['goodsTable'].$refs['xTable'].refreshColumn();
      } else {
        this.updateTotalFootMessageFlag = false
        for (let i = 0; i < noPriceTable.length; i++) {
          delete noPriceTable[i].readOnly
        }
        this.$refs['goodsTable'].$refs['xTable'].refreshColumn();
      }
      //endregion
    },
    /**
     *   @desc   : 外协品修改明细行
     *   @date   : 2024/6/18 15:09
     *   @author : 寇珊珊
     */
    getTotalsOutsourced(field, row, rowIndex){
      //计算合计
      this.getTotale()
      //过滤有商品并且不是赠品数据
      let tableLength = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId ).length
      //region 有价格
      let hasPriceTable = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId && it.priceSale > 0)
      //endregion

      //region  无价格
      if(this.$refs['outsourcedGoodsTable'].tableData && this.$refs['outsourcedGoodsTable'].tableData.length>0 ){
        let noPriceTable = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId && (!it.priceSale || it.priceSale == 0) )
        if (noPriceTable && noPriceTable.length > 0 && noPriceTable.length == tableLength) {
          for (let i = 0; i < noPriceTable.length; i++) {
            //折扣禁用
            noPriceTable[i].readOnly = ['discount']
          }
          this.$refs['outsourcedGoodsTable'].$refs['xTable'].refreshColumn();
        } else {
          let delReadOnlyTable = this.$refs['outsourcedGoodsTable'].tableData
          for (let i = 0; i <delReadOnlyTable.length; i++) {
            delete delReadOnlyTable[i].readOnly
          }
          this.$refs['outsourcedGoodsTable'].$refs['xTable'].refreshColumn();
        }
      }
      //endregion
    },
    /**
     *   @desc   : 修改实收金额或者折扣或者优惠金额
     *   @date   : 2024/6/12 11:01
     *   @author : 寇珊珊
     */
    changeDiscountOrAmount(value ,number){
      //region  修改实收金额或者折扣或者优惠金额
      //实收金额
      if(number ==1){
        if(value == this.oldSumFactAmt){
          return
        }
        //实收金额
        // this.goodsFootFormData.factAmt = value
        //优惠金额 = 合计金额 - 实收金额
        this.goodsFootFormData.discAmt = parseFloat( ( parseFloat(this.goodsFootFormData.sumAmount) - parseFloat(this.goodsFootFormData.factAmt) ).toFixed(2) )
        //总单折扣 = 实收金额 /合计金额
        if(this.goodsFootFormData.sumAmount>0){
          this.goodsFootFormData.discount = parseInt( ( parseFloat(this.goodsFootFormData.factAmt) / parseFloat(this.goodsFootFormData.sumAmount) * 100).toFixed(2) )
        }
      }
      //折扣
      else if(number ==2){
        //折扣
        this.goodsFootFormData.discount = parseInt( parseFloat(value).toFixed(2) )
        //实收金额 = 合计金额 * 折扣
        this.goodsFootFormData.factAmt = parseFloat( ( parseFloat(this.goodsFootFormData.sumAmount) * parseFloat(this.goodsFootFormData.discount) /100 ).toFixed(2) )
        //优惠金额 = 合计金额 - 实收金额
        this.goodsFootFormData.discAmt = parseFloat( ( parseFloat(this.goodsFootFormData.sumAmount) -  parseFloat(this.goodsFootFormData.factAmt) ).toFixed(2) )
      }
      //优惠金额
      else if(number ==3){
        //优惠金额
        // this.goodsFootFormData.discAmt = value
        //实收金额 = 合计金额 - 优惠金额
        this.goodsFootFormData.factAmt = parseFloat( ( parseFloat(this.goodsFootFormData.sumAmount) - parseFloat(this.goodsFootFormData.discAmt) ).toFixed(2) )
        //折扣 = 实收金额 / 合计金额
        this.goodsFootFormData.discount = parseInt(  ( parseFloat(this.goodsFootFormData.factAmt) /  parseFloat(this.goodsFootFormData.sumAmount) * 100 ).toFixed(2) )
      }
      //endregion

      //region  修改普通明细和外协明细
      let table = this.$refs['goodsTable'].tableData.filter(it => it.skuId && it.priceSale > 0 && !it.flgGift)
      let outsourcedTable = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId)
      if (outsourcedTable && outsourcedTable.length > 0) {
        table = table.concat(outsourcedTable)
      }
      if (table && table.length > 0) {
        let  i = 1;
        let sumFactAmt = 0
        for (let row of table) {
          //商品折扣= 折扣
          row.discount = parseInt( parseFloat(this.goodsFootFormData.discount).toFixed(2))
          if(i<table.length){
            //实际单价 = 售价 * 折扣
            row.factPrice = parseFloat( ( parseFloat(row.priceSale) * parseFloat( row.discount) / 100).toFixed(2) )
            //实际金额 =  实际单价 * 数量
            row.factAmt = parseFloat( ( parseFloat(row.factPrice) * parseFloat(row.itemQty) ).toFixed(2) )
            sumFactAmt += parseFloat(row.factAmt.toFixed(2) )
            i++
          }
          //最后一条带价格的明细
          else if(i == table.length){
            //实际金额 =  实收金额 - 除了最后一条明细的实际金额总和
            row.factAmt = parseFloat( ( parseFloat(this.goodsFootFormData.factAmt) - parseFloat(sumFactAmt) ).toFixed(2) )
            //实际单价 = 实际金额 / 数量
            row.factPrice = parseFloat( ( parseFloat(row.factAmt) / parseFloat(row.itemQty) ).toFixed(2) )
          }
        }
      }
      //endregion

      //region 赠品赋值为0
      let flgGiftList = this.$refs['goodsTable'].tableData.filter(it => it.skuId && it.flgGift)
      if (flgGiftList && flgGiftList.length > 0) {
        for (let row of flgGiftList) {
          row.priceSale = 0
          row.factPrice = 0
          row.discount = 0
        }
      }
      //endregion
    },
    /**
    * @desc   : 计算合计
    * @author : 常皓宁
    * @date   : 2024/5/29 13:27
    */
    getTotale(table){
      if (!table) {
        table = this.$refs['goodsTable'].tableData.filter(it => it.skuId)
        let outsourcedTable = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId)
        if (outsourcedTable && outsourcedTable.length > 0) {
          table = table.concat(outsourcedTable)
        }
      }
      let sumQuantity = 0;  // 合计数量
      let sumAmount = 0;    // 合计金额
      let sumStandard = 0;  // 标价总额
      let factAmt = 0;  // 折扣金额
      if (table && table.length > 0) {
        table.forEach(row => {
          sumQuantity += parseFloat(row["itemQty"]);
          sumAmount += parseFloat(row["itemAmt"])
          this.$set(row, 'amtStd', parseFloat(row["itemQty"]) * parseFloat(row["priceStd"]));
          sumStandard += parseFloat(row["amtStd"]);
          // this.$set(row, 'factAmt', parseFloat(row["itemQty"]) * parseFloat(row["factPrice"]));
          //
          factAmt += parseFloat(row["factAmt"])
        })
      }
      this.goodsFootFormData.sumQuantity = sumQuantity;
      this.goodsFootFormData.sumAmount = sumAmount;
      this.goodsFootFormData.sumStandard = sumStandard;
      this.goodsFootFormData.saleDiscount = (sumAmount / sumStandard * 100).toFixed(2);
      //实收金额 = 明细实际金额汇总
      this.goodsFootFormData.factAmt = factAmt;
      //优惠金额 = 合计金额 - 实收金额
      this.goodsFootFormData.discAmt = parseFloat( ( parseFloat(this.goodsFootFormData.sumAmount) -  parseFloat(this.goodsFootFormData.factAmt) ).toFixed(2) );
      //折扣 = 实收金额 / 合计金额  *100
      this.goodsFootFormData.discount = parseInt( ( parseFloat(this.goodsFootFormData.factAmt) / parseFloat(this.goodsFootFormData.sumAmount) * 100 ).toFixed(2) );
      //实收金额
      this.oldSumFactAmt = this.goodsFootFormData.factAmt
    },
    /**
     *   @desc   : 删除明细行
     *   @date   : 2024/6/12 9:44
     *   @author : 寇珊珊
     */
    delRow(row, rowIndex){
      let list = this.$refs['goodsTable'].tableData.filter(it => it.skuId)
      if (list && list.length > 0) {
        let table = this.$refs['goodsTable'].tableData.filter(it => it.priceSale > 0)
        if (table && table.length == 0) {
          this.$IBMessage({
              content: this.$t('Q_002', {'param': this.$v('W_129')}),
              title: this.$t('systemQuestion')
            },
            {
              ok: () => {
                this.getTotals(this.$refs['goodsTable'].tableData)
              },
              cancel: () => {
                this.$refs['goodsTable'].tableData.push(row);
              }
            })
        }
      }
    },
    /**
     *   @desc   : 删除外协品明细行
     *   @date   : 2024/6/12 9:44
     *   @author : 寇珊珊
     */
    delRowOutsourced(row, rowIndex) {
      let list = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.supId)
      if(list && list.length > 0){
        let table = this.$refs['outsourcedGoodsTable'].tableData.filter(it => it.priceSale > 0)
        if (table && table.length == 0) {
          this.$IBMessage({
              content: this.$t('Q_002', {'param': this.$v('W_129')}),
              title: this.$t('systemQuestion')
            },
            {
              ok: () => {
                this.getTotals(this.$refs['outsourcedGoodsTable'].tableData)
              },
              cancel: () => {
                this.$refs['outsourcedGoodsTable'].tableData.push(row);
              }
            })
        }
      }
    },
    /**
     * @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) {
        // redion 对可大编辑标识赋值
        if(this.type === this.$config.formMode.edit){
          //已出库
          if( data["data"].outStatus == this.$config.outStatus.yiChuKu){
            this.canBigEditFlag = false
          }
          //出库中或未出库
          else{
            this.canBigEditFlag = true
          }
        }
        //endregion

        this.formData = data["data"];
        if( data["dataItem"] && data["dataItem"].length>0){
          for(let i =0;i<data["dataItem"].length;i++){
            //可编辑数量（原数量）
            data["dataItem"][i].primaryQty =   data["dataItem"][i].itemQty
          }

          let itemList = data["dataItem"].filter(it=>it.skuId)
          this.formData.itemList =  itemList
          this.formData.outsourcedItemList =  data["dataItem"].filter(it=>!it.skuId)
        }
        this.formData.receiptList = data["receiptItem"];

        if (itemList && itemList.length > 0) {
          itemList.map(row => {
            let item = row
            //包装规格
            this.$set(item, 'unitInfo', row['boxPiece'])
            row.nonStandardForm = {
              formula: (row['subUnitName'] ? '1' + row['subUnitName'] : '') + row['packBox'] + row['unitName'],
              box: row['box'],
              piece: row['piece'],
            }
            //包装
            if (row['subUnitId']) {
              row.nonStandardItems = [
                {code: 'formula', label: '计算公式', type: 'text', readonly: true},
                {code: 'box', label: row['subUnitName'], type: 'number'},
                {code: 'piece', label: row['unitName'], type: 'number'}
              ]
            } else {
              row.nonStandardItems = [
                {code: 'formula', label: '计算公式', type: 'text', readonly: true},
                {code: 'piece', label: row['unitName'], type: 'number', field: 'piece'}
              ]
            }
          })
        }
        //商品总数
        this.goodsFootFormData.sumQuantity = this.formData.sumQuantity;
        //合计金额
        this.goodsFootFormData.sumAmount = this.formData.sumAmount;
        //折扣
        this.goodsFootFormData.discount = this.formData.discount;
        //折后金额
        this.goodsFootFormData.factAmt = this.formData.factAmt;
        //优惠金额
        this.goodsFootFormData.discAmt = this.formData.discAmt;
        //标价
        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();
      //外协品
      let outsourcedItemTable = this.$refs['outsourcedGoodsTable'].getTableDataFilter();
      if(outsourcedItemTable && outsourcedItemTable.length>0){
        itemTable = itemTable.concat(outsourcedItemTable)
      }
      if (!itemTable || itemTable.length == 0) {
        this.$Message.warning(this.$t('W_012'))
        return false;
      }
      let i= 0
      for (let it of itemTable) {
        if (!it.itemQty || it.itemQty === '' || it.itemQty === 0) {
          this.$message.error(this.$t('W_131', {
            'param': this.$t('sequence') + (i + 1) + this.$t('rowNo') + this.$t('itemQty')
          }))
          return false;
        }
        //编辑校验数量不能大于 编辑查询时带出来的数量
        if( this.type === this.$config.formMode.edit ){
          if(it.itemQty > it.primaryQty){
            this.$message.error(this.$t('W_132', {'param1': this.$t('itemQty'), 'param2':  this.$t('primaryQty')}))
            this.$Message.warning(this.$t('W_134'))
            return false;
          }
        }
        i++
      }

      //外协品列表
      let index = 0
      for (let it of outsourcedItemTable) {
        if (!it.itemQty || it.itemQty === '' || it.itemQty === 0) {
          this.$message.error(this.$t('W_133', {
            'param': this.$t('sequence') + (index + 1) + this.$t('rowNo') + this.$t('itemQty')
          }))
          return false;
        }
        //编辑校验数量不能大于 编辑查询时带出来的数量
        if( this.type === this.$config.formMode.edit ){
          if(it.itemQty > it.primaryQty){
            this.$message.error(this.$t('W_134', {'param1': this.$t('itemQty'), 'param2':  this.$t('primaryQty')}))
            return false;
          }
        }
        index++
      }

      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();
        //删除的外协数据
        let deleteOutsourcedItemTable = this.$refs['outsourcedGoodsTable'].getDeleteData();
        if(deleteOutsourcedItemTable && deleteOutsourcedItemTable.length>0){
          this.formData.deleteItemList = deleteItemTable.concat(deleteOutsourcedItemTable)
        }else{
          this.formData.deleteItemList = deleteItemTable
        }
      }

      // 修改新增的表数据
      let itemTable = this.$refs['goodsTable'].getTableDataFilter();
      //修改新增的外协品表数据
      let itemOutsourcedTable = this.$refs['outsourcedGoodsTable'].getTableDataFilter();
      if(itemOutsourcedTable && itemOutsourcedTable.length>0){
        itemTable =  itemTable.concat(itemOutsourcedTable)
      }
      itemTable.forEach((it, index) => {
        if (!it.nonStdCode || it.nonStdCode === '') {
          this.$set(it, 'nonStdCode', '-');
        }
        //标价
        if (!it.priceStd || it.priceStd == 0) {
          this.$set(it, 'priceStd',0);
        }
        //标价金额
        if (!it.amtStd || it.amtStd == 0) {
          this.$set(it, 'amtStd',0);
        }
        //标价折扣
        if (!it.priceDiscount || it.priceDiscount == 0) {
          this.$set(it, 'priceDiscount',100);
        }
      });
      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() {
      console.log('this.params',this.params)
      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() {
    this.focusItem = 'orderId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'orderId'  // 设置主键Id
  }
}
</script>
