<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <products-selector ref="productSelector" v-model="form.productIdList" show-all @setall="isAllProduct=$event"
                         enable-filtered @setFiltered="isAllFilteredProduct=$event"
                         :default-ids="form.productIdList" class="mb-20"/>

      <routers-selector v-model="selectedRoutes" :type="type" />

      <el-card style="margin-bottom: 10px">
        <div slot="header" style="font-size:20px;">
          {{$t('价格设置')}}
        </div>
        <div :gutter="20">
            <el-form-item :label="$t('单价模式')" prop="priceType">
              <dict-selector :type="DICT_TYPE.ECW_PRICE_TYPE" v-model="form.priceType" form-type="radio" />
              <!--海运才需要是否含阶梯价的选项，空运只有阶梯价就不需要了-->
              <div v-if="type == 'sea'">
                <el-checkbox v-model="form.stepPrice" :true-label="1" :false-label="0">{{$t('是否含阶梯价')}}</el-checkbox>
              </div>
            </el-form-item>

            <el-form-item :label="$t('默认全包价')" v-if="form.priceType == 1">
              <inputor default2="0" v-model.number="form.allPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
              <selector v-model="form.allPriceUnit" @input="syncAllUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
              / <selector v-model="form.allVolumeUnit" @input="syncAllUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            </el-form-item>
            <template v-else>
              <el-form-item :label="$t('默认运费')" prop="transportPrice">
                <selector v-model="form.transportPriceUnit" @input="syncAllUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                <inputor default2="0" v-model.number="form.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w-100 ml-10 mr-10" />
                / <selector v-model="form.transportVolumeUnit" @input="syncAllUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
              </el-form-item>
              <el-form-item :label="$t('默认清关费')" prop="clearancePrice" v-if="type != 'air'">
                <selector v-model="form.clearancePriceUnit" @input="syncAllUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                <inputor default2="0" v-model.number="form.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" class="w-100 ml-10 mr-10" />
                / <selector v-model="form.clearanceVolumeUnit" @input="syncAllUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
              </el-form-item>
            </template>

            <!--特需-->
            <template v-if="form.priceType==1">
              <el-form-item
                v-for="(special, specialIndex) in form.specialList"
                :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('全包价')"
                :key="specialIndex + 'transport'">
                <selector disabled v-model="special.allPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                <inputor default2="0" v-model.number="special.allPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w-100 ml-10 mr-10" />
                / <selector disabled v-model="special.allVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
              </el-form-item>
            </template>
            <template v-else v-for="(special, specialIndex) in form.specialList">
              <el-form-item
                :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('运费')"
                :key="specialIndex + 'transport'">
                <selector disabled v-model="special.transportPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                <inputor default2="0" v-model.number="special.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w-100 ml-10 mr-10" />
                / <selector disabled v-model="special.transportVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
              </el-form-item>
              <el-form-item
                v-if="type != 'air'"
                :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('清关费')"
                :key="specialIndex + 'clearance'">
                <selector disabled v-model="special.clearancePriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                <inputor default2="0" v-model.number="special.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" class="w-100 ml-10 mr-10" />
                / <selector disabled v-model="special.clearanceVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
              </el-form-item>
            </template>
        </div>
      </el-card>
    </el-form>

    <div style="margin: 20px 0">
      <el-button @click="submitForm" type="primary" :loading="loading">{{$t('确认提交')}}</el-button>
      <el-button type="default" @click="$router.back()">{{$t('返回上一页')}}</el-button>
    </div>
  </div>
</template>
<script>
import RoutersSelector from '@/components/RoutersSelector'
import {batchAddPrice, batchUpdateProductPrice, getProductPrice} from "@/api/ecw/productPrice";
import { getCurrencyList } from '@/api/ecw/currency';
import { getUnitList } from '@/api/ecw/unit';
import ProductsSelector from '@/components/ProductsSelector'
import Selector from '@/components/Selector'
import Inputor from '@/components/Inputor'
import Decimal from 'decimal.js'

