<template>
  <div class="app-container">
    <el-form ref="form" :model="form" 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>

      <!--多条路线批量修改-->
        <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 :label="$t('出货渠道')">
              {{channel ? $l(channel, 'name') : '/'}}
          </el-form-item>
        </template>
      <!--有路线则不显示路线选择器-->
      <routers-selector v-else v-model="selectedRoutes" :option="routerOption" type="air" />

      <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>
          </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 :min="0" v-model="form.minWeight" :controls="false" class="w-100"/>
							/ <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" v-if="!readonly">
            <quick-set :unit-list="unitList" :currency-list="currencyList" :value="form"></quick-set>
          </el-col>
        </el-row>
        <!--全包价-->
        <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"
              :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"
                :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"
                :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>

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

        <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-form-item :label="$t('线路重量上限')" prop="inquiry">
          <el-input-number v-model="form.weightLimit" :min="0" :controls="false"></el-input-number>
        </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"></logs>
  </div>
</template>
<script>
import RoutersSelector from '@/components/RoutersSelector'
import {
  createProductPrice,
  updateProductPrice,
  batchUpdateProductPrice,
  getProductPrice,
  getProductPriceList,
  getPriceSnapshotList,
  updateProductPriceAir, createProductPriceAir, batchUpdateProductPriceAir
} 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 PriceStep from "@/views/ecw/productPrice/components/PriceStep.vue";

// 定义默认的价格单位和体积单位
const DEFAULT_PRICE_UNIT = 1
const DEFAULT_VOLUME_UNIT = 6
const DEFAULT_WEIGHT_UNIT = 6

export default {
  components: {PriceStep, Logs, QuickSet, PackagingType, RoutersSelector, ProductSelector, Selector, Inputor },
  filters: {parseTime},
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {
        minWeightUnit: 0,
        priceStepList: [], // 阶梯价格
        specialList: [],
        // 是否单询，默认否
        needOrderInquiry: '0'
      },
      needPay: false, // 是否需要预付
      product: 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

      if(this.form.priceType == 1 && this.form.fullPriceStepList?.length){
        currency = this.form.fullPriceStepList[0].allPriceUnit
        unit = this.form.fullPriceStepList[0].allVolumeUnit
      }
      if(this.form.priceType == 1 && this.form.freightPriceStepList?.length){
        currency = this.form.freightPriceStepList[0].allPriceUnit
        unit = this.form.freightPriceStepList[0].allVolumeUnit
      }

      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)
      /* 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.priceType'(priceType){
      if(priceType == 1 && !this.form.fullPriceStepList?.length){
        this.handleAddPrice('fullPriceStepList', 'all')
      }
      if(priceType == 0){
        if(!this.form.freightPriceStepList?.length){
          this.handleAddPrice('freightPriceStepList', 'transport')
        }
        if(!this.form.clearancePriceStepList?.length){
          this.handleAddPrice('clearancePriceStepList', 'clearance')
        }
      }
    },

    'form.needBook'(val){
      if(val) this.$set(this.form, 'dayLimit', 10000)
      else delete this.form.dayLimit
    },
    needPay(val){
      this.$set(this.form, 'needPay', val ? 1 : 0)
    },
    stepPrice(val){
      this.$set(this.form, 'stepPrice', val ? 1 : 0)
    },
    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() {
    if(this.$route.query.readonly){
      this.readonly = true
    }

    this.currencyList = (await getCurrencyList())?.data || []
    this.unitList = (await getUnitList())?.data || []
    this.productTypeList = (await getProductTypeList())?.data || []

    // action=batchUpdate 表示批量修改单个商品的价格（一条或者多条），如果没有ids显示路线选择组件,否则不显示路线组件
    // action=update 表示修改单个商品的单条路线价格,需要回显
    if(this.$route.query.action == 'update'){
      await this.initUpdate()
    }
    // 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
    }

    // 没有操作标识的就是新建，给有效期默认值
    if(!this.$route.query.action){
      await this.initCreate()
    }

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

    // 显示渠道（修改或者从异常处理等进入携带了渠道参数）
    if(this.form.shippingChannelId){
      this.channel = (await getChannel(this.form.shippingChannelId))?.data || {}
    }
  },
  methods: {
    // 新建的初始化
    async initCreate(){
      this.form = {
        priceType: 0,
        stepPrice: 1,
        advanceStatus: 0,
        needBook: 0,
        clearancePriceStepList: [],
        freightPriceStepList: [],
        fullPriceStepList: [],
        validateEndDate: undefined,
        validateStartDate: undefined,
        clearancePrice: 0,
        transportPrice: 0,
        minWeight: 0,
        minWeightUnit: null,
        // 是否单询，默认否
        needOrderInquiry: 0,
        needPay: 0,
        weightLimit: undefined
      }

      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
      }
    },
    async initUpdate(){
      let res = await getProductPrice(this.$route.query.id)
      this.$set(this, 'form', res.data)

      if(this.form.needPay){
        this.needPay = 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]

      // 如果没有对应的阶梯价字段，则初始化一个
      await this.$nextTick()
      if(this.form.priceType === 1){
        if(!this.form.fullPriceStepList?.length){
          this.handleAddPrice("fullPriceStepList", "all")
        }
      }else{
        if(!this.form.clearancePriceStepList?.length){
          this.handleAddPrice("clearancePriceStepList", "clearance")
        }
        if(!this.form.freightPriceStepList?.length){
          this.handleAddPrice("freightPriceStepList", "transport")
        }
      }
    },
    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

      // 如果是重量单位,且不是清关费想换的，则需要同步最小起计量单位
      if(data.field === 'weightUnit' && data.type != 'clearance'){
        this.form.minWeightUnit = data.value
      }
      stepPriceList.forEach(item => {
        item[data.field] = data.value
        if(item.packagingList?.length){
          item.packagingList.forEach(p => {
            p[data.field] = 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
    },
    // force 为是否强制提交，在价格过期的时候需要确认后强制提交
    submitForm(force = false) {
      this.$refs["form"].validate(async (valid) => {
        if (!valid) {
          return;
        }

        if(!this.lineList.length && (!this.selectedRoutes || !this.selectedRoutes.length)) {
          this.$message.error(this.$t('请选择线路'));
          return;
        }
        let data = Object.assign({}, this.form, {
          isAllProduct: 0
        })

        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)
        }else{
          data.clearancePriceStepList = this.getPriceList(this.form.clearancePriceStepList)
          data.freightPriceStepList = this.getPriceList(this.form.freightPriceStepList)
        }

        // 设置了有效期，且已过期则给提示
        if(data.validateEndDate && force !== true){
          let validateEndDate = new Date(data.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 updateProductPriceAir(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
          batchUpdateProductPriceAir(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}))

        this.loading = true
        createProductPriceAir(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>
