<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" :disabled="readonly">

      <el-form-item :label="$t('商品类型')" prop="productType">
        <el-select v-model="form.productType" :disabled="!!$route.query.action">
          <el-option
            v-for="type in productTypeList"
            :key="type.id"
            :label="$l(type, 'title')"
            :value="type.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('商品名称')" prop="titleZh">
        <product-selector v-model="form.productId" :product-type="form.productType" @change="product = $event" :disabled="!!$route.query.action" />
      </el-form-item>

      <el-form-item :label="$t('英文名称')" prop="titleEn">
        <el-input :value="product ? product.titleEn : ''" disabled />
      </el-form-item>

      <!--单条路线修改-->
      <!-- <el-form-item :label="$t('路线')" prop="lineChannelList" v-if="!$route.query.ids">
        <el-input
          v-for="item in lineList"
          :key="item.lineId"
          :value="'【' + getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType) + '】从【' + item.warehouseLineDO.startTitleZh + '】发往【' + item.warehouseLineDO.destTitleZh + '】'"
          disabled/>
      </el-form-item>-->
      <!--多条路线批量修改-->
        <template  v-if="lineList.length">
          <el-form-item :label="$t('路线')" prop="lineChannelList">
            <template v-if="lineList.length == 1">
              <el-input
              v-for="(item, index) in lineList"
              :key="index"
              :value="!item.warehouseLineDO ? $t('数据异常,缺少warehouseLineDO字段') : $t('【{transport}】从【{from}】发往【{to}】', {
                transport: getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType),
                from: $l(item.warehouseLineDO, 'startTitle'),
                to: $l(item.warehouseLineDO, 'destTitle')
              })"
              disabled />
            </template>
            <el-checkbox-group v-else v-model="checkList">
              <el-checkbox
              v-for="item in lineList"
              :key="item.id"
              :label="item.id"
              :disabled="!item.warehouseLineDO"
              style="display:block"
              >
                {{
                  !item.warehouseLineDO ? $t('数据异常,缺少warehouseLineDO字段') : $t('【{transport}】从【{from}】发往【{to}】', {
                    transport: getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType),
                    from: $l(item.warehouseLineDO, 'startTitle'),
                    to: $l(item.warehouseLineDO, 'destTitle')
                  })
                }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item v-if="type === 'air'" :label="$t('出货渠道')">
              {{channel ? $l(channel, 'name') : '/'}}
          </el-form-item>
        </template>
      <!--有路线则不显示路线选择器-->
      <routers-selector v-else v-model="selectedRoutes" :option="routerOption" :type="type" />

      <el-card style="margin-bottom: 10px">
        <div slot="header" style="font-size:20px;">
          {{$t('价格设置')}}
          <span>
            <el-checkbox v-if="$route.query.action != 'batchUpdate'" label="" v-model="needPay">{{$t('预付')}}</el-checkbox>
            <!--空运只有阶梯价格，所以不显示勾选-->
            <el-checkbox label="" v-model="stepPrice" v-if="type != 'air'">{{$t('阶梯定价')}}</el-checkbox>
          </span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('预付')" prop="needPay" v-if="$route.query.action == 'batchUpdate'" >
              <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" defaultable2 />
            </el-form-item>
						<el-form-item
							:label="$t('最小起计量')"
							:prop="`minWeight`"
						>
							<el-input-number v-model="form.minWeight" type="number" class="w-100" :controls="false"/>
							/ <selector v-model="form.minWeightUnit" :options="unitList" :label-field="$l(null, 'title')" value-field="id" defaultable2  class="w-100" disabled />
						</el-form-item>
          </el-col>
          <el-col :span="12">
            <quick-set :value="form" type="sea" :unit-list="unitList" :currency-list="currencyList"></quick-set>
          </el-col>
        </el-row>

        <!--如果是阶梯价-->
        <template v-if="form.stepPrice">
          <!--全包价-->
          <template v-if="form.priceType==1" >
            <div v-for="(item, index) in form.fullPriceStepList" :key="index">
              <price-step
                ref="stepPrice"
                :index="index"
                :currency-list="currencyList"
                :unit-list="unitList"
                field-prefix="all"
                :type="$t('海运')"
                :price-name="$t('全包价')"
                :show-add="index === form.fullPriceStepList.length -1 && !readonly"
                :value="item"
                :readonly="readonly"
                @add="handleAddPrice('fullPriceStepList', $event)"
                @delete="handleDeletePrice('fullPriceStepList', $event)"
                @changeUnit="handleUnitChange(form.fullPriceStepList, index, ...$event)"
              ></price-step>
            </div>
          </template>
          <el-row v-else :gutter="20" class="mt-20">
            <el-col :span="12">
              <div v-for="(item, index) in form.freightPriceStepList" :key="index">
                <price-step
                  ref="stepPrice"
                  :index="index"
                  :currency-list="currencyList"
                  :unit-list="unitList"
                  field-prefix="transport"
                  :type="$t('海运')"
                  :price-name="$t('运费')"
                  :show-add="index === form.freightPriceStepList.length -1 && !readonly"
                  :value="item"
                  :readonly="readonly"
                  @add="handleAddPrice('freightPriceStepList', $event)"
                  @delete="handleDeletePrice('freightPriceStepList', $event)"
                  @changeUnit="handleUnitChange(form.freightPriceStepList, index, ...$event)"
                ></price-step>
              </div>
            </el-col>
            <el-col :span="12">
              <div v-for="(item, index) in form.clearancePriceStepList" :key="index">
                <price-step
                  ref="stepPrice"
                  :index="index"
                  :currency-list="currencyList"
                  :unit-list="unitList"
                  field-prefix="clearance"
                  :type="$t('海运')"
                  :price-name="$t('清关费')"
                  :show-add="index === form.clearancePriceStepList.length -1 && !readonly"
                  :value="item"
                  :readonly="readonly"
                  @add="handleAddPrice('clearancePriceStepList', $event)"
                  @delete="handleDeletePrice('clearancePriceStepList', $event)"
                  @changeUnit="handleUnitChange(form.clearancePriceStepList, index, ...$event)"
                ></price-step>
              </div>
            </el-col>
          </el-row>
        </template>
        <template v-else-if="form.priceType === 1">
          <sea-price
            ref="seaPrice"
            :currency-list="currencyList"
            :unit-list="unitList"
            :value="form"
            :readonly="readonly"
            field-prefix="all"
            :price-name="$t('全包价')"
            packaging-field="fullPricePackagingList"
            @changeUnit="handleFormUnitChange($event)"
          ></sea-price>
        </template>
        <template v-else>
          <el-row :gutter="20">
            <el-col :span="12">
              <sea-price
                ref="seaPrice"
                :currency-list="currencyList"
                :unit-list="unitList"
                :value="form"
                :readonly="readonly"
                field-prefix="transport"
                :price-name="$t('运费')"
                packaging-field="freightPricePackagingList"
                @changeUnit="handleFormUnitChange($event)"
              ></sea-price>
            </el-col>
            <el-col :span="12">
              <sea-price
                ref="seaPrice"
                :currency-list="currencyList"
                :unit-list="unitList"
                :value="form"
                :readonly="readonly"
                field-prefix="clearance"
                :price-name="$t('清关费')"
                packaging-field="clearancePricePackagingList"
                @changeUnit="handleFormUnitChange($event)"
              ></sea-price>
            </el-col>
          </el-row>
        </template>

        <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-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 != 'air'">
          <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>

    <el-card class="mt-10" v-if="readonly">
      <el-descriptions :column="1">
          <el-descriptions-item :label="$t('状态')">{{ statusName(form) }}</el-descriptions-item>
          <el-descriptions-item :label="$t('创建时间')">{{form.createTime|parseTime}}</el-descriptions-item>
        <el-descriptions-item :label="$t('创建人')">{{form.creatorName}}</el-descriptions-item>
        <el-descriptions-item :label="$t('最新修改时间')">{{form.updateTime|parseTime}}</el-descriptions-item>
        <el-descriptions-item :label="$t('最新修改人')">{{form.updaterName}}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <div style="margin: 20px 0">
      <el-button @click="submitForm" type="primary" v-if="!readonly" :loading="loading">{{$t('确认提交')}}</el-button>
      <el-button type="default" @click="$router.back()">{{$t('返回上一页')}}</el-button>
      <el-button @click="showLogs" type="primary" v-if="readonly">{{$t('查看价格日志')}}</el-button>
    </div>

    <logs ref="logs" :unit-map="unitMap" :currency-map="currencyMap"></logs>
  </div>
