<!-- @desc:其它入库新建 @auth:常皓宁 @time : 2024/2/19 9:38 -->
<template>
  <div class="main-div">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <DkCollapse ref="collapse" @on-change="changeCollapse">
      <!--基本信息-->
      <DkPanel prop="essentialInformation">
        <div id="search-cond-div" ref="search-cond-div" slot="content" class="form-content-class">
          <DkForm ref="formInline" v-model="formData" :rules="ruleInline" name="dk-form" :label-max-words="6"
                  @onValidate="onValidate">
            <!--所属公司-->
            <DkFormItem prop="ascpId" :required="true">
              <SelectPop v-model="formData.ascpId" :multiple="false" :options="companyList"
                         ref="ascpId"
                         :labelInValue="true"
                         :disabled="this.type !== this.$config.formMode.add"
                         labelKey="cpName"
                         valueKey=cpId>
              </SelectPop>
            </DkFormItem>
            <!--入库单号-->
            <DkFormItem prop="entryNo">
              <InputPop ref="entry_no" v-model="formData.entryNo"
                        :readonly="true"/>
            </DkFormItem>
            <!-- 单据日期 -->
            <DkFormItem prop="invoiceDate" :required="false">
              <DatePickerPop v-model="formData.makingTime"
                             :placeholder="$t('inputWords',{'search-name':$t('invoiceDate')})"
                             type="date" :short-cut-flag="true"
                             :readonly="true"/>
            </DkFormItem>
            <!-- 入库对象 -->
            <DkFormItem prop="entryObject"
                        :label="$t('entryObjectName')">
              <SelectMagnifier v-model="formData.entryObject"
                               :display-text="formData.entryObjectName"
                               searchType="S"
                               :disabled="entryObjectDisabled"
                               @ok="entryObjectChange"
                               :other-condition="{ascpId:this.formData.ascpId}"
                               :type="this.$config.MagnifierType.organization">

              </SelectMagnifier>
            </DkFormItem>
            <!-- 入库原因 -->
            <DkFormItem prop="entryReason" :required="true">
              <SelectPop v-model="formData.entryReason" :multiple="false" :options="entryReasonList"
                         ref="entryReason"
                         :labelInValue="true"
                         :disabled="entryReasonDisabled"
                         labelKey="dataValue"
                         valueKey=dataId>
              </SelectPop>
            </DkFormItem>
            <!-- 责任人 -->
            <DkFormItem prop="makingUser" :label="$t('directorMan')"
                        :required="true">
              <SelectMagnifier v-model="formData.makingUser"
                               :display-text="formData.makingUserName"
                               searchType="S" :other-condition="{}"
                               :init-search-flag="true"
                               :disabled="makingUserDisabled"
                               :type="this.$config.MagnifierType.user">
              </SelectMagnifier>
            </DkFormItem>
            <!--部门-->
            <DkFormItem prop="orgId" :label="$t('department')"
                        :required="true">
              <SelectMagnifier v-model="formData.orgId"
                               :display-text="formData.orgName"
                               searchType="S" :other-condition="{}"
                               :init-search-flag="true"
                               :disabled="orgIdDisabled"
                               :type="this.$config.MagnifierType.organization"></SelectMagnifier>
            </DkFormItem>
            <!--自动入库标识-->
            <DkFormItem prop="autoFlag">
              <template>
                <i-switch v-model="formData.automaticFlg" @on-change="changeEntryStatus"
                          :disabled="type === $config.formMode.handle">
                  <span slot="open"></span>
                  <span slot="close"></span>
                </i-switch>
              </template>
            </DkFormItem>
            <!--备注-->
            <DkFormItem prop="remarks" :span="12">
              <InputPop ref="remarks" v-model="formData.remarks"
                        maxlength=500 textareaFlag/>
            </DkFormItem>
            <!--入库日期-->
            <DkFormItem prop="entryTime" :label="$t('entryTime')" v-show="showEntryDate">
              <DatePickerPop v-model="formData.entryDate"
                             :placeholder="$t('inputWords',{'search-name':$t('entryTime')})"
                             type="date" :short-cut-flag="true" :readonly="true"/>
            </DkFormItem>
          </DkForm>
        </div>
      </DkPanel>
      <!--商品信息-->
      <DkPanel prop="goodsInformation">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info"
             slot="content">
          <EditTable ref="goodsTable" :data="formData.goodsList" showFooter
                     major-field="skuId"
                     :columns-social="goodsColumns"
                     :columns="visUserSensitive? goodsColumns : goodsColumns.filter(it => !it.flgUserSensitive)"
                     :readonly="this.type === this.$config.formMode.edit"
                     :new-row-flag="this.type === this.$config.formMode.add || (this.type === 'handle' && formData.allEdit)"
                     controlId="skuId"
                     @on-choose="getTotals"
                     @changeValue="changeValue"
                     @onBatchChoose="batchChoose"
                     :flgHidePrice="!visUserSensitive"
          ></EditTable>
          <div>
            <DkForm ref="goodsFootFormData" v-model="goodsFootFormData" :labelMaxWords="5" name="dk-form"
                    class="form-content-class">
              <DkRow>
                <!--货物金额-->
                <DkFormItem prop="sumGoodsAmount">
                  <InputNumberPop ref="sumGoodsAmount" v-model="goodsFootFormData.sumGoodsAmount" :clearable="false"
                                  :digits="2"
                                  :readonly="true"/>
                </DkFormItem>
                <!--总重量-->
                <DkFormItem prop="sumWeight">
                  <InputNumberPop ref="sumWeight" v-model="goodsFootFormData.sumWeight" :digits="2"
                                  :readonly="true" unit="KG"/>
                </DkFormItem>
                <!--总体积-->
                <DkFormItem prop="sumVolume">
                  <InputNumberPop ref="sumVolume" v-model="goodsFootFormData.sumVolume" :digits="2"
                                  :readonly="true" unit="m³"/>
                </DkFormItem>
              </DkRow>
            </DkForm>
          </div>
        </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" :disabled="this.allCanNoEdit?true:false"
                     folder="t_order_entry/annex_paths" :accept="$config.uploadFileConfig.acceptPicType"
                     :format="['jpg','jpeg','png']"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save" @close="close"></DkSaveButton>

  </div>
