<script>
import Selector from "@/components/Selector/index.vue"
import Inputor from "@/components/Inputor/index.vue"
import Template from "@/views/cms/template/index.vue"
import { DICT_TYPE, getDictDatas } from "@/utils/dict"

export default {
  name: "PriceStep",
  components: { Template, Inputor, Selector },
  props: {
    index: Number,
    type: String,
    priceName: String,
    fieldPrefix: String,
    unitList: {
      type: Array,
      default: []
    },
    currencyList: {
      type: Array,
      default: []
    },
    showAdd: Boolean,
    readonly: Boolean,
    stepTips: String,
    value: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  created() {
    if (!this.value.packagingList) {
      this.addPackage()
    }
    // 格式化包装
    if (this.value.packagingList?.length) {
      this.value.packagingList.forEach((item) => {
        if (item.packagingTypes && typeof item.packagingTypes == "string") {
          item.packagingTypes = item.packagingTypes.split(",")
        }
      })
    }
    this.initSpecialPrice()
  },
  data() {
    return {}
  },
  computed: {
    packagingList() {
      const dicts = JSON.parse(JSON.stringify(getDictDatas(DICT_TYPE.ECW_PACKAGING_TYPE)))
      return dicts.map((dict) => {
        dict.enable = true
        this.value.packagingList.forEach((item) => {
          if (item.packagingTypes?.length && item.packagingTypes.indexOf(dict.value) > -1) {
            dict.enable = false
          }
        })
        return dict
      })
    }
  },
  methods: {
    getDictDatas,
    // 初始化特需加价
    initSpecialPrice() {
      if (!this.value.specialList) {
        this.$set(this.value, "specialList", [])
      }
      this.getDictDatas(this.DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS).forEach((item) => {
        if (!this.value.specialList.find((special) => special.specialDictType == item.value)) {
          this.value.specialList.push({
            [`${this.fieldPrefix}Price`]: undefined, // 新建默认给0，否则默认是null
            [`${this.fieldPrefix}PriceUnit`]: this.value[`${this.fieldPrefix}PriceUnit`],
            [`${this.fieldPrefix}VolumeUnit`]: this.value[`${this.fieldPrefix}VolumeUnit`],
            specialDictType: item.value
          })
        }
      })
    },
    // 添加包装类型运费
    addPackage() {
      if (!this.value.packagingList) {
        this.$set(this.value, "packagingList", [])
      }
      this.value.packagingList.push({
        packagingPrice: undefined,
        packagingPriceUnit: this.value[`${this.fieldPrefix}PriceUnit`],
        packagingVolumeUnit: this.value[`${this.fieldPrefix}VolumeUnit`]
      })
    },
    // 删除包装类型运费
    deletePackage(index) {
      this.value.packagingList.splice(index, 1)
    },
    // 校验
    validate() {
      const index = this.index
      const errors = []
      // 区间设置检查
      if (typeof this.value.startNum != "number") {
        errors.push(
          this.$t("请设置{priceName}第{index}阶段的起始值", {
            index: index + 1,
            priceName: this.priceName
          })
        )
      }
      if (!this.value.endNum) {
        errors.push(
          this.$t("请设置{priceName}第{index}阶段的结束值", {
            index: index + 1,
            priceName: this.priceName
          })
        )
      }
      // 价格检查
      if (!this.validatePrice(this.value[`${this.fieldPrefix}Price`])) {
        errors.push(
          this.$t("请设置第{index}阶段的{priceName}", {
            index: index + 1,
            priceName: this.priceName
          })
        )
      }
      // 包装价格检查
      if (this.value.packagingList?.length) {
        this.value.packagingList.forEach((item, i) => {
          if (item.packagingTypes?.length && !this.validatePrice(item.packagingPrice)) {
            errors.push(
              this.$t("请设置第{index}阶段的包装类型{i}的{priceName}", {
                index: index + 1,
                i: i + 1,
                priceName: this.priceName
              })
            )
          }
        })
      }
      if (errors.length) {
        this.$notify.error({
          title: this.$t("表单错误"),
          message: errors.join(";\n")
        })
      }
      if (errors.length) {
        this.$notify.error({
          title: this.$t("表单错误"),
          message: errors.join(";\n")
        })
      }
      return !errors.length
    },
    // 校验价格是否为空，可以是0
    validatePrice(value) {
      if (value === undefined || value === null || value === "") {
        return false
      }
      return true
    }
  }
}
</script>

<template>
  <div>
    <div class="bold text-lg">{{ $t("{type}{priceName}价格设置", { type, priceName }) }}</div>
    <div style="font-size: 14px; margin: 10px 0">
      {{ $t("第{index}阶梯定价方案", { index: index + 1 }) }}：
      <template v-if="showAdd">
        <el-link type="primary" @click.native="$emit('add', fieldPrefix)">{{ $t("添加区间") }}</el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link type="danger" @click.native="$emit('delete', index)">{{ $t("删除") }}</el-link>
      </template>
    </div>
    <el-form-item :label="$t('第{index}阶梯', { index: index + 1 })">
      <el-input-number v-model="value.startNum" :controls="false" class="w-100"></el-input-number>
      -
      <el-input-number v-model="value.endNum" :controls="false" class="w-100"></el-input-number>
      /
      <!--需求为以默认价格单位为准，不能修改阶梯单位 https://zentao.test.jdshangmen.com/bug-view-5982.html-->
      <selector
        disabled
        v-model="value.weightUnit"
        :options="unitList"
        :label-field="$l(null, 'title')"
        @input="
          $emit('changeUnit', {
            value: $event,
            field: 'weightUnit',
            type: fieldPrefix
          })
        "
        value-field="id"
        class="w-100"
      />
      <div class="tips" v-if="stepTips">{{ stepTips }}</div>
    </el-form-item>
    <el-form-item :label="$t('默认') + priceName">
      <el-input-number v-model="value[`${fieldPrefix}Price`]" :placeholder="$t('整数或者两位小数')" :precision="2" :controls="false" class="w-100 mr-10" />
      <selector
        :disabled="index > 0"
        v-model="value[`${fieldPrefix}PriceUnit`]"
        :options="currencyList"
        :label-field="$l(null, 'title')"
        @input="
          $emit('changeUnit', {
            value: $event,
            field: `${fieldPrefix}PriceUnit`
          })
        "
        value-field="id"
        class="w-100"
      />
      /
      <selector
        :disabled="index > 0"
        v-model="value[`${fieldPrefix}VolumeUnit`]"
        :options="unitList"
        :label-field="$l(null, 'title')"
        @input="
          $emit('changeUnit', {
            value: $event,
            field: `${fieldPrefix}VolumeUnit`
          })
        "
        value-field="id"
        class="w-100"
      />
    </el-form-item>

    <!--特性加价-->
    <template v-for="(special, specialIndex) in value.specialList">
      <el-form-item :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + priceName + $t('加价')" :key="specialIndex + 'transport'">
        <el-input-number v-model.number="special[`${fieldPrefix}Price`]" :controls="false" :placeholder="$t('整数或者两位小数')" class="w-100 mr-10" />
        <selector disabled v-model="special[`${fieldPrefix}PriceUnit`]" :options="currencyList" :label-field="$l(null, 'title')" value-field="id" defaultable2 class="w-100 mr-10" />
        <span class="mr-10">/</span>
        <selector disabled v-model="special[`${fieldPrefix}VolumeUnit`]" :options="unitList" :label-field="$l(null, 'title')" value-field="id" defaultable2 class="w-100" />
      </el-form-item>
    </template>

    <!--包装类型价格-->
    <template v-for="(item, i) in value.packagingList">
      <el-form-item :label="$t('包装类型加价') + (i + 1)" :key="i">
        <template #label>
          <div class="el-form-item__label" style="width: 150px">{{ $t("包装类型{name}加价", { name: priceName }) + (i + 1) }}</div>
          <div v-if="!item.packagingTypes || !item.packagingTypes.length" class="tips">{{ $t("未选择包装类型将被忽略") }}</div>
        </template>
        <el-select v-model="item.packagingTypes" multiple placeholder="请选择" style="width: 100%; max-width: 450px; margin-bottom: 5px; display: block">
          <el-option v-for="item in packagingList" :key="item.value" :label="$l(item, 'label')" :value="item.value" :disabled="!item.enable"> </el-option>
        </el-select>
        <el-input-number v-model="item.packagingPrice" :controls="false" :placeholder="$t('整数或者两位小数')" class="w-100 mr-10" />
        <selector disabled v-model="item.packagingPriceUnit" :options="currencyList" :label-field="$l(null, 'title')" value-field="id" defaultable2 class="w-100 mr-10" />
        <span class="mr-10">/</span>
        <selector disabled v-model="item.packagingVolumeUnit" :options="unitList" :label-field="$l(null, 'title')" value-field="id" defaultable2 class="w-100" />
        <template v-if="i == value.packagingList.length - 1 && !readonly">
          <el-link type="primary" @click.native="addPackage" class="ml-5">{{ $t("添加") }}</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link type="danger" @click.native="deletePackage(i)">{{ $t("删除") }}</el-link>
        </template>
      </el-form-item>
    </template>
  </div>
</template>

<style scoped lang="scss">
.bold {
  font-weight: bold;
}
.text-lg {
  font-size: 1.3rem;
}
.tips {
  font-size: 1rem;
  color: red;
}
</style>
