<template>
	<div class="app-container">
		<el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="readonly">
			<el-form-item :label="$t('类型')" prop="type" :rules='[{required: true, message: $t("请选择类型")}]'>
				<dict-selector
					:type="DICT_TYPE.ECW_COUPON_TYPE"
					v-model.number="form.type"
					:placeholder="$t('请选择类型')"
					:disabled="!!form.couponId"
				/>
			</el-form-item>
			<el-form-item :label="$t('标题中文')" prop="titleZh" :rules='[{required: true, message: $t("不能为空")}]'>
				<el-input
					v-model="form.titleZh"
					:placeholder="$t('请输入中文标题')"
				/>
			</el-form-item>
			<el-form-item :label="$t('标题英文')" prop="titleEn" :rules='[{required: true, message: $t("不能为空")}]'>
				<el-input
					v-model="form.titleEn"
					:placeholder="$t('请输入英文标题')"
				/>
			</el-form-item>
            <el-form-item :label="$t('有效期')" prop="titleEn">
				<el-date-picker
					clearable
					v-model="form.startTime"
					type="date"
					value-format="yyyy-MM-dd"
					:placeholder="$t('选择开始时间')"
				/>
                ~
                <el-date-picker
					clearable
					v-model="form.endTime"
					type="date"
					value-format="yyyy-MM-dd"
					:placeholder="$t('选择结束时间')"
				/>
                {{$t('注意：留空则表示永久有效')}}
			</el-form-item>

            <!--1:优惠卷 2:金额-满减 3:方数-满减 4 折扣 5优惠 6 特价 7区间价-->
            <el-form-item :label="$t('优惠券金额')" v-if="form.type == 1">
				<div class="fee-item">
                    <el-input v-model="form.reduceAmount"  @keyup.native="checkPositive(form, 'reduceAmount')" style="width:100px" />
                    <selector  v-model="form.reduceCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
                    <span>{{$t('满')}}</span>
                    <el-input type="number" v-model="form.cashCondition"  @keyup.native="checkPositive(form, 'cashCondition')" style="width:100px" />
                    <span>{{$t('使用')}}</span>
                    <span style="color:red">{{$t('注意：留空则表示不受满金额限制')}}</span>
                </div>
			</el-form-item>

			<el-form-item :label="$t('运费')" v-if="[2,3,4,5,6,7].indexOf(form.type) > -1">
				<span slot="label"><span style="color: red">*</span>{{$t('运费')}}</span>
				<div class="fee-item" v-for="(item, index) in fee[1]" :key="index">
					<template v-if="[1,2,3,4,5].indexOf(form.type) > -1">
						{{$t('满')}}
						<el-input v-model="item.fullAmount" @blur="checkPositive(item, 'fullAmount')" style="width:100px" />
						<!-- <el-select v-model="item.fullCurrencyId" style="width:100px" >
							<el-option v-for="item in currencyList" :key="item.id" :label="item.titleZh" :value="item.id" />
						</el-select> -->
						<!-- <selector v-if="[4].indexOf(form.type) > -1" v-model="item.fullCurrencyId" @input="checkReduceCurrency(item)" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" /> -->
						<selector v-if="[2,4,5].indexOf(form.type) > -1" v-model="item.combUnit" @input="checkReduceCurrency(item)" :options="combUnitList" label-field="label" value-field="value" defaultable style="width:100px" />

						<span v-if="[2].indexOf(form.type) > -1">{{$t('减')}}</span>
						<span v-if="[4].indexOf(form.type) > -1">{{$t('折扣率')}}</span>

						<span v-if="[5].indexOf(form.type) > -1">{{$t('收')}}</span>

						<el-input v-if="[2,3,4].indexOf(form.type) > -1" v-model="item.reduceAmount"   @blur="checkPositive(item, 'reduceAmount')" style="width:100px" />

						<selector v-if="[2,3].indexOf(form.type) > -1" v-model="item.reduceCurrencyId" :disabled="!!item.reduceCurrencyDisabled" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
						<span v-if="[4].indexOf(form.type) > -1">%</span>
					</template>
					<template v-if="form.type==7">
						> <el-input v-model="item.startAmount"  @blur="checkPositive(item, 'startAmount')" style="width:100px" />
						≤ <el-input v-model="item.endAmount"  @blur="checkPositive(item, 'endAmount')" style="width:100px" />

						<!-- <selector v-model="item.startAndEndCurrencyId" @input="checkReduceCurrency(item)"  :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
						 -->
						<selector v-model="item.combUnit" @input="checkReduceCurrency(item)" :options="combUnitList" label-field="label" value-field="value" defaultable style="width:100px" />

						{{$t('价格')}}
					</template>

					<el-input v-if="[5,6,7].indexOf(form.type) > -1"  @blur="checkPositive(item, 'netReceiptsAmount')" v-model="item.netReceiptsAmount" style="width:100px" />
					<selector v-if="[5,6,7].indexOf(form.type) > -1" v-model="item.netReceiptsCurrencyId" :disabled="!!item.reduceCurrencyDisabled"  :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />

					<template v-if="form.type == 6">
					/
					<selector v-model="item.prodUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
					</template>

					<!-- 特价只有一行，不显示增删 -->
					<template v-if="form.type != 6">
						<el-button class="el-icon-plus" size="mini" type="primary" @click="fee[1].push({type:1})" />
						<el-button v-if="fee[1].length > 1" class="el-icon-minus" size="mini" type="danger" @click="fee[1].splice(index,1)" />
					</template>
					<!-- <div class="red-tips" v-if="errTips[1] && errTips[1][index]">{{errTips[1][index]}}</div> -->

					<span style="color:red; margin-left: 10px;" v-if="index == 0 && [2,3,4,5].indexOf(form.type) > -1">{{$t('注意：运费/清关费 方案二选一')}}</span>
				</div>
			</el-form-item>

			<el-form-item :label="$t('清关费')" v-if="[2,3,4,5,6,7].indexOf(form.type) > -1">
				<div class="fee-item" v-for="(item, index) in fee[2]" :key="index">
					<template v-if="[1,2,3,4,5].indexOf(form.type) > -1">
						{{$t('满')}}
						<el-input v-model="item.fullAmount"  @blur="checkPositive(item, 'fullAmount')" style="width:100px" />
						<!-- <selector v-if="[2,4,5].indexOf(form.type) > -1" v-model="item.fullCurrencyId" @input="checkReduceCurrency(item)" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" /> -->
						<selector v-if="[2,4,5].indexOf(form.type) > -1" v-model="item.combUnit" @input="checkReduceCurrency(item)" :options="combUnitList" label-field="label" value-field="value" defaultable style="width:100px" />
						<selector v-if="form.type == 3" v-model="item.prodUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />

						<span v-if="[2].indexOf(form.type) > -1">{{$t('减')}}</span>
						<span v-if="[4].indexOf(form.type) > -1">{{$t('折扣率')}}</span>

						<span v-if="[5].indexOf(form.type) > -1">{{$t('收')}}</span>

						<el-input v-if="[2,3,4].indexOf(form.type) > -1"  @blur="checkPositive(item, 'reduceAmount')" v-model="item.reduceAmount" style="width:100px" />

						<selector v-if="[2,3].indexOf(form.type) > -1" v-model="item.reduceCurrencyId" :disabled="!!item.reduceCurrencyDisabled" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
						<span v-if="[4].indexOf(form.type) > -1">%</span>
					</template>
					<template v-if="form.type==7">
						> <el-input v-model="item.startAmount"  @blur="checkPositive(item, 'startAmount')" style="width:100px" />
						≤ <el-input v-model="item.endAmount"  @blur="checkPositive(item, 'endAmount')" style="width:100px" />
						<!-- <Selector v-model="item.startAndEndCurrencyId" @input="checkReduceCurrency(item)" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" /> -->
						<selector v-model="item.combUnit" @input="checkReduceCurrency(item)" :options="combUnitList" label-field="label" value-field="value" defaultable style="width:100px" />
						{{$t('价格')}}
					</template>

					<el-input v-if="[5,6,7].indexOf(form.type) > -1"  @blur="checkPositive(item, 'netReceiptsAmount')" v-model="item.netReceiptsAmount" style="width:100px" />
					<selector v-if="[5,6,7].indexOf(form.type) > -1" v-model="item.netReceiptsCurrencyId" :disabled="!!item.reduceCurrencyDisabled" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />

					<template v-if="form.type == 6">
					/
					<selector v-model="item.prodUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
					</template>
					<!-- 特价只有一行，不显示增删 -->
					<template v-if="form.type != 6">
						<el-button class="el-icon-plus" size="mini" type="primary" @click="fee[2].push({type:2})" />
						<el-button v-if="fee[2].length > 1" class="el-icon-minus" size="mini" type="danger" @click="fee[2].splice(index,1)" />
					</template>

					<!-- <div class="red-tips" v-if="errTips[2] && errTips[1][index]">{{errTips[2][index]}}</div> -->
				</div>

			</el-form-item>

			<el-form-item :label="$t('叠加优惠')" prop="discountDetailed">
				<div class="coupon-list">
					<el-checkbox-group v-model="couponIds">
						<div class="coupon-item" v-for="item in availCouponList" :key="item.couponId">
							<el-checkbox :label="item.couponId">{{item.titleZh}}</el-checkbox>
						</div>
					</el-checkbox-group>
					<div v-if="!availCouponList.length" style="padding:50px">
						{{$t('暂无可用优惠券')}}
					</div>
				</div>
			</el-form-item>
			<el-form-item
				:label="$t('同类优惠不叠加')"
				prop="isSimilarSuperposition"
                v-if="form.type != 1"
			>
                <dict-selector
					form-type="radio"
                    :type="DICT_TYPE.ECW_YESNO"
					v-model="form.isSimilarSuperposition"
					formatter="bool"
					:placeholder="$t('请选择类型')"
					defaultable
				/>
			</el-form-item>

			<!-- <el-form-item :label="$t('可叠加优惠劵列表')" prop="couponIds" v-if="form.type != 1">
				<el-input
					v-model="form.couponIds"
					:placeholder="$t('请输入可叠加优惠劵列表')"
				/>
			</el-form-item> -->

			<el-form-item
				:label="$t('适用用户')"
				prop="suitableUserType"
			>
                <dict-selector v-if="form.type != 1" :type="DICT_TYPE.ECW_SUITABLE_USER_TYPE" v-model="form.suitableUserType" defaultable />
				<dict-selector form-type="radio" v-else :type="DICT_TYPE.ECW_SUITABLE_USER_TYPE" :filter="item => item.colorType == 'danger'" v-model="form.suitableUserType" defaultable />
                <customer-contacts-selector  v-if="showCustomerSelector" v-model="form.customerIds" style="margin-top:5px" />
			</el-form-item>
            <el-form-item
				:label="$t('适用线路类型')"
				prop="suitableLineType"
                v-if="form.type != 1"
			>
				<!---第一个不是全部，所以不能使用defaultable-->
                <dict-selector :type="DICT_TYPE.ECW_SUITABLE_LINE_TYPE" v-model="form.suitableLineType" formatter="number" defaultable />
                <routers-selector  v-if="showRouterSelector" v-model="form.lineIds" :lineIds="form.lineIds" style="margin-top:5px" :option="option" />
			</el-form-item>
			<el-form-item
				:label="$t('适用商品')"
				prop="prodIds"
                v-if="form.type != 1"
			>
                <!-- <dict-selector :type="DICT_TYPE.ECW_SUITABLE_PROD_TYPE" v-model="form.suitableProdType" /> -->
				<products-selector v-model="form.prodIds" :default-ids="form.prodIds" show-all @setall="isAllProduct=$event" :isall="isAllProduct" />
			</el-form-item>
			<el-form-item
				:label="$t('订单属性')"
				prop="orderAttr"
                v-if="form.type != 1"
			>
				<dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_ORDER_ATTR" v-model="form.orderAttrArr" multiple />
			</el-form-item>
            <!-- <el-form-item :label="$t('是否发送站内信')" prop="isSiteContent">
				<dict-selector formatter="bool" form-type="radio" :type="DICT_TYPE.ECW_YESNO" v-model="form.isSiteContent" :formater="Boolean" />
			</el-form-item> -->
            <el-form-item :label="$t('中文内容')" prop="contentZh" :rules='[{required: true, message: $t("不能为空")}]'>
				<editor v-model="form.contentZh" :min-height="192" />
			</el-form-item>
            <el-form-item :label="$t('英文内容')" prop="contentEn" :rules='[{required: true, message: $t("不能为空")}]'>
				<editor v-model="form.contentEn" :min-height="192" />
			</el-form-item>
            <el-form-item
				:label="$t('品牌')"
				prop="brand"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.BOX_SHIPPING_BRAND_TYPE" v-model="form.brandArr" multiple />
			</el-form-item>
            <el-form-item
				:label="$t('是否控货')"
				prop="isCargoControl"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_YESNO" v-model="form.isCargoControlArr" multiple />
			</el-form-item>
            <el-form-item
				:label="$t('单证报关')"
				prop="documentDeclaration"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.documentDeclarationArr" multiple />
			</el-form-item>
        </el-form>
		<div class="pl-100">
			<template v-if="!readonly">
				<el-button type="primary" @click="submitForm(0)" v-hasPermi="['ecw:coupon:draft']">{{$t('保存')}}</el-button>
				<el-button type="primary" @click="submitForm(1)" v-hasPermi="['ecw:coupon:publish']">{{$t('发布')}}</el-button>
				<el-button type="default" @click="reset">{{$t('重置')}}</el-button>
			</template>
			<el-button @click="$router.back()">{{$t('返回')}}</el-button>
		</div>
	</div>
