<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <DkPageButton :total="editKeys?editKeys.length:0"
                  :current="editIndex"
                  v-if="editKeys && editKeys.length > 1"
                  @pageChange="editPageChange"></DkPageButton>
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <!--  基础属性  -->
      <DkPanel prop="baseAttribute">
        <DkForm slot="content" ref="formInline0" v-model="formData" :labelMaxWords=5>
          <!--商品编码-->
          <DkFormItem prop="skuCode">
            <InputPop ref="skuCode" v-model="formData.skuCode" :readonly="true"/>
          </DkFormItem>
          <!--商品型号-->
          <DkFormItem prop="skuModel" :required="true">
            <InputPop ref="skuModel" v-model="formData.skuModel"/>
          </DkFormItem>
          <!--商品名称-->
          <DkFormItem prop="skuName" :required="true">
            <InputPop ref="skuName" v-model="formData.skuName"/>
          </DkFormItem>
          <!--  品牌  -->
          <DkFormItem prop="brandId" :label="$t('brandIds')" :required="true">
            <SelectMagnifier v-model="formData.brandId" :display-text="formData.brandName"
                             :type="this.$config.MagnifierType.brand"
                             :multiple="false"></SelectMagnifier>
          </DkFormItem>
          <!--商品种类-->
          <DkFormItem prop="categoryId" :label="$t('category')" :required="true">
            <SelectPop v-model="formData.categoryId" :multiple="false"
                       :options="categoryList"
                       labelKey="catName"
                       valueKey=catId>
            </SelectPop>
          </DkFormItem>
          <!--商品系列-->
          <DkFormItem prop="seriesId" :label="$t('series')" :required="true">
            <SelectPop v-model="formData.seriesId" :multiple="false" :options="seriesList"
                       labelKey="seriesName"
                       valueKey=seriesId>
            </SelectPop>
          </DkFormItem>
          <!--商品规格-->
          <DkFormItem prop="skuSpec">
            <InputPop ref="skuSpec" v-model="formData.skuSpec"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks" :span="12">
            <InputPop ref="remarks" v-model="formData.remarks"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--  商品属性  -->
      <DkPanel prop="goodsAttribute">
        <DkForm slot="content" ref="formInline1" v-model="formData" :labelMaxWords=5>
          <!--基本单位-->
          <DkFormItem prop="unitId" :label="$t('piece')" :required="true">
            <SelectPop v-model="formData.unitId" :multiple="false" :options="unitList"
                       @on-select-label="unitClear"
                       labelKey="unitName"
                       valueKey="unitId">
            </SelectPop>
          </DkFormItem>
          <!--是否开启辅助单位-->
          <DkFormItem prop="flgToSubUuId">
            <template>
              <i-switch v-model="formData.flgSubUnit" @on-change="changeSubUnit">
                <span slot="open"></span>
                <span slot="close"></span>
              </i-switch>
            </template>
          </DkFormItem>
          <!--辅助单位-->
          <DkFormItem prop="subUnitId" :label="$t('box')" :required="true" v-if="showSubUnit">
            <SelectPop v-model="formData.subUnitId" :multiple="false"
                       :options="unitList.filter(it=>it.unitId != formData.unitId)"
                       :disabled="formData.unitId?!formData.flgSubUnit:true"
                       labelKey="unitName"
                       valueKey="unitId">
            </SelectPop>
          </DkFormItem>
          <!--包装-->
          <DkFormItem prop="conversionFactor" :label="$t('packBox')" :required="true" data-type="number"
                      v-if="showSubUnit">
            <InputNumberPop ref="conversionFactor"
                            v-model="formData.conversionFactor"
                            :disabled="formData.unitId?!formData.flgSubUnit:true"
                            :digits="this.digits"
            />
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--  价格信息-->
      <DkPanel prop="priceItem">
        <DkForm slot="content" v-model="formData">
          <!--是否开启价格体系-->
          <DkFormItem prop="flgToPrice">
            <template>
              <i-switch v-model="formData.flgPrice">
                <span slot="open"></span>
                <span slot="close"></span>
              </i-switch>
            </template>
          </DkFormItem>
        </DkForm>
        <DkForm slot="content" ref="formInline2" v-model="formData" v-if="formData.flgPrice">
          <!--采购价-->
          <DkFormItem prop="pricePurchase" :required="true" data-type="number">
            <InputNumberPop ref="pricePurchase" v-model="formData.pricePurchase"/>
          </DkFormItem>
          <!--零售价-->
          <DkFormItem prop="priceStandard" :required="true" data-type="number">
            <InputNumberPop ref="priceStandard" v-model="formData.priceStandard"/>
          </DkFormItem>
          <!--批发价-->
          <DkFormItem prop="priceWholesale" :required="true" data-type="number">
            <InputNumberPop ref="priceWholesale" v-model="formData.priceWholesale"/>
          </DkFormItem>
          <!--其他售价-->
          <DkFormItem prop="priceOther" :required="true" data-type="number">
            <InputNumberPop ref="priceOther" v-model="formData.priceOther"/>
          </DkFormItem>
          <!--销售售价-->
          <DkFormItem prop="priceLimited" :required="true" data-type="number">
            <InputNumberPop ref="priceLimited" v-model="formData.priceLimited"/>
          </DkFormItem>
        </DkForm>
      </DkPanel>

      <!--  期初库存信息-->
      <DkPanel prop="invInto">
        <!--是否开启期初库存-->
        <DkForm slot="content" v-model="formData">
          <DkFormItem prop="flgOpeningInv">
            <template>
              <i-switch v-model="formData.flgOpeningInv">
                <span slot="open"></span>
                <span slot="close"></span>
              </i-switch>
            </template>
          </DkFormItem>
        </DkForm>
        <DkForm slot="content" ref="formInline3" v-model="formData" v-if="formData.flgOpeningInv">
          <!--  仓库名称  -->
          <DkFormItem prop="whId" :required="true">
            <SelectMagnifier v-model="formData.whId" :display-text="formData.whName"
                             :type="this.$config.MagnifierType.warehouse"
                             :multiple="false"></SelectMagnifier>
          </DkFormItem>
          <!--库存批号-->
          <DkFormItem prop="nonStdCode" :required="true">
            <InputPop ref="nonStdCode" v-model="formData.nonStdCode"/>
          </DkFormItem>
          <!--期初数量-->
          <DkFormItem prop="intoQty" :label="$t('openingIvtQty')" :required="true" data-type="number">
            <InputNumberPop ref="intoQty"
                            v-model="formData.intoQty"
                            :disabled="formData.unitId?!formData.flgSubUnit:true"
                            :digits="this.digits"
            />
          </DkFormItem>
          <!--期初成本价-->
          <DkFormItem prop="priceInto" :label="$t('openingIvtAmt')" :required="true" data-type="number">
            <InputNumberPop ref="priceInto" v-model="formData.priceInto"/>
          </DkFormItem>
        </DkForm>
      </DkPanel>

      <DkPanel prop="skuImages">
        <div id="search-cond-div-files-info" ref="search-cond-div-files-info" slot="content">
          <DkPicWall v-model="formData.skuImages"
                     :multiple="false"
                     :table="$config.tables.sku" :accept="$config.uploadFileConfig.acceptPicType"></DkPicWall>
          <span style="color:#95A8CB">图片最多传一张</span>
        </div>
      </DkPanel>

    </DkCollapse>

    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save1" @close="close"></DkSaveButton>
  </div>
