import Calendar from "../../components/page-component/diy-form/uni-calendar/util";

export default {
    data() {
        return {
            nowDate: {
                year: '',
                month: '',
                day: '',
            },
            calendar: [],
            weeks: [],
            date: {
                before: '',
                after: '',
                data: [],
            },
            dateData: [],
            weekList: [],
        }
    },
    computed: {
        formatWeeks() {
            const weeks = JSON.parse(JSON.stringify(Object.values(this.weeks))), {
                dateData,
                dataConfig,
                calendar
            } = this;
            if(!dataConfig.calendar_start || !dataConfig.calendar_end){
                return;
            }
            return weeks.map(_ => _.map(day => {
                if(!day){
                    return day;
                }
                let value = {
                        fullDate: day.fullDate,
                        disable: day.disable,
                        stock: '',
                        member_price: '',
                        price: '',

                        top_content: '',
                        end_content: '',
                        text_color: `color: ${day.disable ? '#cccccc' : '#999999'}`,
                    },
                    {year, month, date} = day;

                if (!value.disable) {
                    let {calendar_start, calendar_end} = dataConfig;
                    let startTime = new Date(calendar_start.replace(/-/g, '/'));
                    let endTime = new Date(calendar_end.replace(/-/g, '/'));
                    let fullDate = new Date(value.fullDate.replace(/-/g, '/'));

                    if (fullDate < startTime || fullDate > endTime) {
                        Object.assign(value, {disable: true})
                    }
                }


                let has_select = false;
                for (let _ of dateData) {
                    if (Number(_.date.day) == Number(date)
                        && Number(_.date.month) == Number(month)
                        && Number(_.date.year) == Number(year)
                    ) {
                        has_select = true;
                        const {stock, member_price, calc_price} = _.value
                        Object.assign(value, {
                            stock,
                            member_price,
                            calc_price,
                            end_content: '￥' + calc_price,
                            disable: stock == 0 ? true : value.disable
                        })
                        Object.assign(value, {
                            top_content: '库存' + (stock >= 1000 ? '充足' : stock || 0),
                            text_color: `color: ${value.disable ? '#cccccc' : '#999999'}`,
                        })
                        break;
                    }
                }
                if (!has_select) value.disable = true;

                if (dataConfig.is_alone == 1) {
                    if (day.fullDate === calendar.fullDate) {
                        Object.assign(value, {top_content: '预定', text_color: 'color: #333333'})
                    }
                    if (day.fullDate && this.calendar.fullDate === day.fullDate) {
                        Object.assign(this.calendar, {stock: value.stock, calc_price: value.calc_price})
                    }
                } else {
                    if (day.afterMultiple && dataConfig.has_kuatian == 1) {
                        Object.assign(value, {
                            top_content: '预定',
                            text_color: 'color: #333333',
                            calc_price: 0,
                            end_content: '￥0'
                        })
                    } else if (day.afterMultiple || day.beforeMultiple || day.multiple || day.fullDate === calendar.fullDate) {
                        Object.assign(value, {top_content: '预定', text_color: 'color: #333333'})
                    }
                }

                Object.assign(day, value)
                return Object.assign({
                    ss: this.handlerDay(day)
                }, day);
            }));
        },
        dataConfig() {
            return Object.assign({}, this.goods ? this.goods.form_goods : {});
        },
    },
    filters: {
        formatDate(date) {
            let {before, after} = date, reg = /\d{4}-0?(\d{1,2})-0?(\d{1,2})/, content = '';
            if (before) {
                content += before.replace(reg, "$1月$2号")
            }
            content += ' - '
            if (after) {
                content += after.replace(reg, "$1月$2号")
            }
            return content;
        },
    },
    methods: {
        handlerDay(weeks) {
            let {
                calendar,
                theme,
            } = this;
            let backgroundColor = theme.background_o;
            let activeColor = theme.color;
            let borderColor = theme.border;
            let style = {
                fontSize: '20rpx',
                color: '#333333',
            };
            /////
            if (!weeks.fullDate) {
                return style;
            }
            //////
            if (this.dataConfig.is_alone == 0) {
                if (weeks.multiple) {
                    Object.assign(style, {
                        backgroundColor: backgroundColor,
                        width: '102rpx',
                        color: activeColor,
                    })
                }
                if (weeks.beforeMultiple) {
                    Object.assign(style, {
                        backgroundColor: theme.background_o,
                        borderRadius: `8rpx 0 0 8rpx`,
                        boxSizing: 'border-box',
                        border: `1px solid ${borderColor}`,
                        color: activeColor,
                        borderLeftWidth: '1px',
                    })
                }
                if (weeks.afterMultiple) {

                    Object.assign(style, {
                        backgroundColor: backgroundColor,
                        borderRadius: `0 8rpx 8rpx 0`,
                        boxSizing: 'border-box',
                        border: `1px solid ${borderColor}`,
                        color: activeColor,
                    })
                    if (this.date.data && this.date.data.length == 2) {
                        Object.assign(style, {
                            paddingLeft: '1px',
                            borderLeftWidth: 0,
                        })
                    }
                }
            } else {
                if (weeks.fullDate === calendar.fullDate) {
                    Object.assign(style, {
                        backgroundColor: backgroundColor,
                        borderRadius: '8rpx',
                        color: activeColor,
                        border: `1px solid ${borderColor}`,
                    })
                }
            }
            if (weeks.disable) {
                Object.assign(style, {color: '#cccccc'})
            }
            //////////////;
            return style;
        },
        setDate(date) {
            this.cale.setDate(date)
            this.weeks = this.cale.weeks
            this.nowDate = this.cale.getInfo(date)
        },
        changeMonth({value}) {
            this.setDate(value)
        },
        choiceDate(weeks) {
            if (weeks.disable) return
            try {
                let {has_kuatian, place_unit, day_max, is_day, is_alone} = this.dataConfig;
                /////
                if (is_alone == 0) {
                    let {
                        before,
                        after
                    } = this.cale.multipleStatus
                    if (!this.cale.range) return
                    if (before && !after && weeks.fullDate > before) {
                        let sentinel = false;
                        for (let _ of this.formatWeeks) {
                            for (let week of _) {
                                if (week.fullDate === before) sentinel = true
                                if (sentinel && !!week.disable) sentinel = false;
                                if (week.fullDate === undefined) sentinel = true
                                if (week.fullDate === weeks.fullDate && !sentinel) {
                                    throw new Error('请选择连续可用日期');
                                }
                            }
                        }
                    } else if (before && !after && weeks.fullDate == before) {
                        // weeks.fullDate = '';
                        this.cale.multipleStatus.before = '';
                        this.cale.multipleStatus.after = '';
                        this.cale.multipleStatus.data = [];
                        this.cale._getWeek(weeks.fullDate)

                        this.calendar = weeks;
                        this.weeks = this.cale.weeks
                        this.date = this.cale.multipleStatus;
                        this.updateStock();
                        return;
                    }
                }


                this.cale.setMultiple(weeks.fullDate, is_day, day_max, has_kuatian, place_unit);
                this.calendar = weeks;

                this.weeks = this.cale.weeks
                this.date = this.cale.multipleStatus;
                this.updateStock();
            } catch (error) {
                uni.showToast({title: error.message, icon: 'none'});
            }
        },
        handleParam(){
            const {checked, goods, number, dataConfig, calendar} = this;

            let attrDate = [];
            for (let _ of goods.attr) {
                if (_.id == checked.id) {
                    attrDate = _.date;
                    break;
                }
            }
            let date;
            if (dataConfig.is_alone == 1) {
                date = {
                    before: calendar.fullDate,
                    after: calendar.fullDate,
                    data: calendar.fullDate ? [calendar.fullDate] : []
                }
            } else {
                date = JSON.parse(JSON.stringify(this.date));
            }
            date.data = date.data.map((_,index) => {
                attrDate.forEach(attrinfo => {
                    const {day, month, year, value} = attrinfo.date;
                    if (_ === value) {
                        if(this.dataConfig.has_kuatian == 1 && index + 1 == date.data.length){
                            i = {
                                [_]: 0,
                            }
                        } else {
                            i = {
                                [_]: attrinfo.value.calc_price,
                            }
                        }
                    }
                })
                let i;
                return i;
            })
            return date;
        },
        handleNext() {
            if(this.goods.type === 'form-goods' && this.dataConfig.form_mode_type === 'calendar'){
                if (!this.isSelect()) {
                    uni.showToast({title: '请选择日历信息', icon: 'none'});
                    return;
                }
            }

            let date = this.handleParam();
            const {checked, goods, number} = this;

            let attrs = [];
            checked.attr_list.forEach(_ =>
                attrs.push({
                    attr_id: _.attr_id,
                    attr_group_id: _.attr_group_id
                })
            );
            ////////
            const mch_list = [{
                mch_id: goods.mch_id || 0,
                goods_list: [
                    {
                        id: goods.id,
                        attrs,
                        num: number,
                        cat_id: 0,
                        goods_attr_id: checked.id
                    }
                ]
            }]
            let arr = {
                attr_groups: JSON.stringify(goods.attr_groups),
                mch_list: JSON.stringify(mch_list),
                price: checked.calc_price,
                goods_id: goods.id,
                stock: number,
                date: JSON.stringify(date || [])
            };
            let url = '/pages/goods/goods-form?'
            for (let _ in arr) url += _ + '=' + arr[_] + '&'
            uni.navigateTo({url});
        },
        isSelect() {
            const {dataConfig, calendar, date} = this;
            if (dataConfig.is_alone == 1) {
                let {fullDate} = calendar;
                return !!fullDate;
            } else {
                const {after, before, data} = date;
                return Boolean(after && before);
            }
        },
        updateStock() {
            if (!this.isSelect() || !this.checked) return;
            const {dataConfig, formatWeeks, date, calendar} = this;

            if (dataConfig.is_alone == 1) {
                stock = calendar.stock;
                calc_price = calendar.calc_price;
                this.checked.stock = stock || 0;
            } else {
                let minStock = []
                let allPrice = [];
                if (date.data.length < 2) return;
                for (let i in formatWeeks) {
                    formatWeeks[i].forEach(_ => {
                        let {fullDate, stock, calc_price} = _;
                        date.data.forEach(item => {
                            if (fullDate === item) {
                                minStock.push(Number(stock));
                                allPrice.push(Number(calc_price));
                            }
                        })
                    })
                } 
                this.checked.stock = Math.min(...minStock);
                calc_price = Array.from(allPrice).reduce((a, b) => a + b).toFixed(3).toLocaleString()
                calc_price = calc_price.substr(0,calc_price.length-1)
            }
            this.checked.price = calc_price || 0
            this.checked.calc_price = calc_price || 0
            this.checked.price_member = calc_price || 0;
            let stock, calc_price
        },
        createCalendar() {
            const {calendar_start, calendar_end, is_alone, after_day, is_today} = this.dataConfig,
                formatDate = function (date) {
                    const y = date.getFullYear();
                    let m = date.getMonth() + 1;
                    m = m < 10 ? '0' + m : m;
                    let d = date.getDate();
                    d = d < 10 ? ('0' + d) : d;
                    return y + '-' + m + '-' + d + ' 00:00:00';
                };
            let start = ''
            switch (is_today) {
                case 'none':
                    start = calendar_start
                    break;
                case 'today':
                    const t_c_t = new Date(calendar_start.replace(/-/g, '/')).getTime()
                    start = new Date().getTime() > t_c_t ? formatDate(new Date()) : calendar_start
                    break;
                case 'after':
                    let dateTime = new Date();
                    const a_c_t = new Date(calendar_start.replace(/-/g, '/')).getTime()
                    dateTime = dateTime.setDate(dateTime.getDate() + Number(after_day))
                    start = new Date(dateTime).getTime() > a_c_t ? formatDate(new Date(dateTime)) : calendar_start
                    break;
                default:
                    break;
            }
            if(!start) return;
            let date = new Date(start.replace(/-/g, '/'));
            this.cale = new Calendar({
                date,
                selected: [],
                startDate: start,
                endDate: calendar_end,
                range: is_alone == 0,
            })
            this.setDate(date)
            this.monthList(this.cale)
        },
        monthList({startDate, endDate}) {
            if(!startDate || !endDate){
                return;
            }
            let startTime = new Date(startDate.replace(/-/g, '/'));
            let endTime = new Date(endDate.replace(/-/g, '/'));

            let year = startTime.getFullYear();
            let month = startTime.getMonth() + 1;

            let months = [];
            while (endTime.getFullYear() >= year) {
                let max = endTime.getFullYear() == year ? endTime.getMonth() + 1 : 12;
                for (let i = year == startTime.getFullYear() ? month : 1; i <= max; i++) {
                    months.push({
                        year: year,
                        month: i,
                        value: year + '-' + i + '-1',
                        text: i + '月',
                    })
                }
                year++;
            }
            this.weekList = months;
        },
        upCalendar(info) {
            if (this.goods.type === 'form-goods') {
                this.dateData = info.date;
                this.updateStock()
            }
        }
    }
}
