<template>
  <el-dialog visible :close-on-click-modal="false" :before-close="closeDialog" :title="$t('佣金规则')">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item :label="$t('商品类型')">
        <span>{{ $l(productType, 'title') }}</span>
      </el-form-item>
      <el-form-item :label="$t('商品名称')">
        <span>{{ orderItem.prodTitleZh }}</span>
      </el-form-item>
      <el-form-item :label="$t('英文名称')">
        <span>{{ orderItem.prodTitleEn }}</span>
      </el-form-item>
      <el-form-item :label="$t('线路')">
        【<dict-tag :type="DICT_TYPE.TRANSPORT_TYPE" :value="order.transportId" />】
        {{ channel ? $l(channel, 'title') : '' }}
        {{$t("从【{departureName}】发往【{objectiveName}】", {departureName: $l(order.logisticsInfoDto, 'startTitle'), objectiveName: $l(order.logisticsInfoDto, 'destTitle')})}}
      </el-form-item>
      <el-form-item :label="$t('是否预付')">
        <dict-tag :type="DICT_TYPE.ECW_YESNO" :value="orderItem.isPayAdvance" />
      </el-form-item>
      
      <el-row v-if="!orderItem.charging">
        <el-col :span="12">
          <el-form-item :label="$t('运费')">
            {{orderItem.oneSeaFreight}} {{ currencyMap[orderItem.seaFreightCurrency] }} / {{ unitMap[orderItem.seaFreightVolume] }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('清关费')">
            {{orderItem.oneClearanceFreight}} {{ currencyMap[orderItem.clearanceFreightCurrency] }} / {{ unitMap[orderItem.clearanceFreightVolume] }}
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item :label="$t('全包价')" v-if="orderItem.charging">
        {{orderItem.oneSeaFreight}} {{ currencyMap[orderItem.seaFreightCurrency] }} / {{ unitMap[orderItem.seaFreightVolume] }}
      </el-form-item>

      <el-form-item :label="$t('佣金类型')" prop="commissionType">
        <dict-selector :type="DICT_TYPE.COMMISSION_TYPE" v-model="form.commissionType" form-type="radio" formatter="number" />
      </el-form-item>

      <!-- 明佣或者明佣+暗佣才显示 -->
      <el-form-item label="明佣佣金" v-if="form.commissionType == 1 || form.commissionType == 3">
        <el-input v-model.number="form.lightCommissionAmount" placeholder="" class="w-100"></el-input>
        {{ currencyMap[orderItem.seaFreightCurrency] }} / {{ unitMap[orderItem.seaFreightVolume] }}
      </el-form-item>

      <!-- 明佣+暗佣才显示 -->
      <el-form-item label="暗佣佣金" v-if="form.commissionType == 3">
        <el-input v-model.number="form.shadeCommissionAmount" placeholder="" class="w-100"></el-input>
        {{ currencyMap[orderItem.seaFreightCurrency] }} / {{ unitMap[orderItem.seaFreightVolume] }}
      </el-form-item>

      <!-- 无佣金不显示 -->
      <div class="pl-50" v-if="form.commissionType != 0">
        <div v-if="form.commissionType != 2">{{$l(orderItem, 'prodTitle')}}</div>

        <!-- 明佣+暗佣显示 -->
        <div v-if="form.commissionType == 3">
          {{$t('成本价')}}：{{Decimal(form.freight).minus(form.shadeCommissionAmount)}} {{ currencyMap[form.freightCurrency] }} / {{ unitMap[form.freightVolume] }}
        </div>
        
        <!-- 暗佣显示 -->
        <div v-if="form.commissionType == 2">
          {{$l(orderItem, 'prodTitle')}}
          <template v-if="darkCommission">
            {{$t('暗佣')}}：{{darkCommission}} {{ currencyMap[form.freightCurrency] }} / {{ unitMap[form.freightVolume] }}
          </template>
          <el-link type="primary" @click.native="$router.push('/customer/customerCommission?customerId=' + order.customerId)">{{$t('去设置')}}</el-link>
        </div>

        <div  v-if="form.commissionType == 1 || form.commissionType == 3">{{$t('销售价')}}：{{Decimal(form.freight).plus(form.lightCommissionAmount) }} {{ currencyMap[form.freightCurrency] }} / {{ unitMap[form.freightVolume] }}</div>
        <div v-if="form.commissionType == 3">{{$t('实际佣金返点')}}：{{form.shadeCommissionAmount + form.lightCommissionAmount }} {{ currencyMap[form.freightCurrency] }} / {{ unitMap[form.freightVolume] }}</div>
      </div>
      
    </el-form>
    <div class="page-title">审批流程</div>
    <work-flow xmlkey="commission_config" v-model="ccIdArr" />
    <div v-if="form.applyStatus != 1">
      <el-button type="primary" @click="handleSubmit" :disabled="!submitable">提交</el-button>
    </div>
    <div v-else>
      <el-button type="primary" @click="$router.push('/bpm/process-instance/detail?id=' + form.formId)">
        <dict-tag :type="DICT_TYPE.APPLY_STATUS" :value="form.applyStatus" />
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {createOrderSpecial, getOrderSpecial} from "@/api/ecw/order"
import {getUnitList} from "@/api/ecw/unit"
import {getChannel} from "@/api/ecw/channel"
import { getCurrencyList } from '@/api/ecw/currency'
import { getProductType } from '@/api/ecw/productType'
import WorkFlow from '@/components/WorkFlow'
import {getDarkReturnCommission} from '@/api/ecw/customerCommission'
import Decimal from 'decimal.js'

export default {
  name: "OrderSpecialCommission",
  props: {
    order: Object,
    orderItem: Object,
  },
  components: {
    WorkFlow
  },
  created() {
    // 查看详情，列表进来的
    this.getOrderSpecial()

    getUnitList().then(res => this.unitList = res.data)
    getCurrencyList().then(res => this.currencyList = res.data)

    getProductType(this.orderItem.prodType).then(res => {
      this.productType = res.data
    })
    if(this.order.channelId){
      getChannel(this.order.channelId).then(res => {
        this.channel = res.data
      })
    }
  },
  data() {
    return {
      applyType: 3, // 1是优惠申请2是管理折扣3是佣金设置4是重货优惠5是泡货优惠
      unitList:[],
      currencyList:[],
      ccIdArr: [],
      form: {
        type: 3
      },
      rules:{
        seaFreight      : {required: true, message: '运费不能为空'},
        clearanceFreight: {required: true, message: '清关费不能为空'}
      },
      productType: null,
      channel: null,
      darkCommission: null
    }
  },
  watch:{
    ccIdArr(){
      this.$set(this.form, 'ccIds', this.ccIdArr.join(','))
    },
    'form.commissionType'(val, old){
      if(typeof old !='undefined' && old != val){
        this.$set(this.form, 'lightCommissionAmount', 0)
        this.$set(this.form, 'shadeCommissionAmount', 0)
      }
      
      
      // 暗佣需要查询暗佣设置
      if(val == 2){
        this.getCommission()
      }
    }
  },
  methods: {
    Decimal(n){
      return new Decimal(n)
    },
    handleSubmit(){
      this.$refs.form.validate().then(res => {
        createOrderSpecial(Object.assign({}, this.form, {applyType: this.applyType})).then(res => {
          this.$message.success(this.$t('提交成功'))
          this.$emit('success')
        })
      })
    },
    getOrderSpecial(){
      getOrderSpecial(this.order.orderId, this.applyType, {orderItemId: this.orderItem.orderItemId}).then(r => {
        this.form = r.data
      })
    },
    /* getProductTypeNameById(id){
      return this.$l(this.productTypeList.find(e => e.id === id), 'title')
    }, */
    closeDialog(){
      this.$emit('close')
    },
    getCommission(){
        getDarkReturnCommission({
          customerId: this.order.customerId,
          customsType: this.order.customsType,
          darkCurrency: this.orderItem.seaFreightCurrency,
          darkUnit: this.order.seaFreightVolume,
          departureId: this.order.departureVO.departureId,
          objectiveId: this.order.objectiveVO.objectiveId,
          productAttr: this.orderItem.prodAttrIds.split(',').filter(item => item && item != ''),
          productType: this.orderItem.prodType,
          transportId: this.order.transportId,
          type: 2, // 暗佣
        }).then(res => {
          this.darkCommission = res.data?.darkCommission
        })
    }
  },
  computed: {
    // 是否可以提交
    submitable(){
      let submitable = false;
      [
        ['orgLightCommissionAmount', 'lightCommissionAmount'],
        ['orgShadeCommissionAmount', 'shadeCommissionAmount'],
        ['commissionType', 'orgCommissionType']
      ].forEach(item => {
        if(this.form[item[0]] != this.form[item[1]]){
          submitable = true
        }
      })
      return submitable
    },
    // 根据渠道id显示渠道名
    getChannelNameById(){
      return channelId => {
        const s = this.channelList.find(item => item.channelId == channelId) ?. nameZh
        return s ? '【' + s + '】' : ''
      }
    },
    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
    }
  }
}
</script>