</template>

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

export default {
  components: {},
  mixins: [formMixin],
  data() {
    return {
      digits: 3,
      //辅助单位是否显示
      showSubUnit: true,
      categoryList: [],
      seriesList: [],
      unitList: [],
      formData: {
        skuCode: null,
        skuModel: null,
        skuName: null,
        brandId: null,//商品品牌
        brandName: null,
        categoryId: null,//商品种类
        seriesId: null,//商品系列
        unitId: null,//计量单位
        skuSpec: null,//商品规格
        flgSubUnit: true,//辅助单位标识
        subUnitId: null,//辅助计量单位
        conversionFactor: null, //单位换算
        flgOpeningInv: false,//期初库存标识（编辑时不允许修改）
        nonStdCode: null,
        whId: null,
        whName: null,
        intoQty: null,//期初数量
        priceInto: null,//期初成本价
        flgPrice: false,//价格体系标识
        pricePurchase: 0, //采购价
        priceStandard: 0, //零售价
        priceWholesale: 0,//批发价
        priceLimited: 0, //销售售价
        priceOther: 0, //其他价
        remarks: null,
      },
    }
  },
  methods: {

    /**
     * @desc   : 辅助单位标识变更
     * @author : 常皓宁
     * @date   : 2024/5/24 13:36
     */
    changeSubUnit() {
      if (this.formData.flgSubUnit) {
        this.showSubUnit = true
      } else {
        this.showSubUnit = false
      }
    },


    /**
     * @desc   : 清空基本单位
     * @author : 常皓宁
     * @date   : 2024/5/27 10:46
     */
    unitClear(row) {
      if (row) {
        this.digits = row['decimalPlaces']
      }
      this.formData.subUnitId = null
      this.formData.conversionFactor = null
      this.formData.intoQty = null
    },

    /**
     * @desc   : 数据校验
     * @author : 常皓宁
     * @date   : 2024/3/2 9:51
     */
    save1() {
      this.$refs['formInline0'].validate().then(valid0 => {
        this.$refs['formInline1'].validate().then(valid1 => {
          if (!valid0 || !valid1) {
            return
          } else {
            if (this.$refs['formInline2']) {
              this.$refs['formInline2'].validate().then(valid2 => {
                if (!valid2) {
                  return
                } else if (!this.$refs['formInline3']) {
                  this.outSave()
                }
              })
            }
            if (this.$refs['formInline3']) {
              this.$refs['formInline3'].validate().then(valid3 => {
                if (!valid3) {
                  return
                } else if (!this.$refs['formInline2']) {
                  this.outSave()
                }
              })
            }
            if (this.$refs['formInline2'] || this.$refs['formInline3']) {
              this.$refs['formInline2'].validate().then(valid2 => {
                this.$refs['formInline3'].validate().then(valid3 => {
                  if (!valid2 || !valid3) {
                    return
                  } else {
                    this.outSave()
                  }
                })
              })
            }else{
              this.outSave()
            }
          }
        })
      })

    },

    /**
     * @desc   : 加载数据
     * @author : 宋扬
     * @date   : 2024/4/8 15:12
     */
    initData() {
      // 获取商品种类
      this.getGoodsCategory();
      // 获取商品系列
      this.getGoodsSeries();
      // 获取计量单位
      this.getGoodsUnit();
    },

    /**
     * @desc   : 获取商品种类
     * @author : 宋扬
     * @date   : 2024/4/8 15:13
     */
    getGoodsCategory() {
      this.excute(this.$service.goodsCategoryService, this.$service.goodsCategoryService.selectByCond, {}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.categoryList = res.data.list;
        }
      })
    },

    /**
     * @desc   : 获取商品系列
     * @author : 宋扬
     * @date   : 2024/4/8 15:18
     */
    getGoodsSeries() {
      this.excute(this.$service.goodsSeriesService, this.$service.goodsSeriesService.selectByCond, {}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.seriesList = res.data.list;
        }
      })
    },

    /**
     * @desc   : 获取计量单位
     * @author : 宋扬
     * @date   : 2024/4/8 15:20
     */
    getGoodsUnit() {
      this.excute(this.$service.unitService, this.$service.unitService.selectByCond, {}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.unitList = res.data.list;
        }
      })
    },

    /**
     * @desc   : 赋值信息
     * @author : 宋扬
     * @date   : 2024/4/8 16:41
     */
    setParams() {
      this.params = {...this.formData}
      this.params.orgId = this.$store.state.user.orgId
    },

    /**
     * @desc   : desc
     * @author : 宋扬
     * @date   : 2024/4/9 15:29
     */
    setValuesByEdit(data) {
      if (data) {
        this.formData = data;
      }
    },

    /**
     * @desc   : 通过id查询
     * @author : 宋扬
     * @date   : 2024/4/9 15:31
     */
    detail(id) {
      return this.excuteNoParam(this.$service.goodsService, this.$service.goodsService.selectById, [id], false);
    },

    /**
     * @desc   : 外部保存
     * @author : 常皓宁
     * @date   : 2024/5/24 16:37
     */
    outSave() {
      this.loading = true;
      // 2、给参数赋值
      this.setParams()
      // 3、保存数据
      this._saveData().then(result => {
        // 新建成功
        if (result.code === this.$config.SUCCESS_CODE) {
          // 提示信息
          this.$Message.success(this.$t('I_001', {'param': this.$t(this.typeData)}))
          // 新建清空当前窗体
          if (this.typeData === this.$config.formMode.add
            || this.typeData === this.$config.formMode.addTogether
            || this.typeData === this.$config.formMode.moldDamage) {
            this._clear();
          } else {
            // 如果是多个数据进行编辑不能关页面
            if (this.editKeys && this.editKeys.length > 1) {
              if (this.editIndex + 1 <= this.editKeys.length) {
                // 跳转到下一条数据
                this.editPageChange(this.editIndex + 1)
              }
            } else {
              // 单一页面编辑关闭窗体
              this.close(false);
            }
          }
        } else {
          // 如果不成功就提示错误信息
          this.$Message.warning(result.message)
        }
        this.loading = false
      });
    },

    /**
     * @desc   : 保存数据
     * @author : 宋扬
     * @date   : 2024/4/8 16:30
     */
    saveData() {
      console.log('this.params', this.params)
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.goodsService, this.$service.goodsService.insert, this.params);
      } else if (this.type === this.$config.formMode.edit) {
        return this.excute(this.$service.goodsService, this.$service.goodsService.update, this.params);
      }
    },

  },

  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 宋扬
   * @date   : 2024/4/9 15:30
   */
  created() {
    this.focusItem = 'skuId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'skuId'  // 设置主键Id
  },
}
</script>