</template>

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

export default {
  name: "form",
  mixins: [indexMixin, formMixin],
  data() {
    let self = this
    return {
      //用户敏感信息隐藏
      visUserSensitive: false,
      //画面模式选项角标
      bottomList: ['1', '2', '3', '5'],
      companyList: [],//公司list
      //入库原因
      entryReasonList: [],
      //入库原因是否可用
      entryReasonDisabled: false,
      //入库对象是否可用
      entryObjectDisabled: false,
      //责任人是否可用
      makingUserDisabled: false,
      //部门是否可用
      orgIdDisabled: false,
      //是否显示自动办理入库标识
      showAutoFlag: true,
      //入库日期是否显示
      showEntryDate: false,
      // 保存错误消息
      errMessage: {},
      allCanNoEdit: false, //是否所有的都不允许编辑
      // 画面表单数据
      formData: {
        sale1Id: null,
        sale2Id: null,
        ascpId: null,//所属公司
        entryId: null,//入库单Id
        entryObject: null,//入库对象id
        entryNo: null,//入库单号
        makingTime: null,//制单日期
        entryDate: null,//入库日期
        entryReason: null,//入库原因
        automaticFlg: false,//自动入库标识
        customerId: null,//客户id
        customerName: null,//客户名称
        customerPhone: null,//客户电话
        contactName: null,//联系人
        contactPhones: null,//联系电话
        orgId: null,//业务部门
        makingUser: null,//
        supplierId: null,//供应商id
        remarks: null,//备注
        skuId: null,
        defWhId: null,//部门默认仓库ID

        // 附件
        annexPaths: [],
        designUser: null,
        designUserName: null,
        designRemarks: null,
        apvResult: null,
        erpHdId: null,
        hdList: [],//存放主从家装设计师
        dcId: null,
        dcName: null,
        hdId: null,
        hdName: null,
        hdStaffCode: null,
        hdStaffName: null,
        erpHomeStaffs: [],//家装业务员
        saleChannel: null,//销售渠道
        saleChannelCode: null,//销售渠道编码
      },
      goodsColumns: [
        // 商品名称
        {
          field: 'skuName',
          controlId: 'skuId',
          width: 255,
          type: 'tableSelect',
          sortBoolean: false,
          dataType: self.$config.tableSelectType.entryOtherGoods,
          fieldUpdate: [
            {updateField: 'skuId', valueFiled: 'skuId'},
            {updateField: 'skuName', valueFiled: 'skuName'},
            {updateField: 'skuModel', valueFiled: 'skuModel'},
            {updateField: 'skuCode', valueFiled: 'skuCode'},
            {updateField: 'nonStandardCode', valueFiled: 'nonStandardCode'},//非标号
            {updateField: 'remarks', valueFiled: 'remarks'},
            {updateField: 'skuSpecs', valueFiled: 'skuSpecs'},//商品规格
            {updateField: 'skuTypeName', valueFiled: 'skuTypeName'},
            {updateField: 'brandName', valueFiled: 'brandName'},
            {updateField: 'skuWeight', valueFiled: 'skuWeight'},
            {updateField: 'skuVolume', valueFiled: 'skuVolume'},
            // {updateField: 'whId', valueFiled: 'whId'},
            // {updateField: 'whId_Name', valueFiled: 'whName'},
          ],
          searchDetailFlag: false
        },
        // 商品型号
        {
          field: 'skuModel',
          controlId: 'skuId',
          width: 255,
          type: 'tableSelect',
          sortBoolean: false,
          dataType: self.$config.tableSelectType.entryOtherGoods,
          fieldUpdate: [
            {updateField: 'skuId', valueFiled: 'skuId'},
            {updateField: 'skuName', valueFiled: 'skuName'},
            {updateField: 'skuModel', valueFiled: 'skuModel'},
            {updateField: 'skuCode', valueFiled: 'skuCode'},
            {updateField: 'nonStandardCode', valueFiled: 'nonStandardCode'},//非标号
            {updateField: 'remarks', valueFiled: 'remarks'},
            {updateField: 'skuSpecs', valueFiled: 'skuSpecs'},//商品规格
            {updateField: 'skuTypeName', valueFiled: 'skuTypeName'},
            {updateField: 'brandName', valueFiled: 'brandName'},
            {updateField: 'skuWeight', valueFiled: 'skuWeight'},
            {updateField: 'skuVolume', valueFiled: 'skuVolume'},
          ],
          searchDetailFlag: false
        },
        // 唯一编码(sku编码)
        {
          field: 'skuCode',
          controlId: 'skuId',
          width: 255,
          type: 'tableSelect',
          sortBoolean: false,
          dataType: self.$config.tableSelectType.entryOtherGoods,
          fieldUpdate: [
            {updateField: 'skuId', valueFiled: 'skuId'},
            {updateField: 'skuName', valueFiled: 'skuName'},
            {updateField: 'skuModel', valueFiled: 'skuModel'},
            {updateField: 'skuCode', valueFiled: 'skuCode'},
            {updateField: 'nonStandardCode', valueFiled: 'nonStandardCode'},//非标号
            {updateField: 'remarks', valueFiled: 'remarks'},
            {updateField: 'skuSpecs', valueFiled: 'skuSpecs'},//商品规格
            {updateField: 'skuTypeName', valueFiled: 'skuTypeName'},
            {updateField: 'brandName', valueFiled: 'brandName'},
            {updateField: 'skuWeight', valueFiled: 'skuWeight'},
            {updateField: 'skuVolume', valueFiled: 'skuVolume'},

          ],
          searchDetailFlag: false
        },
        // 入库数量
        {
          field: 'entryGoingQuantity',
          type: 'number',
          digits: 0,
          sum: true,
          formula: {
            entryGoingAmount: ['orderPriceSale*entryGoingQuantity', 'orderPriceSale', 'entryGoingQuantity'],
            skuWeight: ['entryGoingQuantity*skuWeight', 'entryGoingQuantity', 'skuWeight'],
            skuVolume: ['entryGoingQuantity*skuVolume', 'entryGoingQuantity', 'skuVolume'],
            entryQuantity: ['entryGoingQuantity', 'entryGoingQuantity'],
          },
        },
        //入库单价
        {
          field: 'orderPriceSale',
          title: self.$t('entryPriceSale'),
          type: 'number',
          digits: 2,
          flgUserSensitive: true,
          formula: {
            entryGoingAmount: ['orderPriceSale*entryGoingQuantity', 'orderPriceSale', 'entryGoingQuantity'],
          },
        },
        //入库金额
        {
          field: 'entryGoingAmount',
          type: 'number',
          digits: 2,
          sum: true,
          flgUserSensitive: true,
          formula: {
            orderPriceSale: ['entryGoingAmount/entryGoingQuantity', 'entryGoingAmount', 'entryGoingQuantity'],
          },
        },
        //仓库名称
        {
          copyVisible: this.type !== this.$config.formMode.edit,
          field: 'whId',
          type: 'select',
          options: () => self.warehouseList,
          labelKey: 'whName',
          valueKey: 'whId',
          //equal: true,
          dataType: self.$config.tableSelectType.warehouse,
          fieldUpdate: [
            {updateField: 'warehouseName', valueFiled: 'whName'},
            {updateField: 'whId', valueFiled: 'whId'},
          ],
          searchDataFlag: false,
        },
        {field: 'nonStandardCode', type: 'text',}, //非标号
        {field: 'remarks', type: 'text', equal: true,},
        {field: 'skuSpecs', type: 'disabled'},//商品规格sku_specs
        {field: 'skuTypeName', type: 'disabled'},//型号分类
        {field: 'brandName', type: 'disabled'},//商品品牌
        {field: 'skuWeight', type: 'disabled', digits: 0, sum: true,},//商品重量
        {field: 'skuVolume', type: 'disabled', digits: 0, sum: true,},//商品体积
      ],
      //商品合计信息
      goodsFootFormData: {
        sumGoodsAmount: 0,
        sumVolume: 0,
        sumWeight: 0,
      },
      // 校验规则
      ruleInline: {
        entryReason: [
          {required: true, trigger: 'none', type: 'number'}
        ],
        ascpId: [
          {required: true, trigger: 'none', type: 'number'}
        ],
        orgId: [
          {required: true, trigger: 'none', type: 'number'}
        ],
        makingUser: [
          {required: true, trigger: 'none', type: 'number'}
        ],
      },
    }
  },

  methods: {
    /**
     * @desc   : 保存校验
     * @author : 寇珊珊
     * @date   : 2022/3/14 16:56
     */
    onValidate({prop, status, error}) {
      this.$set(this.errMessage, prop, error)
    },
    /**
     * @desc   : 入库对象改变事件
     * @author : 夏常明
     * @date   : 2023/9/13 19:23
     */
    entryObjectChange(val) {
      if (val) {
        if (val[0].objType == 2)//客户
        {
          this.formData.customerId = val[0].objId;
          this.formData.customerName = val[0].objName;
          this.formData.customerPhone = val[0].customerPhone;
        } else { //供应商
          this.formData.supplierId = val[0].objId;
        }
      }
    },
    /**
     * @desc   : 自动入库标识变更
     * @author : 夏常明
     * @date   : 2023/9/1 16:34
     */
    changeEntryStatus() {
      if (this.type === this.$config.formMode.add) {
        if (this.formData.automaticFlg) {
          this.formData.entryDate = new Date().format()
          this.showEntryDate = true
        } else {
          this.formData.entryDate = null
          this.showEntryDate = false
        }
      }
    },
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2022/6/23 8:48
     */
    changeValue(field, row, rowIndex) {
      // 计算合计值
      this.getTotals(field, row, rowIndex);
    },
    /**
     *   @desc   : 获取商品表格中数量、金额后计算总单信息
     *   @date   : 2022/5/30 15:31
     *   @author : 寇珊珊
     */
    getTotals(field, row, rowIndex) {
      let table = this.$refs['goodsTable'].getTableDataFilter()
        .filter(it => it.flgNonStandardType != 1 && it.flgNonStandardType != 2 && it.entryGoingQuantity > 0);
      let itemAmount = 0; // 货物总额
      let weight = 0;// 总重量
      let volumn = 0;// 总体积
      let quantityName = this.type == this.$config.formMode.edit ? 'tItemQuantity' : 'entryGoingQuantity'
      let amountName = this.type == this.$config.formMode.edit ? 'tItemAmount' : 'entryGoingAmount'
      if (table && table.length > 0) {
        table.forEach(row => {
          if (row[amountName]) {
            // 金额
            itemAmount += parseFloat(row[amountName]);
          }
          // 重量
          if (row.skuWeight && row[quantityName]) {
            weight += parseFloat(row[quantityName]) * parseFloat(row.skuWeight);
          }
          // 体积
          if (row.skuVolume && row[quantityName]) {
            volumn += parseFloat(row[quantityName]) * parseFloat(row.skuVolume);
          }

          // 如果是组合，需要计算体积和重量
          if (row['promotionType'] === this.$config.promotionType.combined) {
            if (row.bomItems && row.bomItems.length > 0) {
              row.bomItems.forEach(it => {
                if (it.skuWeight) {
                  weight += parseFloat(it[quantityName]) * parseFloat(it.skuWeight);
                }
                // 体积
                if (it.skuVolume) {
                  volumn += parseFloat(it[quantityName]) * parseFloat(it.skuVolume);
                }
              })
            }
          }
        })
      }
      this.goodsFootFormData.sumGoodsAmount = itemAmount;
      // 计算合计金额
      this.getSumAmount();
      this.goodsFootFormData.sumWeight = parseFloat(weight.toFixed(6));
      this.goodsFootFormData.sumVolume = parseFloat(volumn.toFixed(6));

      //选择数据带出默认仓库
      if (!row.whId || row.whId === 0 || row.whId === null) {
        this.$set(row, 'whId', this.whId);
        this.$set(row, 'whId_Name', this.whName);
      }
    },
    /**
     * @desc   : 计算合计金额
     * @author : 周兴
     * @date   : 2022/6/16 14:45
     */
    getSumAmount() {
      // // 合计金额=费用金额+货物金额
      // this.feeFormData.sumAmount = this.feeFormData.sumFeeAmount + this.goodsFootFormData.sumGoodsAmount;
      // // 剩余应收=合计金额-收款金额
      // this.feeFormData.receivable = this.feeFormData.sumAmount - this.feeFormData.sumReceivableAmount;
    },
    /**
     * @desc   : 批量选择数据带出默认仓库
     * @author : 赵振岚
     * @date   : 2023/10/26 16:08
     */
    batchChoose(batchRows, rowIndex) {
      console.log("batchRows", batchRows)
      batchRows.forEach(it => {
        if (!it.whId || it.whId === 0 || it.whId === null) {
          this.$set(it, 'whId', this.whId);
          this.$set(it, 'whId_Name', this.whName);
        }
      })
    },
  },
}
</script>

<style>

</style>