</template>
<script>
import RoutersSelector from '@/components/RoutersSelector'
import { createProductPrice, updateProductPrice, batchUpdateProductPrice, getProductPrice, getProductPriceList, getPriceSnapshotList } from "@/api/ecw/productPrice";
import { getProductType, getProductTypeList } from '@/api/ecw/productType'
import { getCurrencyList } from '@/api/ecw/currency';
import { getUnitList } from '@/api/ecw/unit';
import ProductSelector from '@/components/ProductSelector'
import { arrryToKeyedObjectBy } from '@/utils/index'
import Selector from '@/components/Selector'
import Inputor from '@/components/Inputor'
import {parseTime} from '@/utils/ruoyi'
import {openedRouterList} from '@/api/ecw/warehouse'
import Decimal from "decimal.js";
import {getChannel} from "@/api/ecw/channel";
import PackagingType from "@/views/ecw/channel/componrnts/packaging-type.vue";
import {getStatusName} from './util'
import QuickSet from "./components/QuickSet.vue"
import Logs from "@/views/ecw/productPrice/components/Logs.vue";
import SeaStep from "@/views/ecw/productPrice/components/SeaStep.vue";
import Template from "@/views/cms/template/index.vue";
import SeaPrice from "@/views/ecw/productPrice/components/SeaPrice.vue";
import PriceStep from "@/views/ecw/productPrice/components/PriceStep.vue";