</template>
<script>
import { getCurrencyList } from '@/api/ecw/currency';
import { getUnitList } from '@/api/ecw/unit';
import {
	createCoupon,
	updateCoupon,
	deleteCoupon,
	getCoupon,
	getCouponPage,
	exportCouponExcel,
	getCouponSelect
} from "@/api/ecw/coupon";
import CustomerContactsSelector from '@/components/CustomerContactsSelector'
import {getDictData} from '@/utils/dict'
import RoutersSelector from '@/components/RoutersSelector'
import ProductsSelector from '@/components/ProductsSelector'
import Editor from '@/components/Editor'
import Selector from '@/components/Selector/index'
import {parseTime} from '@/utils/ruoyi'
import {str2arr} from '@/utils/index'
import item from '@/layout/components/Sidebar/Item.vue'
import { getChannelList } from "@/api/ecw/channel"


export default {
	name: "CouponEdit",
	components: {CustomerContactsSelector, RoutersSelector, ProductsSelector, Editor, Selector},
	data() {
		let validatorPositiveNumber = (rule, value, callback) => {
			if(!value || value == '')return callback();
			if (!Number(value)) return callback(new Error('请输入有效数字'))
			let reg = /((^[1-9]\d*)|^0)(\.\d*){0,1}$/;
			if (!reg.test(value)) return callback(new Error('请输入有效数字'));
			callback();
		}
		return {
			validatorPositiveNumber,
			// 遮罩层
			loading: true,
			readonly: false,
			// 表单参数
			form: {
				status: 1,
				isSimilarSuperposition: true
			},
			// 表单校验
			rules: {
				isCargoControl:		[{required: true, message: this.$t('请选择是否控货')}],
				brand:				[{required: true, message: this.$t('请选择品牌')}],
				orderAttr: 			[{required: true, message: this.$t('请选择订单属性')}],
				documentDeclaration: [{required: true, message: this.$t('请选择单证报关')}]
			},
            currencyList:[],
            /* clearanceFeeList:[{},{}],
            freightFeeList:[{},{}],
            discountList:[{}], // 优惠券固定一条 */
            unitList:[],
			couponList: [], // 优惠券列表
			couponIds:[],
			fee:{
				1: [],
				2: [],
				3: []
			},
			errTips: {}, // 跟fee对应的错误提示
			isAllProduct: false, // 是否全部商品
			initing: false, // 初始化中，编辑或者查看的时候，初始化中修改type不改默认值
      option: {channelIds: null, transportId: 1}
		};
	},
    computed:{
      // 是否显示客户选择器
      showCustomerSelector(){
          let dict = getDictData(this.DICT_TYPE.ECW_SUITABLE_USER_TYPE, this.form.suitableUserType)
          return dict && dict.cssClass == 'show-selector'
      },
      // 是否显示路线选择器
      showRouterSelector(){
          let dict = getDictData(this.DICT_TYPE.ECW_SUITABLE_LINE_TYPE, this.form.suitableLineType)
          return dict && dict.cssClass == 'show-selector'
      },
      // 显示显示产品选择器
      showProductsSelector(){
          let dict = getDictData(this.DICT_TYPE.ECW_SUITABLE_PROD_TYPE, this.form.suitableProdType)
          return dict && dict.cssClass == 'show-selector'
      },
      availCouponList(){
        return this.couponList.filter(item => !this.form.isSimilarSuperposition || item.type != this.form.type)
      },
      costType(){
        // 优惠券
        if(this.form.type == 1){
          return 3
        }
        let costType = null
        for(let type in this.fee){
          let feeList = this.fee[type]
          feeList.forEach(item => {
            if(item.reduceAmount || item.netReceiptsAmount){
            	costType = type
            	return false
            }
          })
        }
        return costType
      },
      // 满减组合单位列表
      combUnitList(){
        let arr = []

		// 满减和折扣暂时不需要货币单位
		if(this.form.type != 2 && this.form.type != 4){
			this.currencyList.forEach(item => {
				arr.push({
					label: this.$l(item, 'title'),
					value: 'fullCurrencyId_' + item.id
				})
			})
		}


        this.unitList.forEach(item => {
          arr.push({
            label: this.$l(item, 'title'),
            value: 'prodUnit_' + item.id
          })
        })
        return arr
      }
    },
    watch:{
      'form.type'(val){
        // 非优惠券则查询优惠券列表
        if(val && val != 1){
          this.getCouponSelect()

          if(!this.initing){
			// 非优惠券给默认数据
			this.$set(this.form, 'documentDeclarationArr', ["1", "2", "3"])
			this.$set(this.form, 'isCargoControlArr', ["0", "1"])
			this.$set(this.form, 'orderAttrArr', ["2","3","1"])
			this.$set(this.form, 'brandArr', ["0","1", "2"])
			this.$set(this.form, 'suitableLineType', 0)
		  }
        }

		// 没有优惠券ID的情况下才对特价做处理，有id则表示查看和编辑不做处理
		if(!this.form.couponId && val == 6){
			this.fee[1] = [{type:1}]
			this.fee[2] = [{type:2}]
		}

		// 过一遍费用，禁用/启用、同步 部分货币单位
		[1,2].forEach(index => {
			this.fee[index].forEach(item => {
				this.checkReduceCurrency(item)
			})
		})
      },
      'form.isSimilarSuperposition'(val){
        if(val){
          let keepIds = []
          this.couponIds.forEach((item, index) => {
            if(this.availCouponList.findIndex(coupon => coupon.couponId == item) > -1){
              keepIds.push(item)
            }
          })
          this.couponIds = keepIds
        }
      },
	  'form.orderAttrArr'(v){
		this.$set(this.form, 'orderAttr', v.join(','))
	  },
	  'form.brandArr'(v){
		this.$set(this.form, 'brand', v.join(','))
	  },
	  'form.isCargoControlArr'(v){
		this.$set(this.form, 'isCargoControl', v.join(','))
	  },
	  'form.documentDeclarationArr'(v){
		this.$set(this.form, 'documentDeclaration', v.join(','))
	  }
    },
	created() {
		if(this.$route.query.readonly == 1){
			this.readonly = true
		}
		this.getUnitList()
    getCurrencyList().then(res => this.currencyList = res.data)
		if (this.$route.query.id) {
			this.initing = true
			getCoupon(this.$route.query.id).then((res) => {

				this.form = res.data;
        // 线路种的渠道字段跟价格模块不同，需要转换兼容
        if(this.form.lineIds?.length) {
          this.form.lineIds = this.form.lineIds.map(item => {
            return {...item, shippingChannelId: item.channelId}
          })
        }
				['orderAttr', 'isCargoControl', 'brand', 'documentDeclaration'].forEach(field => {
					this.$set(this.form, field + 'Arr', str2arr(res.data[field]))
				})

				// 没有商品则表示全部
				if(!this.form.prodIds || !this.form.prodIds.length){
					this.isAllProduct = true
				}
				if(this.form.couponIds){
					let couponIds = this.form.couponIds.split(',').filter(item => item && item != '')
					console.log({couponIds})
					this.$nextTick(res => {
						this.couponIds = couponIds.map(item => parseInt(item))
					})
				}
        console.log('lineIds', this.form.lineIds)
        if (this.form.lineIds!=null&&this.form.lineIds.length != 0) {
          if(this.form.lineIds[0].channelId==0) {
            this.option.transportId = 1
          } else {
            this.option.transportId = 3
          }
        }

				if(this.form.discountDetailedVOs){
					/* this[['clearanceFeeList', 'freightFeeList', 'discountList'][]] */
					// this.fee[this.form.costType] = this.form.discountDetailedVOs.filter(item => item.type ==  this.form.costType)
				}
				this.form.discountDetailedVOs.forEach(item => {
					if(item.prodUnit){
						item.combUnit = 'prodUnit_' + item.prodUnit
					}else if(item.fullCurrencyId){
						item.combUnit = 'fullCurrencyId_' + item.fullCurrencyId
					}else{

					}

					this.fee[item.type].push({...item})
				})
				/* if(this.costType != this.form.costType){
					console.error(`费用类型冲突，计算出来的类型为${this.costType},接口费用类型为${res.data.costType}，类型为${res.data.type}`)
					this.$alert(this.$t('费用类型冲突'))
				} */
				// 非优惠券需要查询出优惠券作为叠加备选
				if(this.form.type != 1){
					this.getCouponSelect()
				}

				// 如果是复制，则需要去掉id
				if(this.$route.query.action == 'copy'){
					this.form.couponId = null
				}

				// 对没有默认值的给一个空表单
				[1,2].forEach(type => {
					if(!this.fee[type].length){
						this.fee[type] = [{type}]
					}
				})
			}).finally(() => {
				this.$nextTick(() => {
					this.initing = false
				})
			})
		}
		// 不是编辑查看则给默认的费用表格
		else{
			this.fee = {
				1: [{type:1},{type:1}], // 运费
				2: [{type:2},{type:2}], // 清关费
				3: [{}] // 优惠券专用
			}
		}
    this.reset()
    getChannelList().then(res => {
      var list = []
      for(var i in res.data) {
        list.push(res.data[i].channelId)
      }
      this.option.channelIds = list
    })
	},
	methods: {
		// 满减清关费修改满的货币后需要同步减的货币
		syncClearanceCurrency(item){
			if(this.form.type != 2) return
			item.reduceCurrencyId = item.fullCurrencyId
		},
		// 满减活动如果选择的满多少金额减，则在选择满货币后需要同步减的货币，且禁用减的货币修改
		checkReduceCurrency(item){
			console.log('checkReduceCurrency', {...item}, this.form.type)
			// 金额满减
			if([2,4,5,7].indexOf(this.form.type) > -1){
				// 只要不是按产品单位满减
				if(!item.combUnit || item.combUnit.split('_')[0] != 'prodUnit'){
					this.$set(item, 'reduceCurrencyDisabled', true)
					let currencyId = +item.fullCurrencyId
					if(!currencyId && item.combUnit){
						currencyId = +item.combUnit.split('_')[1]
					}
					if(!currencyId){
						currencyId = this.currencyList[0].id
					}
					// 满减
					if(this.form.type == 2){
						this.$set(item, 'reduceCurrencyId', currencyId)
					}

					// 优惠5,区间价7
					if(this.form.type == 5 || this.form.type == 7){
						this.$set(item, 'netReceiptsCurrencyId', currencyId)
					}
				}else this.$set(item, 'reduceCurrencyDisabled', false)

				return
			}

			// 优惠
			/* if(this.form.type == 5){
				if(!item.fullCurrencyId){
					this.$set(item, 'fullCurrencyId', this.currencyList[0].id)
				}
				// this.$set(item, 'reduceCurrencyDisabled', true)
				this.$set(item, 'netReceiptsCurrencyId', +item.fullCurrencyId)
				return
			} */

			// 区间价
			if(this.form.type== 7){
				if(!item.startAndEndCurrencyId){
					this.$set(item, 'startAndEndCurrencyId', this.currencyList[0].id)
				}
				this.$set(item, 'reduceCurrencyDisabled', true)
				this.$set(item, 'netReceiptsCurrencyId', +item.startAndEndCurrencyId)
				return
			}


			if(item.reduceCurrencyDisabled){
				this.$set(item, 'reduceCurrencyDisabled', false)
			}

		},
		getCouponSelect(){
			getCouponSelect({overdueStatus: 1, status: 1, pageSize: 100}).then(res => {
				this.couponList = res.data
			})
		},
        getUnitList(){
            getUnitList().then(res => this.unitList = res.data)
        },

		/** 表单重置 */
		reset() {
			this.form = {
				couponId: undefined,
				titleZh: undefined,
				titleEn: undefined,
				type: undefined,
				cashCondition: undefined,
				reduceAmount: undefined,
				conditionCurrencyId: undefined,
				startTime: undefined,
				reduceCurrencyId: undefined,
				endTime: undefined,
				afterReceiveDays: undefined,
				validDays: undefined,
				costType: undefined,
				discountDetailed: undefined,
				isSimilarSuperposition: true,
				couponIds: undefined,
				suitableUserType: undefined,
				suitableLineType: undefined,
				suitableProdType: undefined,
				limitNum: undefined,
				overdueStatus: undefined,
				putonStatus: undefined,
				getWay: undefined,
				orderAttr: undefined,
				isSiteContent: undefined,
				isCargoControl: undefined,
				documentDeclaration: undefined,
				status: undefined,
			};
			this.resetForm("form");
		},

		// 检查正数
		checkPositive(object, field){
			console.log('checkPositive', object, field)
			const lastChar = object[field].split('').pop()
			object[field] = parseFloat(object[field])
			if(isNaN(object[field]) || object[field] < 0) object[field] = ''
			else object[field] = object[field].toString()

			// 如果最后一位是.且没有其他点则补上
			if(object[field] != '' && object[field].indexOf('.') == -1 && lastChar == '.') object[field] += '.'
		},

		/** 提交按钮 */
		submitForm(status = 0) {
			this.$refs["form"].validate((valid) => {
				if (!valid) {
					return;
				}
				if(!this.costType){
					return this.$message(this.$t('暂无费用设置'))
				}
				// 非有优惠券需要把运费和清关费一起提交
				this.errTips = {}
				let discountDetailedVOs = this.costType == 3 ? this.fee[3] : this.fee[1].concat(this.fee[2]).filter(item => item.netReceiptsAmount || item.fullAmount)
				discountDetailedVOs.map(item => {
					// 目前只有满减(1)和优惠(5)使用组合单位
					if([2,4,5,7].indexOf(this.form.type) > -1 && item.combUnit){
						// 满减需要 先删除单位，防止编辑的时候切换单位导致两个同时存在
						delete item.fullCurrencyId
						delete item.prodUnit

						let tmp = item.combUnit.split('_')
						/* if(this.form.type == 5){
							item['fullCurrencyId'] =
						} */
						/* if(this.form.type == 7){
							item.startAndEndCurrencyId =
						} */
						// 这里目前只能是满减，优惠会提示 “优惠劵满减货币不能为空”
						item[tmp[0]] = tmp[1]
					}
				})

				this.$set(this.form, 'suitableProdType', this.isAllProduct ? 0 : 1)
        let data = Object.assign({}, this.form, {discountDetailedVOs})
        // 开始时间必填
        if(!data.startTime)data.startTime = parseTime(Date.now()) // '2022-01-01 00:00:00'
        // status必填
        data.status = status
				data.couponIds = this.couponIds.join(',')

				// 费用类型 1 运输费 2 清关费 3 总费用(优惠卷专用)
				if(this.form.type == 1){
					data.costType = 3
				}

				// 没勾选全部就需要选择商品
				if(this.form.type != 1 && !this.isAllProduct && !this.form.prodIds){
					return this.$message.error('请选择商品')
				}
				this.$set(this.form, 'suitableProdType', this.isAllProduct ? 0 : 1)

        // 优惠模块的线路渠道字段跟价格模块不同，需要转换
        if(data.lineIds?.length){
          data.lineIds = data.lineIds.map(item => {
            return {...item, channelId: item.shippingChannelId}
          })
        }

				// 修改的提交
				if (data.couponId != null) {
					updateCoupon(data).then((response) => {
						this.$modal.msgSuccess(this.$t("修改成功"));
						this.$redirect("index");
					});
					return;
				}
				// 添加的提交
				createCoupon(data).then((response) => {
					this.$modal.msgSuccess(this.$t("新增成功"));
					this.$redirect("index");
				});
			});
		},
	},
};
</script>
<style scoped lang="scss">
.fee-item{
    padding: 5px 0;
    >div{
        margin-right: 5px;
    }
}
.coupon-list{
	max-height: 200px;
	border: 1px solid #ccc;
	padding: 10px;
	overflow-y: auto;
}
</style>