export default {
  components: { RoutersSelector, ProductsSelector, Selector, Inputor },
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {
        priceType: '0',
        specialList: [],
        stepPrice: 0
      },
      isAllProduct: false, // 是否全部商品
      isAllFilteredProduct: false, // 是否全部篩選商品
      specialProducts: [],
      rules: {},
      product: null,
      currencyList: [],
      unitList: [],
      productTypeList: [],
      productDisabled: true,
      lineList: [], //路线数组
      loading: false,
      // 批量加价/减价
      quickForm:{}
    }
  },
  computed: {
    // 类型，默认海运sea,air表示空运
    type(){
      return this.$route.path.split(/[-_]/).pop()
    },
    // 默认运费的货币和体积单位
    currencyAndUnit(){
      let currency = null, unit = null, fields = null
      // 如果是阶梯价格则取第一阶梯,否则就取form中的字段
      let obj = this.form.stepPrice == 1 ? this.form.priceStepList[0] : this.form
      // 全包价
      if(this.form.priceType == 1){
        currency = obj.allPriceUnit
        unit = obj.allVolumeUnit
      }else{
        currency = obj.transportPriceUnit
        unit = obj.transportVolumeUnit
      }

      return {currency, unit}
    }
  },
  watch: {
    checkList() { //选择路线
      if (this.checkList.length > 0) {
        this.form.lineChannelList = this.checkList.map(item => {
          return { lineId: item, shippingChannelId: 0 }
        })
      } else {
        this.form.lineChannelList = []
      }
    },
    product() {
      this.$set(this.form, 'productType', this.product.typeId)
    },
    selectedRoutes(routers) {
      let transportIds = []
      routers.forEach(item => {
        item.shippingChannelId = item.channelId
        transportIds.push(+item.transportId)
      })

      // 如果只选择了空运（3），则默认体积单位改成千克
      transportIds = new Set(transportIds)
      console.log(transportIds)
      window.transportIds = transportIds
      if(transportIds.size == 1 && transportIds.has(3)){
        this.setDefaultVolumeUnit(6)
      }else this.setDefaultVolumeUnit(7)
    }
  },
  async created() {
    getCurrencyList().then(res => this.currencyList = res.data)
    getUnitList().then(res => this.unitList = res.data)

    this.$nextTick(async() => {
      this.setDefaultVolumeUnit(this.type == 'air' ? 6 : 7)
    })

    this.getDictDatas(this.DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS).forEach(item => {
        // 没有的才push，已有的可能是从复制模板携带过来的数据
        if(!this.form.specialList.find(special => special.specialDictType == item.value)) {
          this.form.specialList.push({
            "clearancePrice": null,
            "clearancePriceUnit": null,
            "clearanceVolumeUnit": null,
            "specialDictType": item.value,
            "transportPrice": null,
            "transportPriceUnit": null,
            "transportVolumeUnit": null,
          })
        }
    })
  },
  methods: {
    // 同步全部单位
    syncAllUnit(){
      let obj = this.form
      let fields = {}
      // 全包价
      if(this.form.priceType == 1){
        fields = {
          allPriceUnit: obj['allPriceUnit'],
          allVolumeUnit: obj['allVolumeUnit']
        }
      }else{
        fields = {
          transportPriceUnit:  obj.transportPriceUnit,
          transportVolumeUnit: obj.transportVolumeUnit,
          clearancePriceUnit:  obj.clearancePriceUnit,
          clearanceVolumeUnit: obj.clearanceVolumeUnit,
        }
      }

      // 全包价还需要同步阶梯的重量单位
      if(this.form.stepPrice == 1){
        fields['weightUnit'] = obj.weightUnit
      }

      this.syncSpecialUnit(fields)
    },
    // 同步特需的货币单位和体积单位
    syncSpecialUnit(obj){
      console.log('syncSpecialUnit', obj)
      if(!obj) return
      // 同步特需单位
      this.form.specialList.forEach(item => {
        Object.assign(item, obj)
      })

      // 如果是阶梯价则需要同步其他阶梯
      if(this.form.stepPrice == 1){
        this.form.priceStepList.forEach((item, index) => {
          this.$set(this.form.priceStepList, index, Object.assign(item, obj))
        })
      }

      // 不是阶梯价需要 同步最小起计量
      if(obj['transportVolumeUnit'] || obj['allVolumeUnit']){
        this.$set(this.form, 'minWeightUnit', obj['transportVolumeUnit'] || obj['allVolumeUnit'])
      }
    },
    // 价格校验器
    priceValidator(rule, value, callback){
      if(!value || value == '') return callback()
      value = parseFloat(value)
      if(!value || value < 0){
        return callback(new Error('价格错误'))
      }
      callback()
    },
    setDefaultVolumeUnit(unit){
      this.$set(this.form, 'transportVolumeUnit', unit)
      this.$set(this.form, 'clearanceVolumeUnit', unit)
      this.$set(this.form, 'allVolumeUnit', unit)
      this.$set(this.form, 'minWeightUnit', unit)
      console.log(this.form.priceStepList, this.form.stepPrice)
      // 阶梯价
      if(this.form.stepPrice == 1 && this.form.priceStepList?.length){
        this.form.priceStepList.forEach(item => {
          this.$set(item, 'transportVolumeUnit', unit)
          this.$set(item, 'clearanceVolumeUnit', unit)
          this.$set(item, 'allVolumeUnit', unit)
          this.$set(item, 'weightUnit', unit)
        })
      }
    },
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) {
          return;
        }

        // 只有新增的时候做判断
        if (!this.$route.query.ids && (!this.selectedRoutes || !this.selectedRoutes.length)) {
          this.$message.error(this.$t('请选择线路'));
          return;
        }

        let data = Object.assign({}, this.form, {
          // lineChannelList: this.selectedRoutes,
          // specialList: this.specialProducts,
          isAllProduct: this.isAllProduct ? 1:0
        })

        // 如果是勾選了全部篩選商品，則獲取商品ID
        if(this.isAllFilteredProduct){
          data.productIdList = await this.$refs.productSelector.getFilteredIds()
        }
        if(!data.isAllProduct && (!data.productIdList || !data.productIdList.length)){
          return this.$message.error(this.$t('请选择商品') + "!")
        }

        data.lineChannelList = this.selectedRoutes

        if(data.lineChannelList.length < 1){
          return this.$message.error(this.$t('请选择需要修改的路线'))
        }
        await this.$confirm(this.$t('已选择{route}条路线，{product}个商品；确认提交修改？', {
          route: data.lineChannelList.length,
          product: this.isAllProduct ? this.$refs.productSelector.allTotal : data.productIdList.length
        }))
        this.loading = true
        batchAddPrice(data).then(async(response) => {
          await this.$alert(this.$t("操作成功"));
          this.$store.dispatch("tagsView/delCurrentView")
        })
        .finally(res => {
          this.loading = false
        })
      });
    }
  }
}
</script>
<style scoped>
.w100{
  width: 100px;
}
.mr10{
  margin-right: 10px;
}
</style>