const DEFAULT_PRICE_UNIT = 1
const DEFAULT_VOLUME_UNIT = 7
const DEFAULT_WEIGHT_UNIT = 7

export default {
  components: {
    PriceStep,
    SeaPrice,
    Template, Logs, QuickSet, PackagingType, RoutersSelector, ProductSelector, Selector, Inputor, SeaStep },
  filters: {parseTime},
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {
        minWeightUnit: 0,
        priceStepList: [], // 阶梯价格
        specialList: [],
        // 是否单询，默认否
        needOrderInquiry: '0'
      },
      needPay: false, // 是否需要预付
      stepPrice: false, // 是否阶梯订单
      rules: {
        transportPrice: [{ required: true, message: this.$t("海运费不能为空"), trigger: "blur" }],
        clearancePrice: [{ required: true, message: this.$t("清关费不能为空"), trigger: "blur" }],
        advanceStatus: [{ required: true, message: this.$t("是否预付不能为空"), trigger: "blur" }]
      },
      product: null,
      /* productType: null, */
      currencyList: [],
      unitList: [],
      productTypeList: [],
      productDisabled: true,
      readonly: false,
      lineList: [], //路线数组
      loading: false,
      // 渠道信息
      channel: null
    }
  },
  computed: {
    statusName(){
        return getStatusName
    },
    routerOption(){
      return this.$route.query
    },
    currencyMap(){
      let map = {}
      this.currencyList.forEach(item => {
        map[item.id] = this.$l(item, 'title')
      })
      return map
    },
    unitMap(){
      let map = {}
      this.unitList.forEach(item => {
        map[item.id] = this.$l(item, 'title')
      })
      return map
    },
    // 默认运费的货币和体积单位
    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}
    },
    // 类型，默认海运sea,air表示空运
    type(){
      return this.$route.path.split(/[-_]/).pop()
    },

  },
  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)
      /* getProductType(this.product.typeId).then(res => {
        this.productType = res.data
      }) */
      // 只有新建才需要把参数带过来
      if(!this.$route.query.action){
        this.$set(this.form, 'needBook', this.product.needBook)
        this.$set(this.form, 'square', this.product.square)
        this.$set(this.form, 'dayLimit', this.product.dayLimit)
        this.$set(this.form, 'containerLocation', this.product.containerLocation)
      }

    },
    'form.needBook'(val){
      if(val) this.$set(this.form, 'dayLimit', 10000)
      else delete this.form.dayLimit
    },
    'form.priceType'(priceType){
      if(this.form.stepPrice === 1){
        this.initStepPrice()
      }
      this.syncMinWeightUnit()
    },
    'form.stepPrice'(stepPrice){
      if(this.form.stepPrice === 1){
        this.initStepPrice()
      }
      this.stepPrice = !!stepPrice
        this.syncMinWeightUnit()
    },
    needPay(val){
      this.$set(this.form, 'needPay', val ? 1 : 0)
    },
    stepPrice(val){
      this.$set(this.form, 'stepPrice', val ? 1 : 0)
    },
  },
  async created() {
    this.currencyList = (await getCurrencyList())?.data || []
    this.unitList = (await getUnitList())?.data || []
    this.productTypeList = (await getProductTypeList())?.data || []

    if(this.$route.query.readonly){
      this.readonly = true
    }

    const defaultVolumeUnit = this.type === 'air' ? 6 : 7
    const defaultPriceUnit = 1

    // action=batchUpdate 表示批量修改单个商品的价格（一条或者多条），如果没有ids显示路线选择组件,否则不显示路线组件
    // action=update 表示修改单个商品的单条路线价格,需要回显
    if(this.$route.query.action == 'update'){
      let res = await getProductPrice(this.$route.query.id)
      this.$set(this, 'form', res.data)

      if(this.form.needPay){
        this.needPay = true
      }
      if(this.form.stepPrice == 1){
        this.stepPrice = true
      }
      if(res.data.validateStartDate){
        this.form.validateStartDate = parseTime(res.data.validateStartDate)
      }
      if(res.data.validateEndDate){
        this.form.validateEndDate = parseTime(res.data.validateEndDate)
      }
      this.lineList = [res.data]

      // 如果不是阶梯价，需要初始化包装类型
      if(this.form.stepPrice != 1){
        if(this.form.freightPricePackagingList?.length){
          this.form.freightPricePackagingList.forEach(item => {
            if(!item.packagingTypes){
              this.$set(item, 'packagingTypes', [])
            }else if(typeof item.packagingTypes == 'string'){
              item.packagingTypes = item.packagingTypes.split(',')
            }
          })
        }else this.form.freightPricePackagingList = [{}]
        if(this.form.clearancePricePackagingList?.length){
          this.form.clearancePricePackagingList.forEach(item => {
            if(!item.packagingTypes){
              this.$set(item, 'packagingTypes', [])
            }else if(typeof item.packagingTypes == 'string'){
              item.packagingTypes = item.packagingTypes.split(',')
            }
          })
        }else this.form.clearancePricePackagingList = [{}]
      }
    }

    // action=batchUpdate且ids不为空
    if(this.$route.query.action == 'batchUpdate'){
      delete this.form.needBook
    }
    if (this.$route.query.ids) {
      let query = {
        ids: this.$route.query.ids
      }
      getProductPriceList(query).then(res => {
        this.lineList = res.data
        this.lineList.forEach(item =>{
          this.checkList.push(item.id)
        })
      })
    }

    // 未指定商品则不禁用商品选择
    if(!this.$route.query.product_id){
        this.productDisabled = false
    }

    // 获取类型列表
    getProductTypeList().then(res => this.productTypeList = res.data)


    // 没有操作标识的就是新建，给有效期默认值
    if(!this.$route.query.action){
      this.form = {
        priceType: 0,
        // 空运则默认是阶梯价格
        stepPrice: this.type == 'air' ? 1 : 0,
        advanceStatus: 0,
        needBook: 0,
        specialList: [],
        clearancePricePackagingList: [{}],
        freightPricePackagingList: [{}],
        fullPricePackagingList: [{}],
        // dayLimit: 10000,
        validateEndDate: undefined,
        validateStartDate: undefined,
        clearancePrice: 0,
        transportPrice: 0,
        minWeight: 0,
        minWeightUnit: null,
        // 是否单询，默认否
        needOrderInquiry: 0
      }

      this.form.validateStartDate = parseTime(Date.now())
      this.form.validateEndDate = parseTime(Date.now() + 86400*365*2*1000)

      // 如果指定了始发，目的仓和运输方式，渠道，则是从未报价异常跳转过来的，固定一个路线
      if(this.$route.query.startWarehouseId){
        const res = await openedRouterList({
          destCityId: this.$route.query.importCity,
          lineId: this.$route.query.lineId,
          startCityId: this.$route.query.exportCity,
          transportType: this.$route.query.transportId
        })
        console.log("open ---> ", res)
        this.lineList = [
          Object.assign({
            // id: res.data[0].id,
            lineId:this.$route.query.lineId,
            shippingChannelId: this.$route.query.channelId,
            warehouseLineDO: {... res.data[0]}
          })
        ]
        // 后面会根据这个渠道ID获取渠道信息
        this.form.shippingChannelId = this.$route.query.channelId
      }
    }

    if(!this.$route.query.action || this.$route.query.action == 'batchUpdate'){
      this.$nextTick(() => {
        // 空运默认的阶梯重量单位是千克
        if(this.type === 'air'){
          this.$set(this.form.priceStepList[0], 'weightUnit', 6)
        }
      })
    }

    if (this.$route.query.product_type) {
      this.$set(this.form, 'productType', +this.$route.query.product_type)
    }
    if (this.$route.query.product_id) {
      this.$set(this.form, 'productId', +this.$route.query.product_id)
    }

    this.getDictDatas(this.DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS).forEach(item => {
      if(!this.form.specialList.find(special => special.specialDictType == item.value)){
        this.form.specialList.push({
          "clearancePrice": !this.$route.query.action ? 0 : null, // 新建默认给0，否则默认是null
          "clearancePriceUnit": null,
          "clearanceVolumeUnit": null,
          "specialDictType": item.value,
          "transportPrice": !this.$route.query.action ? 0 : null, // 新建默认给0，否则默认是null
          "transportPriceUnit": null,
          "transportVolumeUnit": null,
        })
      }
    })
  },
  methods: {
    // 设置最小起计量单位
    syncMinWeightUnit(){
        // 如果是阶梯价
        if(this.form.stepPrice){
            const field = this.form.priceType === 1 ? "fullPriceStepList" : "freightPriceStepList"
            const stepPriceList = this.form[field]
            if(stepPriceList?.length){
                this.form.minWeightUnit = stepPriceList[0]?.weightUnit || DEFAULT_WEIGHT_UNIT
            }else {
                this.form.minWeightUnit = DEFAULT_WEIGHT_UNIT
            }
        }else{
            this.form.minWeightUnit = this.form[this.form.priceType === 1 ? 'allVolumeUnit' : 'transportVolumeUnit'] || DEFAULT_WEIGHT_UNIT
        }
    },
    handleAddPrice(field, fieldPrefix){
      if(!this.form[field]){
        this.$set(this.form, field, [])
      }
      let priceUnit = DEFAULT_PRICE_UNIT
      let volumeUnit = DEFAULT_VOLUME_UNIT
      let weightUnit = DEFAULT_WEIGHT_UNIT
      if(this.form[field].length){
        const first = this.form[field][0]
        priceUnit = first[`${fieldPrefix}PriceUnit`]
        volumeUnit = first[`${fieldPrefix}VolumeUnit`]
        weightUnit = first.weightUnit
      }
      console.log("添加价格的默认单位", {
        priceUnit,
        volumeUnit,
        weightUnit
      })
      this.form[field].push({
        [`${fieldPrefix}PriceUnit`]: priceUnit,
        [`${fieldPrefix}VolumeUnit`]: volumeUnit,
        weightUnit: weightUnit,
        specialList:[]
      })
    },
    handleDeletePrice(field, index){
      this.form[field].splice(index, 1)
    },
    handleUnitChange(stepPriceList, index, data){
      console.log('handleUnitChange', ...arguments)
      if(index > 0) return
      const isVolumeUnit = data.field.indexOf("VolumeUnit") > -1
      // 如果是重量单位,且不是清关费想换的，则需要同步最小起计量单位
      if(isVolumeUnit && data.type != 'clearance'){
        this.form.minWeightUnit = data.value
      }
      stepPriceList.forEach(item => {
        item[data.field] = data.value
        // 如果是设置体积单位，则还需要同步到阶梯重量单位
        if(isVolumeUnit){
          item['weightUnit'] = data.value
        }
        if(item.packagingList?.length){
          item.packagingList.forEach(p => {
            if(data.field.indexOf("PriceUnit") > -1){
              p['packagingPriceUnit'] = data.value
            }
            if(data.field.indexOf("VolumeUnit") > -1){
              p['packagingVolumeUnit'] = data.value
            }
          })
        }
        if(item.specialList?.length){
          item.specialList.forEach(p => {
            p[data.field] = data.value
          })
        }
      })
    },

    // 获得用语提交的阶梯价副本
    getPriceList(stepList){
      if(!stepList?.length) return []
      let stepPriceList = JSON.parse(JSON.stringify(stepList))
      stepPriceList.forEach((item, index) => {
        item.rankNum = index + 1
        item.packagingList = item.packagingList.filter(p => !!p.packagingTypes?.length)
        item.packagingList = item.packagingList.map( p => {
          p.packagingTypes = p.packagingTypes.join(",")
          return p
        })
      })
      return stepPriceList
    },
    // 格式化包装类型费用
    getPackingPrice(packging){
      if(!packging?.length) return
      packging = JSON.parse(JSON.stringify(packging))
      return packging.filter(item => !!item.packagingTypes).map(item => {
        item.packagingTypes = item.packagingTypes?.join(",") || ""
        return item
      })
    },
    // 非阶梯价格更新单位
    handleFormUnitChange(data){
      // 海运非阶梯价没有重量单位，所以按照体积单位同步最小起计量单位
      if(data.field === 'transportVolumeUnit' || data.field == 'allVolumeUnit'){
          this.form.minWeightUnit = data.value
      }

      if(this.form.specialList?.length){
        this.form.specialList.forEach(p => {
          p[data.field] = data.value
        })
      }

      // 同步包装的单位
      let packingField = {
        transportVolumeUnit: 'freightPricePackagingList',
        clearanceVolumeUnit: 'clearancePricePackagingList',
        allVolumeUnit: 'fullPricePackagingList',
        transportPriceUnit: 'freightPricePackagingList',
        clearancePriceUnit: 'clearancePricePackagingList'
      }[data.field]
      if(!this.form[packingField]?.length){
        return false
      }
      this.form[packingField].forEach(item => {
        if(data.field.indexOf("PriceUnit") > -1){
          item['packagingPriceUnit'] = data.value
        }
        if(data.field.indexOf("VolumeUnit") > -1){
          item['packagingVolumeUnit'] = data.value
        }
      })
    },
    initStepPrice(){
      if(this.form.priceType == 1 && !this.form.fullPriceStepList?.length){
        this.handleAddPrice("fullPriceStepList", 'all')
      }
      if(this.form.priceType === 0){
        if(!this.form.freightPriceStepList?.length){
          this.handleAddPrice('freightPriceStepList', 'transport')
        }
        if(!this.form.clearancePriceStepList?.length){
          this.handleAddPrice('clearancePriceStepList', 'clearance')
        }
      }
    },
    // force 为是否强制提交，在价格过期的时候需要确认后强制提交
    submitForm(force = false) {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) {
          return;
        }

        // 只有修改单条路线的时候，不需要选择路线
        /* if (this.$route.query.action !== 'update' && (!this.selectedRoutes || !this.selectedRoutes.length)) {
          this.$message.error('请选择线路');
          return;
        } */
        if(!this.lineList.length && (!this.selectedRoutes || !this.selectedRoutes.length)) {
          this.$message.error(this.$t('请选择线路'));
          return;
        }
        let data = Object.assign({}, this.form, {
          // lineChannelList: this.selectedRoutes,
          // specialList: this.specialProducts,
          isAllProduct: 0
        })
        // 阶梯价
        if(this.form.stepPrice){
          let isValid = true
          for (let stepPrice of this.$refs.stepPrice){
            if(!stepPrice.validate()){
              isValid = false
              break
            }
          }
          if(!isValid)return

          // 全包价
          if(this.form.priceType == 1) {
            data.fullPriceStepList = this.getPriceList(this.form.fullPriceStepList)
            delete data.clearancePriceStepList
            delete data.freightPriceStepList
          }else{
            data.clearancePriceStepList = this.getPriceList(this.form.clearancePriceStepList)
            data.freightPriceStepList = this.getPriceList(this.form.freightPriceStepList)
            delete data.fullPriceStepList
          }
        }
        //海运非阶梯价校验
        else{
          // 有多个组件则表示清关费 + 运费
          if(this.$refs.seaPrice?.length){
            let isValid = true
            for (let seaPrice of this.$refs.seaPrice){
              if(!seaPrice.validate()){
                isValid = false
                break
              }
            }
            if(!isValid)return
          }
          // 只有一个海运费组件，全包价
          else if(this.$refs.seaPrice && !this.$refs.seaPrice.validate()){
            return
          }

          // 格式化
          if(this.form.priceType === 1){
            data.fullPricePackagingList = this.getPackingPrice(data.fullPricePackagingList)
            delete data.freightPricePackagingList
            delete data.clearancePricePackagingList
          }else{
            data.freightPricePackagingList = this.getPackingPrice(data.freightPricePackagingList)
            data.clearancePricePackagingList = this.getPackingPrice(data.clearancePricePackagingList)
            delete data.fullPricePackagingList
          }


          // 删除阶梯价字段
          delete data.freightPriceStepList
          delete data.fullPriceStepList
          delete data.clearancePriceStepList
        }

        // 设置了有效期，且已过期则给提示
        if(this.form.validateEndDate && force !== true){
          let validateEndDate = new Date(this.form.validateEndDate)
          if(validateEndDate.getTime() < Date.now()){
            return this.$confirm('您设置的线路价格已过期，确定提交吗?', '提示', {
              confirmButtonText: '确认提交',
              cancelButtonText: '取消提交',
              type: 'warning'
            }).then(res => {
              this.submitForm(true)
            })
          }
        }

        // 修改单条路线
        if (this.$route.query.action == 'update') {
          this.loading = true
          return updateProductPrice(data).then(res => {
            this.$modal.msgSuccess(this.$t("请求成功"));
            this.$tab.closePage()
          }).finally(res => this.loading = false)
        }

        // 批量修改（单个商品的单个路线，多个路线，或者全部路线）的提交
        if (this.$route.query.action == 'batchUpdate') {
          // 指定一条路线
          if(this.lineList.length == 1){
            data.lineChannelList = {
              lineId: this.lineList[0].warehouseLineId,
              shippingChannelId: this.lineList[0].shippingChannelId || 0
            }
          }
          // 指定多条路线的需要过滤未勾选的
          else if(this.lineList.length > 1){
            data.lineChannelList = []
            this.lineList.forEach(item => {
              if(this.checkList.indexOf(item.id) > -1){
                data.lineChannelList.push({
                    lineId: item.warehouseLineId,
                    shippingChannelId: item.shippingChannelId || 0
                  }
                )
              }
            })
          }
          // 未指定路线的从路线选择组件里获取
          if(!this.lineList.length){
            data.lineChannelList = this.selectedRoutes
          }
          if(data.lineChannelList.length < 1){
            return this.$message.error(this.$t('请选择需要修改的路线'))
          }
          await this.$confirm(this.$t("已选择{route}条路线，确认提交？", {route: data.lineChannelList.length}))
          data.productIdList = [this.form.productId]
          this.loading = true
          batchUpdateProductPrice(data).then(response => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            this.$router.replace('/product/product-price?' + (new URLSearchParams(this.$route.query)).toString())
          }).finally(res => this.loading = false)
          return;
        }
        // 添加的提交
        if(!this.product){
          return this.$message.error(this.$t('请选择商品'))
        }
        data.productId = this.product.id;
        data.lineChannelList = this.lineList.length ? this.lineList : this.selectedRoutes
        await this.$confirm(this.$t("已选择{route}条路线，确认提交？", {route: data.lineChannelList.length}))

        // 空运且不是全包价的清关费用0填充
        if(this.type == 'air' && this.form.priceType == 0){
          // 根据是否全包价确定字段
          data.priceStepList.forEach(item => {
            item.clearancePrice = item.clearancePrice || 0
          })
        }

        this.loading = true
        createProductPrice(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);
      });
    },
    showLogs(){
      if(!this.$refs.logs){
        return this.$message.error("未找到组件")
      }
      this.$refs.logs.open(this.form.id)
    }
  }
}
</script>
<style scoped>
.w-100{
  width: 100px;
}
.mr10{
  margin-right: 10px;
}
</style>
