<script>
import Decimal from 'decimal.js'
import { parseTime } from '@/utils/ruoyi'
export default {
  name: 'DetailProd',
  props: {
    list: {
      type: Array,
      required: true
    },
    attrList: {
      type: Array,
      required: true
    },
    prodTypeList: {
      type: Array,
      required: true
    },
    currencyMap: {
      type: Object,
      required: true
    },
    unitMap:{
      type: Object,
      required: true
    },
    transportId: {
      type: Number,
      required: false
    },
  },
  data(){
    return {
      feeDetail: null,
      showFeeDetailDialog: false
    }
  },
  computed:{
    getProdTypeName() {
      return (prodType) => {
        for (let index in this.prodTypeList) {
          let prodTypeItem = this.prodTypeList[index];
          if (prodTypeItem.id == prodType) {
            return this.$l(prodTypeItem, "title");
          }
        }
      };
    },
    // 显示特性
    showAttrText(){
      return ids => {
        if(!ids) return ''
        ids = !Array.isArray(ids) ? ids.split(',') : ids
        const attrMap = {}
        this.attrList.forEach(item => {
          attrMap[item.id] = this.$l(item, 'attrName')
        })
        return ids.map(id => attrMap[id]).join(',')
      }
    },
  },
  methods:{
    closeFeeDetail(){
      this.showFeeDetailDialog = null
    },
    showFeeDetail(row, type){
      console.log("showFeeDetail", row, type)
      this.showFeeDetailDialog = true
      const freight = [], clearance = []

      let freightFields = []
      let clearanceFields = []

      const brandType = row.warehouseInInfoVO ? row.feeType : row.brandType
      // 不是特价则显示其他字段
      freightFields = [
        // {field: 'oneSeaFreight', label: this.$t('成交单价')},
        {field: 'originalSeaFreight', label: this.$t('默认单价（无牌无液无电）')},
        // {field: 'brandFreightPrice', label: this.$t('品牌加价')},
        {field: 'liquidFreightPrice', label: this.$t('液体加价')},
        {field: 'electrifiedFreightPrice', label: this.$t('带电加价')},
        {field: 'discountFreightPrice', label: this.$t('优惠活动减免')},
        {field: 'plainCommission', label: this.$t('明佣')},
        {field: 'hiddenCommission', label: this.$t('暗佣')}
      ]

      // 批量加价
      if(row.markupSeaFreight){
        freightFields.push({field: 'markupSeaFreight', label: this.$t('批量加价')})
      }

      // 品牌加价
      if(row['brandFreightPrice'] && row['brandFreightPrice'] > 0){
        freightFields.push({field: 'brandFreightPrice', label: brandType == 1 ? this.$t('有品牌加价') : this.$t('中性品牌加价')})
      }

      // 有减免金额才显示优惠后单价
      if(row['discountFreightPrice'] && row['discountFreightPrice'] > 0){
        freightFields.push({field: 'afterDiscountSeaFreight', label: this.$t('优惠后单价')})
      }
      // 包装加价
      if(row['packagingFreightPrice'] && row['packagingFreightPrice'] > 0){
        freightFields.push({field: 'packagingFreightPrice', label: this.$t('包装加价')})
      }
      freightFields.push({field: 'oneSeaFreight', label: this.$t('成交单价')})
      console.log({freightFields})
      freightFields.forEach(item => {
        if(row[item.field]){
          freight.push({
            label: item.label,
            value: row[item.field],
            currency: row.seaFreightCurrency,
            volume: row.seaFreightVolume,
            // 特价通过四个字段标识，任一为true则为特价
            remark: item.field == 'oneSeaFreight' && (row.specialPriceType || row.splitCustomPriceType || row.channelManualPricing) ? this.$t('特价') : null
          })

        }
      })

      clearanceFields = [
        {field: 'originalClearanceFreight', label: this.$t('默认单价（无牌无液无电）')},
        // {field: 'brandClearanceFeePrice', label: this.$t('品牌加价')},
        {field: 'liquidClearanceFeePrice', label: this.$t('液体加价')},
        {field: 'electrifiedClearanceFeePrice', label: this.$t('带电加价')},
        {field: 'discountClearanceFeePrice', label: this.$t('优惠活动减免')}
      ]
      // 批量加价
      if(row.markupClearanceFreight){
        clearanceFields.push({field: 'markupClearanceFreight', label: this.$t('批量加价')})
      }
      // 品牌加价
      if(row['brandClearanceFeePrice'] && row['brandClearanceFeePrice'] > 0){
        clearanceFields.push({field: 'brandClearanceFeePrice', label: brandType == 1 ? this.$t('有品牌加价') : this.$t('中性品牌加价')})
      }
      if(row['discountClearanceFeePrice'] && row['discountClearanceFeePrice'] > 0){
        clearanceFields.push({field: 'afterDiscountClearanceFreight', label: this.$t('优惠后单价')})
      }
      // 包装加价
      if(row['packagingClearanceFeePrice'] && row['packagingClearanceFeePrice'] > 0){
        clearanceFields.push({field: 'packagingClearanceFeePrice', label: this.$t('包装加价')})
      }
      clearanceFields.push({field: 'oneClearanceFreight', label: this.$t('成交单价')})
      clearanceFields.forEach(item => {
        if(row[item.field]){
          clearance.push({
            label: item.label,
            value: row[item.field],
            currency: row.clearanceFreightCurrency,
            volume: row.clearanceFreightVolume,
            remark: (row.specialPriceType || row.splitCustomPriceType || row.channelManualPricing) && item.field == 'oneClearanceFreight' ? this.$t('特价') : null
          })
        }
      })


      freight.push({
        label: this.$t('价格更新时间'),
        value: parseTime(row.updateTime)
      })
      clearance.push({
        label: this.$t('价格更新时间'),
        value: parseTime(row.updateTime)
      })
      this.feeDetail = {
        freight,
        clearance,
        charging:
        row.charging,
        coupons: row.couponInfoVOList,
        airClearanceSource: [,this.$t('商品'), this.$t('渠道'), this.$t('商品线路价格'),this.$t('线路渠道')][row.airClearanceSource], // 1 商品 2 渠道 3 商品线路价格 4 线路渠道
        airClearanceInfo: JSON.parse(row.airClearanceInfo), //空运清关费来源数据详情,
        sourceName: row.airClearanceSource == 1 ? this.$l(row, 'prodTitle') : this.order?.channelName
      }
    },
    // 获取储位名称
    getLocationName(locationArr){
      if(!locationArr || !locationArr.length) return ''
      let arr = []
      locationArr.forEach(item => {
        arr.push(`${item.areaName}${item.locationName || ''}`)
      })
      return Array.from(new Set(arr)).join(",")
    },
    // 获取品名汇总数据
    getProdSummary(e){
      console.log("getProdSummart", e)
      // 货值
      let worth = new Decimal(0)
      // 填单数据
      let fillData = {
        num: new Decimal(0),
        weight: new Decimal(0),
        volume: new Decimal(0),
        quantity: new Decimal(0)
      }
      // 入仓数据
      let warehouseInData = {
        num: new Decimal(0),
        weight: new Decimal(0),
        volume: new Decimal(0),
        quantity: new Decimal(0)
      }
      // 收费数据
      let chargeData = {
        weight: new Decimal(0),
        volume: new Decimal(0),
      }
      this.list?.forEach(item => {
        worth = worth.plus(item.worth || 0)
        fillData.num = fillData.num.plus(item.num || 0)
        fillData.weight = fillData.weight.plus(item.weight || 0)
        fillData.volume = fillData.volume.plus(item.volume || 0)
        fillData.quantity = fillData.quantity.plus(item.quantity || 0)
        if(item.warehouseInInfoVO){
          warehouseInData.num = warehouseInData.num.plus(item.warehouseInInfoVO.cartonsNum || 0)
          warehouseInData.weight = warehouseInData.weight.plus(item.warehouseInInfoVO.weight || 0)
          warehouseInData.volume = warehouseInData.volume.plus(item.warehouseInInfoVO.volume || 0)
          warehouseInData.quantity = warehouseInData.quantity.plus(item.warehouseInInfoVO.quantityAll || 0)
        }
        chargeData.weight = chargeData.weight.plus(item.chargeWeight || 0)
        chargeData.volume = chargeData.volume.plus(item.chargeVolume || 0)
      })
      const summary = Array(19).fill(null)
      summary[3] = this.$t("合计")
      // 入仓
      summary[4] = `${warehouseInData.num}${this.$t('箱')} ${warehouseInData.weight}KG ${warehouseInData.volume}m³ ${warehouseInData.quantity}${this.$t('个')}`
      // 货值
      summary[7] = worth.toNumber()
      // 收费数九
      summary[10] = `${chargeData.weight}KG ${chargeData.volume}m³`
      // 填单数据
      summary[17] = `${fillData.num}${this.$t('箱')} ${fillData.weight}KG ${fillData.volume}m³ ${fillData.quantity}${this.$t('个')}`
      return summary
    }
  }
}
</script>

