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

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

			</el-form-item>

			<el-form-item label="*运费" v-if="[2,3,4,5,6,7].indexOf(form.type) > -1">
				<div class="fee-item" v-for="(item, index) in freightFeeList" :key="index">
                    <template v-if="[1,2,3,4,5].indexOf(form.type) > -1">
                        满
                        <el-input v-model="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="[2,4,5].indexOf(form.type) > -1" v-model="item.fullCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" 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">减</span>
                        <span v-if="[4].indexOf(form.type) > -1">折扣率</span>
                        
                        <span v-if="[5].indexOf(form.type) > -1">收</span>
                        
                        <el-input v-if="[2,3,4].indexOf(form.type) > -1" type="number" v-model="item.reduceAmount" style="width:100px" />

                        <Selector v-if="[2,3].indexOf(form.type) > -1" v-model="item.fullCurrencyId" :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" style="width:100px" />
                        ≤ <el-input v-model="item.endAmount" style="width:100px" />
                        <Selector v-model="item.startAndEndCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
                        价格
                    </template>
                    
                    <el-input v-if="[5,6,7].indexOf(form.type) > -1" type="number" v-model="item.netReceiptsAmount" style="width:100px" />
                    <Selector v-if="[5,6,7].indexOf(form.type) > -1" v-model="item.netReceiptsCurrencyId" :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>

                    <el-button class="el-icon-plus" size="mini" type="primary" @click="freightFeeList.push({})" />
                    <el-button v-if="freightFeeList.length > 1" class="el-icon-minus" size="mini" type="danger" @click="freightFeeList.splice(index,1)" />
                </div>

			</el-form-item>
            
			<el-form-item label="清关费" v-if="[2,3,4,5,6,7].indexOf(form.type) > -1">
                <div class="fee-item" v-for="(item, index) in clearanceFeeList" :key="index">
                    <template v-if="[1,2,3,4,5].indexOf(form.type) > -1">
                        满
                        <el-input v-model="item.fullAmount" style="width:100px" />
                        <Selector v-if="[2,4,5].indexOf(form.type) > -1" v-model="item.fullCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" 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">减</span>
                        <span v-if="[4].indexOf(form.type) > -1">折扣率</span>
                        
                        <span v-if="[5].indexOf(form.type) > -1">收</span>
                        
                        <el-input v-if="[2,3,4].indexOf(form.type) > -1" type="number" v-model="item.reduceAmount" style="width:100px" />

                        <Selector v-if="[2,3].indexOf(form.type) > -1" v-model="item.fullCurrencyId" :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" style="width:100px" />
                        ≤ <el-input v-model="item.endAmount" style="width:100px" />
                        <Selector v-model="item.startAndEndCurrencyId" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
                        价格
                    </template>
                    
                    <el-input v-if="[5,6,7].indexOf(form.type) > -1" type="number" v-model="item.netReceiptsAmount" style="width:100px" />
                    <Selector v-if="[5,6,7].indexOf(form.type) > -1" v-model="item.netReceiptsCurrencyId" :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>

                    <el-button class="el-icon-plus" size="mini" type="primary" @click="freightFeeList.push({})" />
                    <el-button v-if="freightFeeList.length > 1" class="el-icon-minus" size="mini" type="danger" @click="freightFeeList.splice(index,1)" />
                </div>
				
			</el-form-item>




			<!-- <el-form-item label="使用条件(优惠卷专用)" prop="cashCondition">
				<el-input
					v-model="form.cashCondition"
					placeholder="请输入使用条件(优惠卷专用)"
				/>
			</el-form-item>
			<el-form-item label="减免金额(优惠卷专用)" prop="reduceAmount">
				<el-input
					v-model="form.reduceAmount"
					placeholder="请输入减免金额(优惠卷专用)"
				/>
			</el-form-item>
			<el-form-item label="条件货币ID" prop="conditionCurrencyId">
				<el-input
					v-model="form.conditionCurrencyId"
					placeholder="请输入条件货币ID"
				/>
			</el-form-item>
			<el-form-item label="开始时间" prop="startTime">
				<el-date-picker
					clearable
					v-model="form.startTime"
					type="date"
					value-format="yyyy-MM-dd"
					placeholder="选择开始时间"
				/>
			</el-form-item>
			<el-form-item label="减免货币ID" prop="reduceCurrencyId">
				<el-input
					v-model="form.reduceCurrencyId"
					placeholder="请输入减免货币ID"
				/>
			</el-form-item>
			<el-form-item label="结束时间" prop="endTime">
				
			</el-form-item>
			<el-form-item label="领券后X天起生效" prop="afterReceiveDays">
				<el-input
					v-model="form.afterReceiveDays"
					placeholder="请输入领券后X天起生效"
				/>
			</el-form-item>
			<el-form-item label="有效天数" prop="validDays">
				<el-input
					v-model="form.validDays"
					placeholder="请输入有效天数"
				/>
			</el-form-item>
			<el-form-item
				label="费用类型"
				prop="costType"
			>
				<dict-selector :type="DICT_TYPE.ECW_COUPON_COST_TYPE" v-model="form.costType"/>
			</el-form-item> -->
			<!-- <el-form-item label="优惠清单" prop="discountDetailed">
				<el-input
					v-model="form.discountDetailed"
					placeholder="请输入优惠清单"
				/>
			</el-form-item>
             -->
			<el-form-item
				label="同类叠加"
				prop="isSimilarSuperposition"
                v-if="form.type != 1"
			>
                <dict-selector
					form-type="radio"
                    :type="DICT_TYPE.ECW_YESNO" 
					v-model="form.isSimilarSuperposition"
					placeholder="请选择类型"
				/>
			</el-form-item>

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

			<el-form-item
				label="适用用户"
				prop="suitableUserType"
			>
                <dict-selector :type="DICT_TYPE.ECW_SUITABLE_USER_TYPE" v-model="form.suitableUserType" defaultable />
                <customers-selector  v-if="showCustomerSelector" v-model="form.customerIds" style="margin-top:5px" />
			</el-form-item>
            <el-form-item
				label="适用线路类型"
				prop="suitableLineType"
                v-if="form.type != 1"
			>
                <dict-selector :type="DICT_TYPE.ECW_SUITABLE_LINE_TYPE" v-model="form.suitableLineType" />
                <routers-selector  v-if="showRouterSelector" v-model="form.lineIds" style="margin-top:5px" />
			</el-form-item>
			<el-form-item
				label="适用商品"
				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" />
			</el-form-item>
			<el-form-item
				label="订单属性"
				prop="orderAttr"
                v-if="form.type != 1"
			>
				<dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_ORDER_ATTR" v-model="form.orderAttr" multiple />
			</el-form-item>
            <el-form-item label="是否发送站内信" prop="isSiteContent">
				<dict-selector form-type="radio" :type="DICT_TYPE.ECW_YESNO" v-model="form.isSiteContent" />
			</el-form-item>
            <el-form-item label="中文内容" prop="contentZh" :rules='[{required: true, message: "不能为空"}]'>
				<editor v-model="form.contentZh" :min-height="192" />
			</el-form-item>
            <el-form-item label="英文内容" prop="contentEn" :rules='[{required: true, message: "不能为空"}]'>
				<editor v-model="form.contentEn" :min-height="192" />
			</el-form-item>
            <el-form-item
				label="品牌"
				prop="brand"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.BRAND_REG_TYPE" v-model="form.brand" multiple />
			</el-form-item>
            <el-form-item
				label="是否控货"
				prop="isCargoControl"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_YESNO" v-model="form.isCargoControl" multiple />
			</el-form-item>
            <el-form-item
				label="单证报关"
				prop="documentDeclaration"
                v-if="form.type != 1"
			>
                <dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="form.documentDeclaration" multiple />
			</el-form-item>
			<!--el-form-item
				label="每个用户领券上限，如不填则默认为1"
				prop="limitNum"
			>
				<el-input
					v-model="form.limitNum"
					placeholder="请输入每个用户领券上限，如不填则默认为1"
				/>
			</el-form-item>
			<el-form-item
				label="优惠券过期状态 0:过期 1:未过期"
				prop="overdueStatus"
			>
				<el-radio-group v-model="form.overdueStatus">
					<el-radio label="1">请选择字典生成</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item
				label="优惠券投放状态(-1:取消投放 0:等待投放 1:投放 2:违规下架 3:等待审核)"
				prop="putonStatus"
			>
				<el-radio-group v-model="form.putonStatus">
					<el-radio label="1">请选择字典生成</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="获取方式 0=客户领取 1=平台发放" prop="getWay">
				<el-input
					v-model="form.getWay"
					placeholder="请输入获取方式 0=客户领取 1=平台发放"
				/>
			</el-form-item>
			
			
			<el-form-item
				label="是否控货(可多选) 0否 1是"
				prop="isCargoControl"
			>
				<el-input
					v-model="form.isCargoControl"
					placeholder="请输入是否控货(可多选) 0否 1是"
				/>
			</el-form-item>
			<el-form-item
				label="单证报关(可多选) 1 我司全代 2自单代报 3混合报关"
				prop="documentDeclaration"
			>
				<el-input
					v-model="form.documentDeclaration"
					placeholder="请输入单证报关(可多选) 1 我司全代 2自单代报 3混合报关"
				/>
			</el-form-item>
			<el-form-item label="优惠券状态(0:草稿 1:发布)" prop="status">
				<el-radio-group v-model="form.status">
					<el-radio label="1">请选择字典生成</el-radio>
				</el-radio-group>
			</el-form-item-->
            <el-form-item>
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="$router.back()">返 回</el-button>
                <el-button type="default" @click="reset">重 置</el-button>
			</el-form-item>
        </el-form>
	</div>
