import { getGradeList, getCategoryList, createIntegralProService, getIntegralMallProInfo, createCategoryService } from '@/service/api/mallApi.js';
import cardTemp from '../common/card-temp.vue';
import { formateDateTimeByType } from '@/utils/index.js';
export default {
    components: {
        'card-temp': cardTemp
    },
    data() {
        return {
            form: {
                integralMallProId: '',
                proReferId: '',
                proName: '', // String 商品名字，优惠券就是所选券的名字。 (必填)
                integralCost: 0, // Number 100 积分费用 (必填)
                cashCost: 0, // Number 现金费用，两位小数
                memberGradeArr: [], // array 适用会员 这里是数组 传给后台要拼接为字符串数组逗号隔开
                limitTimes: 0,
                exchangeDateType: 1,
                exchangeTimeType: 1, // 兑换时间类型 1:全部 2:部分时段
                proShowStatus: 1,
                releaseType: 1,

                exchangeFixDate: ['', ''], // exchangeFixDateBegin // exchangeFixDateEnd,
                exchangeDateDayArr: [],
                exchangeDateWeekArr: [],
                limitTimeBegin: '',
                virtualStock: 0,
                weChatVirtualStock: 0
            },
            rules: {
                integralCost: { required: true, type: 'number', min: 0, message: '请输入积分费用', trigger: 'blur' },
                cashCost: { required: true, type: 'number', min: 0, message: '请输入现金费用', trigger: 'blur' },
                memberGradeArr: { required: true, type: 'array', message: '请选择适用会员', trigger: 'blur' },
            },
            memberGradeOptions: [],
            exchangeDateWeekOptions: ['1', '2', '3', '4', '5', '6', '7'],
            monthOptions: Array.from(Array(31), (v, k) => (k + 1).toString()),
            sendChildData: {
                storeType: 0,
                storeGroupIds: '',
                storeIds: [],
            },
            timeRangeList: [{}],
            isLimitTimes: false,
            isAdd: this.$route.meta.type === 'add',
            isEdit: this.$route.meta.type === 'edit',
            isInfo: this.$route.meta.type === 'info',
        }
    },
    created() {
        this.$store.commit('mutations_breadcrumb', [{ name: '积分商城' }, { name: '优惠券', path: '/coupon' }, { name: this.isAdd ? '新增优惠券' : '编辑优惠券', path: '' }]);
        this.getGradeList();
        // 解决响应式问题
        if (!this.timeRangeList) {
            this.$set(this.timeRangeList, 0, { timeRange: ['', ''] })
        }
        if (this.isEdit || this.isInfo) {
            this.getIntegralMallProInfo();
        }
    },
    computed: {
        asideShow() {
            return this.$store.state.marketing.asideShow
        }
    },
    watch: {
        'form.limitTimes' (val) {
            this.isLimitTimes = (val > 0);
        },
    },

    methods: {
        // init 拉取详情
        async getIntegralMallProInfo() {
            let res = await getIntegralMallProInfo({ integralMallProId: this.$route.params.id });
            if (res.errorCode === 0) {

                const result = res.result;
                this.form.integralMallProId = result.integralMallProId || '';
                this.form.proReferId = result.proReferId || '';
                this.form.proName = result.proName || '';
                this.form.virtualStock = result.virtualStock || 0;
                this.form.integralCost = result.integralCost || 0;
                this.form.cashCost = result.cashCost || 0;
                this.form.memberGradeArr = result.memberGrade ? result.memberGrade.split(',') : [];
                this.form.limitTimes = result.limitTimes || 0;
                this.form.exchangeDateType = result.exchangeDateType || 1;
                this.form.exchangeTimeType = result.exchangeTimeType || 1;
                this.form.proShowStatus = result.proShowStatus || 1;
                this.form.releaseType = result.releaseType || 1;

                this.form.exchangeFixDate = [result.exchangeFixDateBegin || '', result.exchangeFixDateEnd || ''];
                this.form.exchangeDateDayArr = result.exchangeDateDay ? result.exchangeDateDay.split(',') : [];
                this.form.exchangeDateWeekArr = result.exchangeDateWeek ? result.exchangeDateWeek.split(',').filter(v => v) : [];
                this.form.limitTimeBegin = result.limitTimeBegin || '';
                // result.showStore = 2;

                this.sendChildData = {
                    storeType: result.showStore || 0
                }


                if (result.showStore === 1) {
                    this.sendChildData.storeGroupIds = result.storeGroupIds || '';
                } else if (result.showStore === 2) {
                    let list = [];
                    if (result.storeInfo.length) {
                        result.storeInfo.map(v => {
                            list.push(v);
                        })
                    }
                    this.sendChildData.storeIds = list;
                }
                console.log(this.sendChildData)
                if (this.form.exchangeTimeType === 2 && result.timeZones) {
                    let list = result.timeZones.split('#').filter(v => v);
                    list.map((v, i) => {
                        let arr = v.split('-');
                        this.$set(this.timeRangeList, i, { timeRange: [arr[0], arr[1]] })
                    });
                }

                this.isLimitTimes = this.form.limitTimes > 0;
                this.$nextTick(_ => {
                    this.$refs.cardTemp.getCardList();
                })
            }
        },
        //门店分组回执方法
        getSelectGroupData(val) {
            this.sendChildData.storeType = val.storeType || 0
            this.sendChildData.storeGroupIds = val.storeGroupIds || ''
            this.sendChildData.storeIds = val.storeIds || []
        },
        // 拉取会员等级列表
        async getGradeList() {
            let res = await getGradeList();
            if (res.errorCode === 0) {
                this.memberGradeOptions = res.result || [];
            }
            console.log(res);
        },
        // 获取卡券组件回调的对象
        getCardActiveObjFun(val) {
            console.log(val)
            if (val.coupCardId && this.isAdd) {
                this.form.virtualStock = val.couponStock || 0;
                this.form.proReferId = val.coupCardId || '';
                this.form.proName = val.cardName || '';
            }
        },
        // 添加时间段
        addTimeRange() {
            let length = this.timeRangeList.length;
            if (length >= 5) {
                this.$tips({ type: 'warning', message: '最多五个时间段' });
                return;
            }
            this.$set(this.timeRangeList, length, { timeRange: ['', ''] })
        },
        // 删除时间段
        delTimeRange(index) {
            this.timeRangeList.splice(index, 1);
        },

        submit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitService();
                } else {
                    console.log('表单未提交完整');
                }
            });
        },

        submitService() {
            if (!this.form.proReferId) {
                this.$tips({ type: 'warning', message: '请选择优惠券' });
                return;
            }

            console.log(this.timeRangeList)
            let params = {
                integralMallProId: this.form.integralMallProId || '',
                proType: 1, // 商品类型 1 优惠券，2礼品，3实物
                proName: this.form.proName || '', // 商品名字，优惠券就是所选券的名字。
                proReferId: this.form.proReferId || '', // 关联的卡券或者礼品
                proShowStatus: this.form.proShowStatus || 1, // 商品显示状态 1:上架状态就显示 2:兑换状态下显示
                integralCost: this.form.integralCost || 0, // 积分费用
                cashCost: this.form.cashCost || 0, // 现金费用，两位小数
                costValue: this.form.costValue || 0,
                limitTimes: this.isLimitTimes ? this.form.limitTimes : -1, // 次数限制
                memberGrade: this.form.memberGradeArr.length ? this.form.memberGradeArr.join(',') : '', // 适用会员，多个，逗号拼接。
                exchangeDateType: this.form.exchangeDateType || 1, // 兑换日期1:全部 2:固定日期 3:每月 4:每周
                exchangeTimeType: this.form.exchangeTimeType || 1, // 兑换时间类型 1:全部 2:部分时段

                releaseType: this.form.releaseType || 1, // 布发状态 1立即 2定时

                showStore: this.sendChildData.storeType || 0, // 显示门店 0所有 1部分分组 2部分门店


                virtualStock: this.form.virtualStock || 0, //库存
            }

            // 判断 兑换日期
            if (params.exchangeDateType === 2) {
                if (this.form.exchangeFixDate && this.form.exchangeFixDate[0]) {
                    params.exchangeFixDateBegin = formateDateTimeByType(this.form.exchangeFixDate[0], 'yyyy-MM-dd-HH-mm-ss');
                    params.exchangeFixDateEnd = formateDateTimeByType(this.form.exchangeFixDate[1], 'yyyy-MM-dd-HH-mm-ss');
                } else {
                    this.$tips({ type: 'warning', message: '兑换固定日期不能为空' });
                    return;
                }
            } else if (params.exchangeDateType === 3) {
                if (this.form.exchangeDateDayArr.length > 0) {
                    params.exchangeDateDay = this.form.exchangeDateDayArr.join(',');
                } else {
                    this.$tips({ type: 'warning', message: '兑换每月日期不能为空' });
                    return;
                }
            } else if (params.exchangeDateType === 4) {
                if (this.form.exchangeDateWeekArr.length > 0) {
                    params.exchangeDateWeek = this.form.exchangeDateWeekArr.join(',');
                } else {
                    this.$tips({ type: 'warning', message: '兑换每周日期不能为空' });
                    return;
                }
            }

            // 判断 兑换时段
            if (params.exchangeTimeType === 2) {
                let list = [];
                let flag = false;
                let arr = [];
                console.log(JSON.stringify(this.timeRangeList))
                this.timeRangeList.forEach(v => {
                    if (!v.timeRange || !v.timeRange[0]) {
                        flag = true;
                    } else {
                        arr.push(v.timeRange);
                        list.push(v.timeRange[0] + '-' + v.timeRange[1]);
                    }
                })
                if (flag) {
                    this.$tips({ type: 'warning', message: '部分时段未填写完整' });
                    return;
                }
                // list.sort((a,b) => {a.timeRange[0] - b.timeRange[0]})
                // 如果数组为1的话也要传 #分割
                if (list.length === 1) {
                    params.timeZones = list[0] + '#';
                } else {
                    params.timeZones = list.length ? list.join('#') : '';
                }

                let breakFlag = false;
                for (var i = 0; i < arr.length; i++) {
                    if (breakFlag) {
                        break;
                    }
                    var p1 = arr[i];
                    for (var j = i + 1; j < arr.length; j++) {
                        var p2 = arr[j];
                        console.log(p1, p2);
                        if ((p2[0] > p1[0] && p2[0] < p1[1]) || (p2[1] > p1[0] && p2[1] < p1[1]) || (p1[0] > p2[0] && p1[0] < p2[1]) || (p1[1] > p2[0] && p1[1] < p2[1])) {
                            breakFlag = true;
                            break;
                        }
                    }
                }
                if (breakFlag) {
                    this.$tips({ type: 'warning', message: "兑换时段之间不允许出现时间交叠" });
                    return;
                }
            }

            // 判断发送时间
            if (params.releaseType === 2) {
                if (this.form.limitTimeBegin) {
                    params.limitTimeBegin = formateDateTimeByType(this.form.limitTimeBegin, 'yyyy-MM-dd-HH-mm-ss');
                } else {
                    this.$tips({ type: 'warning', message: '定时发布时间不能为空' });
                    return;
                }
            }


            // 门店分组
            console.log(this.sendChildData)
            if (this.sendChildData.storeType === 1) {
                if (this.sendChildData.storeGroupIds) {
                    params.storeGroupIds = this.sendChildData.storeGroupIds || '';
                } else {
                    this.$tips({ type: 'warning', message: '门店分组不能为空' });
                    return;
                }
            } else if (this.sendChildData.storeType === 2) {
                if (this.sendChildData.storeIds.length) {
                    params.storeIds = this.sendChildData.storeIds.map(v => v.storeId).join(',');
                } else {
                    params.storeIds = '';
                    this.$tips({ type: 'warning', message: '部分门店不能为空' });
                    return;
                }
            }

            createIntegralProService(params).then(res => {
                if (res.errorCode === 0) {
                    this.$router.push('/coupon');
                    this.$tips({ type: 'success', message: '操作成功' });
                } else {
                    this.$tips({ type: 'error', message: '操作失败' });
                }
                console.log(res);
            }).catch(err => {
                this.$tips({ type: 'error', message: '操作失败' });
            })
        }
    }
}