<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" :disabled="form.applyStatus == 1">
      <el-form-item :label="$t('商品类型')">
        <span>{{ getProductTypeNameById(form.productType) }}</span>
      </el-form-item>
      <el-form-item :label="$t('商品名称')">
        <span>{{ form.prodTitleZh }}</span>
      </el-form-item>
      <el-form-item :label="$t('英文名称')">
        <span>{{ form.prodTitleEn }}</span>
      </el-form-item>
      <el-form-item :label="$t('线路')">
        {{ `【${getDictDataLabel(DICT_TYPE.TRANSPORT_TYPE, form.transportId)}】${ getChannelNameById(form.channelId) }`}}
        {{$t("从【{departureName}】发往【{objectiveName}】", {departureName: form.departureName, objectiveName: form.objectiveName})}}
      </el-form-item>
      
      <el-row v-if="!form.charging">
        <el-col :span="12">
          <el-form-item :label="$t('运费')">
            {{form.orgSeaFreight}} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('清关费')">
            {{form.clearanceFreight}} {{ currencyMap[form.clearanceFreightCurrency] }} / {{ unitMap[form.clearanceFreightVolume] }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('全包价')" v-if="form.charging">
        {{form.orgSeaFreight}} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.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="$t('明佣佣金')" v-if="form.commissionType == 1 || form.commissionType == 3">
        <el-input v-model.number="form.lightCommissionAmount" placeholder="" class="w-100"></el-input>
        {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}
      </el-form-item>

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

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

        <!-- 明佣+暗佣显示 -->
        <div v-if="form.commissionType == 3">
          {{$t('成本价')}}:{{costPrice}} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}
        </div>
        
        <!-- 暗佣显示 -->
        <div v-if="form.commissionType == 2">
          {{$l(form, 'prodTitle')}}
          <template v-if="darkCommission">
            {{$t('暗佣')}}:{{darkCommission}} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}
          </template>
          <el-link type="primary" @click.native="$router.push('/customer/customerCommission?customerId=' + offer.relationId)">{{ $t('去设置') }}</el-link>
        </div>

        <div  v-if="form.commissionType == 1 || form.commissionType == 3">{{$t('销售价')}}:{{ salePrice }} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}</div>
        <div v-if="form.commissionType == 3">{{$t('实际佣金返点')}}:{{form.shadeCommissionAmount + form.lightCommissionAmount }} {{ currencyMap[form.seaFreightCurrency] }} / {{ unitMap[form.seaFreightVolume] }}</div>
      </div>
      <div class="page-title">{{$t('审批流程')}}</div>
      <work-flow xmlkey="sheet_sale" v-model="ccIdArr" />
    </el-form>
    

    <div v-if="form.applyStatus != 1">
      <el-button type="primary" @click="handleSubmit" :disabled="!submitable">{{ $t('提交') }}</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>
      <el-button type="primary" @click="cancelAudit">{{ $t('取消审核') }}</el-button>
      <el-button type="default" @click="closeDialog">{{ $t('返回') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {createOfferSpecial, getOfferSpecial, getOfferSpecialByApproveId} from "@/api/ecw/offer"
import {DICT_TYPE, getDictDataLabel} from "@/utils/dict"
import DictSelector from "@/components/DictSelector"
import {getUnitList} from "@/api/ecw/unit"
import {getChannelList} from "@/api/ecw/channel"
import { getCurrencyList } from '@/api/ecw/currency'
import { getProductTypeList } from '@/api/ecw/productType'
import WorkFlow from '@/components/WorkFlow'
import {getDarkReturnCommission} from '@/api/ecw/customerCommission'
import {cancelProcessInstance} from '@/api/bpm/processInstance'
import Decimal from "decimal.js"
const TYPE = 3
export default {
  name: "Commossion",
  props: {
    offer: Object,
    offerProd: Object,
    /* 
    offerProdId: Number,
    customerId: Number */
  },
  components: {
    DictSelector, WorkFlow
  },
  created() {
    this.getOfferSpecial()

    getUnitList().then(res => this.unitList = res.data)
    getChannelList().then(res => this.channelList = res.data)
    getCurrencyList().then(res => this.currencyList = res.data)
    getProductTypeList().then(res => this.productTypeList = res.data)

  },
  data() {
    return {
      getDictDataLabel,
      DICT_TYPE,
      unitList:[],
      channelList:[],
      currencyList:[],
      productTypeList:[],
      ccIdArr: [],
      form: {
        type: TYPE
      },
      rules:{
        commissionType      : {required: true, message: this.$t('请选择佣金类型')},
      },
      darkCommission: null, // 暗佣佣金
    }
  },
  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 ? this.$t('【') + s + this.$t('】') : ''
      }
    },
    // 最初的运费
    initialPrice(){
      return Decimal(this.form.orgSeaFreight || 0)
        // .minus(this.form.orgShadeCommissionAmount || 0)
        .minus(this.form.orgLightCommissionAmount || 0)

    },
    // 新的成本价
    costPrice(){
      return this.initialPrice.minus(this.form.shadeCommissionAmount || 0)
    },
    // 新的销售价
    salePrice(){
      return this.initialPrice.plus(this.form.lightCommissionAmount || 0)
    },
    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
    },
  },
  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: {
    handleSubmit(){
      this.$refs.form.validate().then(res => {
        // 接口运费不能为空,所以这里提交了运费字段
        createOfferSpecial(Object.assign({
          clearanceFreight: this.form.orgClearanceFreight,
          seaFreight: this.form.orgSeaFreight
        }, this.form, {type: TYPE})).then(res => {
          this.$message.success(this.$t('提交成功'))
          this.$emit('success')
        })
      })
    },
    getOfferSpecial(){
      getOfferSpecial(this.offerProd.offerProdId, {type: TYPE}).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.offer.relationId,
          customsType: this.offer.customsType,
          darkCurrency: this.form.orgSeaFreightCurrency,
          darkUnit: this.form.orgSeaFreightVolume,
          departureId: this.offer.departureId,
          objectiveId: this.offer.objectiveId,
          productAttr: this.offerProd.prodAttrIds.split(',').filter(item => item && item != ''),
          productType: this.offerProd.productType,
          transportId: this.offer.transportId,
          type: 2, 
        }).then(res => {
          this.darkCommission = res.data?.darkCommission
        })
    },
    cancelAudit(){
      this.$prompt(this.$t('请输入取消原因?'), this.$t("取消审批"), {
        type: 'warning',
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/, // 判断非空,且非空格
        inputErrorMessage: this.$t("取消原因不能为空"),
      }).then(({ value }) => {
        return cancelProcessInstance(this.form.formId, value);
      }).then(() => {
        this.$modal.msgSuccess(this.$t("取消成功"));
        this.closeDialog()
      })
    },
  }
}
</script>