const _Http = getApp().globalData.http;

import {
    getHeight
} from "../../utils/getHeight";
import {
    formatTime
} from "../../utils/getTime"
Component({
    options: {
        multipleSlots: true
    },
    properties: {
        rule: {
            type: Boolean,
            value: true
        },
        list: {
            type: {
                type: Array
            },
            value: [{
                label: "筛选1",
                index: null,
                showName: "name", //显示字段
                valueKey: "name", //返回Key
                selectKey: "id", //传参 代表选着字段 不传参返回整个选择对象
                value: "", //选中值
                default: "", //默认索引
                list: [{
                    name: "a1",
                    id: 0
                }, {
                    name: "a2",
                    id: 1
                }]
            }]
        },
        show: {
            type: Boolean
        },
        handle: {
            type: Function
        }, //按钮回调函数
        dateRange: {
            type: Boolean
        }, //是否开启日期范围筛选
        dateRangeName: {
            type: String,
            value: "日期范围"
        },
        dateRange1: {
            type: Boolean
        }, //是否开启日期范围筛选
        zIndex: {
            type: String,
            value: 99999,
        },
        interrupt: {
            type: Function
        },
        isReset: {
            type: Boolean,
            value: true
        },
        minus: {
            type: [Number, String],
            value: 80
        }
    },
    data: {
        startdate: "", //开始时间
        enddate: "", //结束时间
        periodstart: "",
        periodend: ""
    },
    observers: {
        "show"(newVal) {
            if (newVal) getHeight('.head', this).then(res => this.setData({
                listHeight: res - this.data.minus
            }));
        }
    },
    lifetimes: {
        attached() {
            getApp().globalData.Language.getLanguagePackage(this)
        }
    },
    methods: {
        /* 选择 */
        onSelect(e) {
            const {
                item, //被选项
                index, //列表下标
                i //被选项下标
            } = e.currentTarget.dataset;
            if (this.data.list[index].index == i) {
                this.setData({
                    [`list[${index}].value`]: "",
                    [`list[${index}].index`]: null
                });
            } else {
                this.setData({
                    [`list[${index}].value`]: this.data.list[index].selectKey ? item[this.data.list[index].selectKey] : item,
                    [`list[${index}].index`]: i
                });
            };
            if (this.data.list[index].interrupt) this.triggerEvent("interrupt", {
                item,
                index,
                name: this.data.list[index].selectKey,
                data: this.data.list[index],
                list: this.data.list
            })
        },
        onSelectCheckbox(e) {
            const {
                item, //被选项
                index, //列表下标
                i //被选项下标
            } = e.currentTarget.dataset,
                list = this.data.list;
            if (list[index].index == "" || list[index].index == null) {
                list[index].index = [];
                list[index].value = [];
            }
            let arrIndex = list[index].index.indexOf(i)
            if (arrIndex == -1) {
                list[index].index.push(i)
                list[index].value.push(list[index].selectKey ? item[list[index].selectKey] : item)
                try {
                    if (item.mutextags.length) {
                        try {
                            list[index].ops[item.tag] = item.mutextags;
                        } catch (error) {
                            list[index].ops = {};
                            list[index].ops[item.tag] = item.mutextags;
                        }
                    }
                } catch (error) {
                    if (item.mutextag.length) {
                        try {
                            list[index].ops[item.tag] = item.mutextag;
                        } catch (error) {
                            list[index].ops = {};
                            list[index].ops[item.tag] = item.mutextag;
                        }
                    }
                }
            } else {
                list[index].index.splice(arrIndex, 1)
                list[index].value.splice(arrIndex, 1)
                try {
                    if (item.mutextags.length) {
                        delete list[index].ops[item.tag]
                    }
                } catch (error) {
                    if (item.mutextag.length) {
                        delete list[index].ops[item.tag]
                    }
                }
            };
            list[index].disableds = [];
            for (const key in list[index].ops) {
                list[index].disableds = list[index].disableds.concat(list[index].ops[key].map(v => v.tag))
            }
            this.setData({
                list
            })
            if (this.data.list[index].interrupt) this.triggerEvent("interrupt", {
                item,
                index,
                name: this.data.list[index].selectKey,
                list
            })
        },
        /* 点击按钮 */
        onClick(e) {
            const {
                name
            } = e.target.dataset;
            if (name == 'reset') {
                this.setData({
                    startdate: '',
                    enddate: ''
                })
                this.setData({
                    list: this.data.list.map(v => {
                        let value = "",
                            index = null;
                        try {
                            if ((v.default+'').length) {
                                value = v.selectKey ? v.list[v.default][v.selectKey] : v.list[v.default]
                            }
                        } catch (error) {

                        }
                        v.value = value;
                        v.index = index;
                        if (index != null && v.relevance == 'dateRange') this.queryMonths(v.list[index].queryMonths)
                        return v;
                    })
                })
                let MultilevelClass = this.selectComponent("#MultilevelClass");
                if (MultilevelClass) MultilevelClass.clearChild()
            };
            let obj = {};
            this.data.list.forEach(v => {
                if (v.type == 'multilevelClass') {
                    obj[v.valueKey] = getApp().globalData.temporaryId;
                    delete(getApp().globalData.temporaryId);
                } else if (v.type == 'checkbox') {
                    obj[v.valueKey] = v.value || [];
                } else {
                    try {
                        if (v.value != null && v.value != undefined && String(v.value).length) {
                            obj[v.valueKey] = v.value
                        } else {
                            obj[v.valueKey] = v.list[v.default][v.selectKey] || ''
                        }
                    } catch (error) {
                        obj[v.valueKey] = v.value
                    }
                }
            });
            if (this.data.dateRange) {
                obj.startdate = this.data.startdate;
                obj.enddate = this.data.enddate;
            };
            if (this.data.dateRange1) {
                obj.periodstart = this.data.periodstart;
                obj.periodend = this.data.periodend;
            };
            obj.name = name;
            this.triggerEvent("handle", obj);
            this.onClose();
        },
        /* 筛选日期范围 */
        changeDate(e) {
            const name = e.currentTarget.dataset.name,
                value = e.detail.value;
            let data = this.data.list.find(v => v.relevance == "dateRange")
            if (data) {
                data.index = null;
                this.setData({
                    list: this.data.list
                })
            }
            this.setData({
                [name]: value
            })
        },
        setTimeCycle(startdate = "", enddate = "") {
            console.log(startdate, enddate)
            if (typeof startdate == 'object') {
                startdate = formatTime(startdate, '-').split(' ')[0]
            }
            if (typeof enddate == 'object') {
                enddate = formatTime(enddate, '-').split(' ')[0];
            }
            this.setData({
                startdate,
                enddate,
            })
        },
        //本周
        getWeekRange(date = new Date()) {
            const startOfWeek = new Date(date);
            const endOfWeek = new Date(date);
            // 获取本周的第一天（周一）
            const dayOfWeek = startOfWeek.getDay();
            const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
            startOfWeek.setDate(startOfWeek.getDate() + diffToMonday);
            startOfWeek.setHours(0, 0, 0, 0);
            // 获取本周的最后一天（周日）
            endOfWeek.setDate(endOfWeek.getDate() + (7 - dayOfWeek));
            endOfWeek.setHours(23, 59, 59, 999);
            this.setTimeCycle(startOfWeek, endOfWeek)
        },
        //本月
        getMonthRange(date = new Date()) {
            const startOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
            const endOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
            endOfMonth.setHours(23, 59, 59, 999);
            this.setTimeCycle(startOfMonth, endOfMonth)
        },
        //上月
        getLastMonthRange(date = new Date()) {
            const year = date.getFullYear();
            const month = date.getMonth(); // Current month (0-based index)
            const startOfLastMonth = new Date(year, month - 1, 1); // First day of last month
            const endOfLastMonth = new Date(year, month, 0); // Last day of last month
            endOfLastMonth.setHours(23, 59, 59, 999); // Set end time to the last millisecond of the day
            this.setTimeCycle(startOfLastMonth, endOfLastMonth);
        },
        //本年
        getYearRange(date = new Date()) {
            const startOfYear = new Date(date.getFullYear(), 0, 1);
            const endOfYear = new Date(date.getFullYear(), 11, 31);
            endOfYear.setHours(23, 59, 59, 999);
            this.setTimeCycle(startOfYear, endOfYear)
        },
        queryDays(num) {
            if (num == -1) return this.setTimeCycle()
            let now = new Date().getTime(),
                end = now,
                beg = end - (num * 86400000);
            this.setTimeCycle(formatTime(new Date(beg), '-').split(' ')[0], formatTime(new Date(end), '-').split(' ')[0])
        },
        queryMonths(period) {
            if (period == -1) return this.setTimeCycle()
            let startdate = formatTime(new Date(), '-').split(' ')[0],
                enddate = formatTime(new Date(), '-').split(' ')[0].split('-');
            for (let i = period; i != 0; i--) {
                enddate[1] = Number(enddate[1]) - 1;
                if (enddate[1] == 0) {
                    enddate[1] = 12;
                    enddate[0] = enddate[0] - 1;
                }
                if (i == 1 && enddate[1] < 10) enddate[1] = "0" + enddate[1]
            }
            let lastDay = new Date(enddate[0], enddate[1], 0).getDate();
            if (enddate[2] > lastDay) enddate[2] = lastDay;
            this.setTimeCycle(enddate.join("-"), startdate)
        },
        onClose() {
            this.setData({
                show: false
            })
        }
    }
})