<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="请选择类型"
					:disabled="!!form.couponId"
				/>
			</el-form-item>
			<el-form-item label="标题中文" prop="titleZh" :rules='[{required: true, message: "不能为空"}]'>
				<el-input
					v-model="form.titleZh"
					placeholder="请输入标题-中文"
				/>
			</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 fee[1]" :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.reduceCurrencyId" :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="fee[1].push({})" />
                    <el-button v-if="fee[1].length > 1" class="el-icon-minus" size="mini" type="danger" @click="fee[1].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 fee[2]" :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.reduceCurrencyId" :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="fee[2].push({})" />
                    <el-button v-if="fee[2].length > 1" class="el-icon-minus" size="mini" type="danger" @click="fee[2].splice(index,1)" />
                </div>
				
			</el-form-item>

			<el-form-item label="叠加优惠" 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">
						暂无可用优惠券
					</div>
				</div>
			</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"
					formatter="bool"
					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 formatter="bool" form-type="radio" :type="DICT_TYPE.ECW_YESNO" v-model="form.isSiteContent" :formater="Boolean" />
			</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>
                <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,
	getCouponSelect
} 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/index'
export default {
	name: "CouponEdit",
	components: {CustomersSelector, RoutersSelector, ProductsSelector, Editor, Selector},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 表单参数
			form: {
                status: 1,
            },
			// 表单校验
			rules: {},
            currencyList:[],
            /* clearanceFeeList:[{},{}],
            freightFeeList:[{},{}],
            discountList:[{}], // 优惠券固定一条 */
            unitList:[],
			couponList: [], // 优惠券列表
			couponIds:[],
			fee:{
				1: [{},{}], // 运费
				2: [{},{}], // 清关费
				3: [{}] // 优惠券专用
			}
		};
	},
    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){
                        costType = type
						return false
                    }
				})
			}
			return costType
		}
    },
    watch:{
        'form.type'(val){
            // 方数满减3和特价6需要单位
            if((val == 3 || val == 6) && !this.unitList.length){
                this.getUnitList()
            }

			// 非优惠券则查询优惠券列表
			if(val && val != 1){
				this.getCouponSelect()
			}
        },
		'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
			}
		}
    },
	created() {
        getCurrencyList().then(res => this.currencyList = res.data)
		if (this.$route.query.id) {
			getCoupon(this.$route.query.id).then((res) => {
					this.form = res.data
					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))
						})
					}
					/* this.costType = this.form.costType */
					
					if(this.form.discountDetailedVOs){
						/* this[['clearanceFeeList', 'freightFeeList', 'discountList'][]] */
						this.fee[this.form.costType] = this.form.discountDetailedVOs
					}
					if(this.costType != this.form.costType){
						console.error(`费用类型冲突，计算出来的类型为${this.costType},接口费用类型为${res.data.costType}，类型为${res.data.type}`)
						this.$alert('费用类型冲突')
					}
					// 非优惠券需要查询出优惠券作为叠加备选
					if(this.form.type != 1){
						this.getCouponSelect()
					}
				}
			);
		}
        this.reset()
	},
	methods: {
		getCouponSelect(){
			getCouponSelect().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: 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;
				}
				if(!this.costType){
					return this.$message('暂无费用设置')
				}
                let data = Object.assign({}, this.form, {discountDetailedVOs: this.fee[this.costType]})
                // 开始时间必填
                if(!data.startTime)data.startTime = '2022-01-01 00:00:00'
                // status必填
                data.status = 0
				data.couponIds = this.couponIds.join(',')
				
				// 费用类型 1 运输费 2 清关费 3 总费用(优惠卷专用)
				if(this.form.type == 1){
					data.costType = 3
				}

				// 修改的提交
				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;
    }
}
.coupon-list{
	max-height: 200px;
	border: 1px solid #ccc;
	padding: 10px;
	overflow-y: auto;
}
</style>