<template>
  <div>
    <el-table
      :data="list"
      border
      show-summary
      :summary-method="getProdSummary"
      style="width: 100%">
      <el-table-column :label="$t('序号')" width="90px">
        <template slot-scope="scope">{{scope.$index + 1}}</template>
      </el-table-column>
      <el-table-column prop="prodTitleZh" :label="$t('品名')" width="220px">
        <template slot-scope="{row}">
          <div>{{ getProdTypeName(row.prodType) }}</div>
          <div>{{row.prodTitleZh}}/{{row.prodTitleEn}}</div>
        </template>
      </el-table-column>
      <!--<el-table-column prop="prodTitleEn" :label="$t('品名')" />-->
      <el-table-column prop="brand" :label="$t('品牌')"  width="90px">
        <template slot-scope="{row}">
          <template v-if="row.brandName">{{row.brandName}}</template>
          <dict-tag v-else :type="DICT_TYPE.ECW_IS_BRAND" :value="row.brandType" />
        </template>
      </el-table-column>
      <el-table-column prop="brand" :label="$t('特性')"  width="90px">
        <template slot-scope="{row}">
          {{showAttrText(row.warehouseInInfoVO ? row.warehouseInProdAttrIds : row.prodAttrIds)}}
        </template>
      </el-table-column>
      <el-table-column prop="sumNum" :label="$t('入仓信息')"  width="220px">
        <template slot-scope="{row}">
          <!--<el-link type="primary" @click.native="showWarehouseLogs(row,1)">{{row.warehouseInInfoVO ? row.warehouseInInfoVO.cartonsNum : 0}}</el-link>
          <div v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.isMultiSpecification">({{$t('多规格')}})</div>-->
          <el-link type="primary" @click.native="$emit('showWarehouseLogs', row,1)" v-if="row.warehouseInInfoVO">
            {{row.warehouseInInfoVO.cartonsNum}}{{$t('箱')}}
            {{row.warehouseInInfoVO.weight}}Kg
            {{row.warehouseInInfoVO.volume}}m³
            {{row.warehouseInInfoVO.quantityAll}}{{$t('个')}}
          </el-link>
          <div v-if="row.warehouseInInfoVO && row.warehouseInInfoVO.isMultiSpecification">({{$t('多规格')}})</div>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseType" :label="$t('类型')"  width="120px"/>
      <el-table-column prop="specificationType" :label="$t('包装')"  width="120px"/>
      <el-table-column prop="worth" :label="$t('货值')"  width="120px"/>
      <el-table-column prop="warehouseRecordRemark" :label="$t('入仓备注')"  width="120px"/>
      <el-table-column prop="warehouseInInfoVO.expressNo" :label="$t('快递单号')" />
      <el-table-column prop="sumNum" :label="$t('收费数据')"  width="220px">
        <template slot-scope="{row}">
          <div v-if="row.warehouseInInfoVO">
            {{row.chargeWeight}}Kg
            {{row.chargeVolume}}m³
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" :label="`${$t('费用类型')}/${$t('模式')}`" width="200px">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_PAY_ADVANCE" :value="row.isPayAdvance" />
          <div v-if="row.charging ==0">{{ $t('运费/清关费') }}</div>
          <div v-if="row.charging ==1">{{ $t('全包价') }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="" :label="$t('成交单价')"  width="220px">
        <template slot-scope="{row}">

          <template v-if="row.charging ==1">
            <template v-if="!row.originalSeaFreight">{{ $t('未报价') }}</template>
            <el-link type="primary" @click="showFeeDetail(row, 'clearance')" v-else>{{$t('全包价')}} {{row.oneSeaFreight}} {{currencyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}</el-link>
          </template>
          <template v-else-if="!row.originalSeaFreight && !row.originalClearanceFreight">{{ $t('未报价') }}</template>
          <template v-else>
            <el-link type="primary" @click="showFeeDetail(row, 'freight')">
              {{$t('运费')}}：{{row.oneSeaFreight}} {{currencyMap[row.seaFreightCurrency]}} / {{unitMap[row.seaFreightVolume]}}
            </el-link>
            <el-link type="primary" @click="showFeeDetail(row, 'clearance')">
              {{$t('清关费')}}：{{row.oneClearanceFreight}} {{currencyMap[row.clearanceFreightCurrency]}} / {{unitMap[row.clearanceFreightVolume]}}
            </el-link >
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="" :label="$t('材质')">
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_PRODUCT_MATERIAL" :value="row.material" />
        </template>
      </el-table-column>
      <el-table-column prop="" :label="$t('用途')">
        <template slot-scope="{row}">
          <div v-if="row.usageIds">
            <div v-for="(item,index) in row.usageIds.split(',')">
              <dict-tag :type="DICT_TYPE.OREER_ITEM_USAGE" :value="item" />
              <span v-if="(index+1)!=row.usageIds.split(',').length">,</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" :label="$t('储位')">
        <template slot-scope="{row}">
          <template v-if="row.warehouseInInfoVO">
            {{getLocationName(row.warehouseInInfoVO.orderLocationMergeVOSet)}}
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="" :label="$t('商品链接')">
        <template slot-scope="{row}">
          <template v-if="row.link">
            <a target="_blank" :url="row.link">{{row.link}}</a>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="sumNum" :label="$t('填单信息')"  width="180px">
        <template slot-scope="{row}">
          {{row.num}}{{$t('箱')}}
          {{row.weight}}Kg
          {{row.volume}}m³
          {{row.quantity}}{{$t('个')}}
        </template>
      </el-table-column>
      <el-table-column prop="expressNo" :label="$t('填单快递单号')" />
    </el-table>
    <el-dialog :title="$t('费用详情')" :visible="!!showFeeDetailDialog" :before-close="closeFeeDetail">
      <el-row v-if="feeDetail">
        <el-col :span="12">
          <div>{{feeDetail.charging ? $t('全包价') : $t('运费')}}</div>
          <div v-for="item in feeDetail.freight">
            {{item.label}}: {{item.value}}
            <template v-if="item.currency">
              {{currencyMap[item.currency]}} / {{unitMap[item.volume]}} <span v-if="item.remark">【{{item.remark}}】</span>
            </template>
          </div>
        </el-col>
        <el-col :span="12" v-if="feeDetail.charging != 1">
          <div>
            {{$t('清关费')}}
            <template v-if="transportId == 3 || transportId == 4">
              {{$t('来自{source}', {source: feeDetail.airClearanceSource + feeDetail.sourceName})}}
            </template>
          </div>
          <div v-for="item in feeDetail.clearance">
            {{item.label}}: {{item.value}}
            <template v-if="item.currency">
              {{currencyMap[item.currency]}} / {{unitMap[item.volume]}} <span v-if="item.remark">【{{item.remark}}】</span>
            </template>
          </div>
        </el-col>
      </el-row>

      <div v-if="feeDetail && feeDetail.coupons && feeDetail.coupons.length" class="page-title">{{ $t('优惠详情') }}</div>
      <el-table v-if="feeDetail && feeDetail.coupons && feeDetail.coupons.length" :data="feeDetail.coupons">
        <el-table-column label="优惠ID" prop="couponId"></el-table-column>
        <el-table-column label="优惠名称">
          <template slot-scope="{row}">
            {{ $l(row, 'title') }}
          </template>
        </el-table-column>
        <el-table-column label="类型">
          <template slot-scope="{row}">
            <dict-tag :type="DICT_TYPE.ECW_COUPON_TYPE" :value="row.type" ></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="运费优惠">
          <template slot-scope="{row}">
            {{ row.freightReduceAmount}}
            {{currencyMap[row.freightReduceCurrencyId]}}
          </template>
        </el-table-column>
        <el-table-column label="清关费优惠">
          <template slot-scope="{row}">
            {{ row.clearanceReduceAmount}}
            {{ currencyMap[row.clearanceReduceCurrencyId] }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