</template>
<script>
import { getCurrencyList } from '@/api/ecw/currency';
import { getUnitList } from '@/api/ecw/unit';
import {
	createCoupon,
	updateCoupon,
	deleteCoupon,
	getCoupon,
	getCouponPage,
	exportCouponExcel,
} from "@/api/ecw/coupon";
import CustomersSelector from '@/components/CustomersSelector'
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'

export default {
	name: "CouponEdit",
	components: {CustomersSelector, RoutersSelector, ProductsSelector, Editor, Selector},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 表单参数
			form: {
                status: 1,
            },
			// 表单校验
			rules: {},
            currencyList:[],
            clearanceFeeList:[{},{}],
            freightFeeList:[{},{}],
            discountList:[{}], // 优惠券固定一条
            unitList:[]
		};
	},
    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'
        },
        discountDetailedVOs(){
            let activeField = null
            let fields = ['clearanceFeeList', 'freightFeeList']
            fields.forEach(field => {
                this[field].forEach(feeItem => {
                    if(feeItem.reduceAmount){
                        activeField = field
                    }
                })
            })
            let discountedList = activeField ? this[activeField] : []
            discountedList.forEach(item => {
                [
                    'endAmount',
                    'fullAmount',
                    'fullCurrencyId',
                    'netReceiptsAmount',
                    'netReceiptsCurrencyId',
                    'prodUnit',
                    'reduceAmount',
                    'reduceCurrencyId',
                    'startAmount',
                    'startAndEndCurrencyId'
                ].forEach(field => {
                    if(item[field])item[field] = parseFloat(item[field])
                })
            })
            return discountedList
        }
    },
    watch:{
        'form.type'(val){
            // 方数满减3和特价6需要单位
            if((val == 3 || val == 6) && !this.unitList.length){
                this.getUnitList()
            }
        }
    },
	created() {
        getCurrencyList().then(res => this.currencyList = res.data)
		if (this.$route.query.id) {
			getCoupon(this.$route.query.id).then(
				(res) => (this.form = res.data)
			);
		}
        this.reset()
	},
	methods: {
        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: undefined,
				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");
		},

		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate((valid) => {
				if (!valid) {
					return;
				}
                let data = Object.assign({}, this.form, {discountDetailedVOs: this.discountDetailedVOs})
                // 开始时间必填
                if(!data.startTime)data.startTime = '2022-01-01 00:00:00'
                // status必填
                data.status = 0
				// 修改的提交
				if (data.couponId != null) {
					updateCoupon(data).then((response) => {
						this.$modal.msgSuccess("修改成功");
						this.$router.back();
					});
					return;
				}
				// 添加的提交
				createCoupon(data).then((response) => {
					this.$modal.msgSuccess("新增成功");
					this.$router.back();
				});
			});
		},
	},
};
</script>
<style scoped lang="scss">
.fee-item{
    padding: 5px 0;
    >div{
        margin-right: 5px;
    }
}
</style>