<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" :default-ids="form.productIdList" enable-filtered @setFiltered="isAllFilteredProduct=$event" class="mb-20" />

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

      <el-card style="margin-bottom: 10px">
        <div slot="header" style="font-size:20px;">
          {{$t('价格设置')}}
          <!--空运只有阶梯价格，不显示阶梯价格勾选-->
          <span v-if="type != 'air'">
            <el-checkbox label="" @change="form.stepPrice=$event ? 1 : 0">{{$t('阶梯价格')}}</el-checkbox>
          </span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('预付')" prop="needPay" >
              <el-radio-group v-model="form.needPay">
                <el-radio :label="1">{{ $t('预付') }}</el-radio>
                <el-radio :label="0">{{ $t('均可') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('单价模式')" prop="priceType">
              <dict-selector :type="DICT_TYPE.ECW_PRICE_TYPE" v-model="form.priceType" form-type="radio" formatter='number' />
            </el-form-item>
            <el-form-item
              :label="$t('最小起计量')"
              :prop="`minWeight`"
            >
              <inputor default2="0" v-model.number="form.minWeight" type="number" class="w-100" :rules="{validator: priceValidator, trigger: 'blur',   message: '数量错误'}"/>
              / <selector v-model="form.minWeightUnit" :options="unitList" :label-field="$l(null, 'title')" value-field="id" defaultable2  class="w-100" disabled />
            </el-form-item>

            <!--阶梯订单-->
            <template v-if="form.stepPrice==1" >
              <div v-for="(item, index) in form.priceStepList" :key="index">
                <div style="font-size:14px; margin:10px 0">
                  {{$t('第{index}阶梯定价方案', {index: index+1})}}：
                  <template v-if="index == form.priceStepList.length - 1">
                    <el-link type="primary" @click.native="form.priceStepList.push({})">{{$t('添加区间')}}</el-link>
                    <el-divider v-if="index" direction="vertical"></el-divider>
                    <el-link v-if="index" type="danger" @click.native="form.priceStepList.splice(index, 1)">{{$t('删除')}}</el-link>
                  </template>
                </div>

                <div v-if="willBeIgnore(item)" style="color:red">{{$t('此阶梯未设置阶梯和价格，将会被忽略')}}</div>
                <div v-else-if="!isStepPriceOk(item)" style="color:red">{{$t('此阶梯价信息设置不完整')}}</div>

                <el-form-item :label="$t(`第{index}阶梯`, {index: index+1})">
                  <el-input v-model="item.startNum" type="number" placeholder="" class="w100"></el-input>
                  -
                  <el-input v-model="item.endNum" type="number" placeholder="" class="w100"></el-input>
                  /
                  <selector :disabled="index > 0" @input="syncAllUnit" v-model="item.weightUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                </el-form-item>
                <el-form-item :label="$t('默认运费')" v-if="form.priceType != 1"  :key="`transportPrice-${index}`">
                  <inputor default2="0" v-model.number="item.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
                  <selector  :disabled="index > 0" @input="syncAllUnit" v-model="item.transportPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                  / <selector  :disabled="index > 0" @input="syncAllUnit" v-model="item.transportVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                </el-form-item>
                <el-form-item :label="$t('默认清关费')" v-if="form.priceType != 1 && type != 'air'">
                  <inputor default2="0" v-model.number="item.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
                  <selector :disabled="index > 0" @input="syncAllUnit" v-model="item.clearancePriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                  / <selector :disabled="index > 0" @input="syncAllUnit" v-model="item.clearanceVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                </el-form-item>

                <el-form-item :label="$t('默认全包价')" v-if="form.priceType == 1" :key="`allPrice-${index}`">
                  <inputor default2="0" v-model.number="item.allPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
                  <selector :disabled="index > 0" @input="syncAllUnit" v-model="item.allPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                  / <selector :disabled="index > 0" @input="syncAllUnit" v-model="item.allVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
                </el-form-item>
              </div>
            </template>
            <!--非阶梯订单-->
            <template v-else>

              <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>

            <!--特需-->
            <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>

            <!-- <el-form-item :label="$t('是否预付')" prop="advanceStatus">
              <dict-selector form-type="radio" :type="DICT_TYPE.ADVANCE_STATUS" v-model="form.advanceStatus" />
            </el-form-item> -->
            <el-form-item :label="$t('价格有效期')">
              <el-date-picker v-model="form.validateStartDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
              -
              <el-date-picker v-model="form.validateEndDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.stepPrice">
            <h2>{{$t('快捷设置')}}</h2>
            <div class="flex items-center">
              {{$t('批量加价')}}+
              <el-input v-model="quickForm.plus" class="w-100 ml-10 mr-10" :disabled="!!quickForm.minus"></el-input>
              <selector disabled v-model="currencyAndUnit.currency" :options="currencyList" :label-field="$l('title')" value-field="id" class="w-100" />
              / <selector disabled v-model="currencyAndUnit.unit" :options="unitList" :label-field="$l('title')" value-field="id" class="w-100" />
              <div class="ml-10">{{$t('*针对所有价格加价')}}</div>
            </div>
            <div class="flex items-center mt-10">
              {{$t('批量减价')}} -
              <el-input v-model="quickForm.minus" class="w-100 ml-10 mr-10" :disabled="!!quickForm.plus"></el-input>
              <selector disabled v-model="currencyAndUnit.currency" :options="currencyList" :label-field="$l('title')" value-field="id" class="w-100" />
              / <selector disabled v-model="currencyAndUnit.unit" :options="unitList" :label-field="$l('title')" value-field="id" class="w-100" />
              <div class="ml-10">{{$t('*针对所有价格加价')}}</div>
            </div>
            <div class="mt-10">
              <el-button @click="quickSet" type="primary" :disabled="!quickForm.plus && !quickForm.minus">{{$t('确定')}}</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>


      <el-card>
        <div slot="header" style="font-size:20px;">
          {{$t('基础信息')}}
        </div>

        <el-form-item :label="$t('是否预约入仓')" prop="needBook">
          <el-radio v-model.number="form.needBook" :label="1">{{$t('是')}}</el-radio>
          <el-radio v-model.number="form.needBook" :label="0">{{$t('否')}}</el-radio>
        </el-form-item>

        <!--下面几个字段只有批量设置海运才需要-->
        <template v-if="type == 'sea'">
          <el-form-item :label="$t('每日入仓上限')" prop="dayLimit" v-if="form.needBook == 1">
            <el-input v-model.number="form.dayLimit" type="number" class="w-100" />{{$t('立方米')}}
          </el-form-item>

          <el-form-item :label="$t('货柜位置')" prop="containerLocation">
            <dict-selector :type="DICT_TYPE.ECW_CONTAINER_LOCATION" v-model="form.containerLocation" />
          </el-form-item>

          <el-form-item :label="$t('订单方数上限')" prop="square">
            <el-input v-model.number="form.square" type="number" style="width:200px" />
          </el-form-item>
        </template>

        <el-form-item :label="$t('是否单询')" prop="inquiry">
          <dict-selector :type="DICT_TYPE.NEED_ORDER_INQUIRY" v-model="form.needOrderInquiry" form-type="radio" formatter="number"></dict-selector>
        </el-form-item>
      </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 {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'
import {getProduct} from "@/api/ecw/product";

export default {
  components: { RoutersSelector, ProductsSelector, Selector, Inputor },
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {
        specialList: [],
        priceStepList: [],
        stepPrice: 0,
        priceType: null
        // advanceStatus: 0,
        // needBook: 0,
        // dayLimit: 10000
      },
      isAllProduct: false, // 是否全部商品
      isAllFilteredProduct: false, // 是否勾選全部搜索結果
      specialProducts: [],
      // priceStepList: [{},{}], // 阶梯价格
      // specialList:[], // 特殊需求,默认四个
      rules: {},
      product: null,
      /* productType: null, */
      currencyList: [],
      unitList: [],
      productTypeList: [],
      productDisabled: true,
      lineList: [], //路线数组
      loading: false,
      // 批量加价/减价
      quickForm:{}
    }
  },
  computed: {
    // 类型，默认海运sea,air表示空运
    type(){
      let type = this.$route.path.split(/[-_]/).pop()
      if(type == 'air' || type == 'sea') return type
      return null
    },
    // 默认运费的货币和体积单位
    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}
    },
    // 判断是否空值
    isEmpty(){
      return (content) => {
        return !content && content !== 0 && content !== '0'
      }
    },
    // 判断某个阶梯价是否会被忽略
    willBeIgnore(){
      return (stepPrice) => {
        if(!this.isEmpty(stepPrice.startNum) || !this.isEmpty(stepPrice.endNum)) return false
        if(this.form.priceType == 1 && !this.isEmpty(stepPrice.allPrice)) return false
        if(this.form.priceType != 1 && !this.isEmpty(stepPrice.transportPrice) && !this.isEmpty(stepPrice.clearancePrice)) return false
        return true
      }
    },
    // 判断阶梯价是否设置不完整
    isStepPriceOk(){
      return (stepPrice) => {
        console.log({
          stepPrice,
          startNum: this.isEmpty(stepPrice.startNum),
          endNum:this.isEmpty(stepPrice.endNum),
          allPrice: this.isEmpty(stepPrice.allPrice),
          allPriceUnit: this.isEmpty(stepPrice.allPriceUnit),
          allVolumeUnit: this.isEmpty(stepPrice.allVolumeUnit),
          transportPrice: this.isEmpty(stepPrice.transportPrice),
          transportPriceUnit: this.isEmpty(stepPrice.transportPriceUnit),
          transportVolumeUnit: this.isEmpty(stepPrice.transportVolumeUnit),
          priceType: this.form.priceType
        })
        if(this.isEmpty(stepPrice.startNum) || this.isEmpty(stepPrice.endNum)) return false
        if(this.form.priceType == 1 && (this.isEmpty(stepPrice.allPrice) || this.isEmpty(stepPrice.allPriceUnit) || this.isEmpty(stepPrice.allVolumeUnit))){
          console.log('全包价设置不完整')
          return false
        }
        else if(this.form.priceType != 1 && (this.isEmpty(stepPrice.transportPrice) || this.isEmpty(stepPrice.transportPriceUnit) || this.isEmpty(stepPrice.transportVolumeUnit))){ // 清关费可能为0或者空
          console.log('非全报价，未设置完整')
          return false
        }
        return true
      }
    },
  },
  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)
    },
    'form.stepPrice'(stepPrice){
      if(stepPrice == 1 && !this.form.priceStepList.length){
        this.form.priceStepList = [{}, {}]
      }
    },
    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)
    },
    'form.needBook'(val){
      if(val) this.$set(this.form, 'dayLimit', 10000)
      else delete this.form.dayLimit
    },
  },
  async created() {
    getCurrencyList().then(res => this.currencyList = res.data)
    getUnitList().then(res => this.unitList = res.data)

    await this.$nextTick()
    // 如果是空运，阶梯价格默认为1
    if(this.type == 'air'){
      this.$set(this.form, 'stepPrice', 1)
    }

    // 默认单位，空运千克，海运立方米
    this.setDefaultVolumeUnit(this.type == 'air' ? 6 : 7)

    // 如果是复制，则获取数据并填充，先复制，然后填充特需，避免数据的特需不全导致部分不显示
    if(this.$route.query.templateId){
      await this.getTemplateDetail(this.$route.query.templateId)
    }

    // 从价格中获取特需的默认单位
    const obj = (this.form.stepPrice ? this.form.priceStepList[0] : this.form) || {}
    this.getDictDatas(this.DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS).forEach(item => {
        // 没有的才push，已有的可能是从复制模板携带过来的数据
        if(!this.form.specialList.find(special => special.specialDictType == item.value)) {
          console.log('特需push', item.value)
          this.form.specialList.push({
            "clearancePrice": null,
            "clearancePriceUnit": obj.clearancePriceUnit,
            "clearanceVolumeUnit": obj.clearanceVolumeUnit,
            "specialDictType": item.value,
            "transportPrice": null,
            "transportPriceUnit": obj.transportPriceUnit,
            "transportVolumeUnit": obj.transportVolumeUnit,
          })
        }else console.log('已存在特需', item.value)
    })


  },
  methods: {
    // 获取模板数据(复制的源路线价格信息)
    async getTemplateDetail(id){
      const res = await getProductPrice(id)
      // 填充商品、线路、价格信息、出货渠道（空运）
      // this.form.productIdList = [res.data.productId]
      /* 23-11-07要求不复制商品和线路 https://zentao.test.jdshangmen.com/bug-view-5145.html
      this.selectedRoutes = [{
        "lineId": res.data.warehouseLineId,
        "channelId": res.data.shippingChannelId,
        "transportId": res.data.warehouseLineDO.transportType,
        "shippingChannelId":res.data.channelId
      }]*/
      // 要复制过来的字段
      const {
        allPrice,
        allPriceUnit,
        allVolumeUnit,
        transportPrice,
        transportPriceUnit,
        transportVolumeUnit,
        clearancePrice,
        clearancePriceUnit,
        clearanceVolumeUnit,
        priceType,
        stepPrice,
        specialList,
        priceStepList,
        minWeight,
        minWeightUnit,
        needOrderInquiry,
        needBook,
        needPay
      } = res.data

      const data = {
        allPrice,
        allPriceUnit,
        allVolumeUnit,
        transportPrice,
        transportPriceUnit,
        transportVolumeUnit,
        clearancePrice,
        clearancePriceUnit,
        clearanceVolumeUnit,
        priceType,
        stepPrice,
        specialList,
        priceStepList,
        minWeight,
        minWeightUnit,
        needOrderInquiry,
        needBook,
        needPay
      }
      // 海运需要填充货柜位置和订单方数上限
      if(this.type == 'sea'){
        data.containerLocation = res.data.containerLocation
        data.square = res.data.square
      }
      this.$set(this, 'form', Object.assign({}, this.form, data))

      // 产品选择器默认选择的商品
      /* 23-11-07要求不复制商品和线路 https://zentao.test.jdshangmen.com/bug-view-5145.html
      getProduct(res.data.productId).then(res => {
        this.$refs.productSelector.choose(res.data)
      })*/
    },
    // 同步全部单位
    syncAllUnit(){
      let obj = this.form.stepPrice == 1 ? this.form.priceStepList[0] : 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('请选择商品')
        }
        /* if(this.form.stepPrice == 1){
          data.priceStepList = this.form.priceStepList
        } */
        // 没有设置阶梯价格则不提交priceStepList
        if(data.stepPrice != 1){
          delete data.priceStepList
        }else{
          // 根据23-11-23 21点左右的群讨论，阶梯价如果留空则不提交，如果全部为空则不提交此字段
          // 相关工单 https://zentao.test.jdshangmen.com/bug-view-5460.html

          // 填写不完整的给提示
          let notOk = []
          data.priceStepList.forEach((item, index) => {
            if(!this.willBeIgnore(item) && !this.isStepPriceOk(item)){
              notOk.push(index + 1)
            }
          })
          if(notOk.length){
            return this.$confirm(this.$t("第{steps}阶梯设置不完整", {steps: notOk.join(",")}))
          }
          // 删除未填写的阶梯价
          data.priceStepList = data.priceStepList.filter(item => {
            return !this.willBeIgnore(item)
          })
          if(!data.priceStepList.length){
            delete data.priceStepList
          }
        }

        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
        batchUpdateProductPrice(data).then(response => {
          this.$modal.msgSuccess(this.$t("修改成功"));
          this.$router.replace('/lineProject/product-price?' + (new URLSearchParams(this.$route.query)).toString())
        })
        .finally(res => this.loading = false)
      });
    },
    // 快捷设置,只更新默认运费
    quickSet(){
      // 字段，根据是否全包价来取
      let field = this.form.priceType == 1 ? 'allPrice' : 'transportPrice'
      // 取得要加的数额（减少则是负数）
      let amount = Decimal(this.quickForm.plus || -this.quickForm.minus)
      this.form.priceStepList.forEach(item => {
        // 加上对应的价格，但是不能小于0
        this.$set(item, field, Math.max(0, Decimal(item[field] || 0).plus(amount).toNumber()))
      })
    }
  }
}
</script>
<style scoped>
.w100{
  width: 100px;
}
.mr10{
  margin-right: 10px;
}
</style>
