<template>
    <view class="diy-form-menu dir-top-nowrap" :style="[boxStyle]">
        <view class="_diy-form-label"
              :style="{ color: data.title_color}"
              v-if="data.list_style != 3"
              :class="{required: data.is_required}">
            {{ data.title }}
        </view>
        <view :style="[inputStyle]" class="dir-left-nowrap">
            <view v-if="data.type === 'date'" class="menu-basic date dir-left-nowrap cross-center box-grow-1">
                <view class="_diy-form-label box-grow-0"
                      :style="{ color: data.title_color}"
                      v-if="data.list_style == 3"
                      :class="{required: data.is_required}"
                      style="padding: 0;margin-right:16rpx;margin-bottom: 0"
                >
                    {{ calcTextWidth(data.title) }}
                </view>
                <picker class="box-grow-1"
                        v-if="data.type_data.date.is_alone == 1"
                        :mode="data.type"
                        :fields="dateConfig.fields"
                        :start="dateConfig.start"
                        :end="dateConfig.end"
                        @change="changeDateAloneSelect"
                >
                    <view class="dir-left-nowrap cross-center" style="width: 100%">
                        <view class="m-select cross-center box-grow-1"
                              :style="{color: date.alone_at ? data.in_color : data.place_color}">
                            <view class="box-grow-0"
                                  :style="{marginLeft: data.list_style == 3 ? 'auto': 'inherit',marginRight: data.list_style == 3 ? '12rpx': 0}">
                                {{ date.alone_at || data.place_text }}
                            </view>
                        </view>
                        <image class="menu-date-icon box-grow-0" :src="appImg.menu_date"></image>
                    </view>
                </picker>
                <template v-else>
                    <view class="box-grow-1" style="width: 50%;">
                        <picker
                            mode="date"
                            :fields="dateConfig.fields"
                            :start="dateConfig.start"
                            :end="dateConfig.end ? ((date.end_at < dateConfig.end && date.end_at) ? date.end_at : dateConfig.end) : date.end_at"
                            @change="changeDateBeginSelect"
                        >
                            <view class="dir-left-nowrap cross-center">
                                <view class="m-select cross-center"
                                      :style="{color: date.begin_at ? data.in_color : data.place_color}">
                                    {{ date.begin_at || data.place_text }}
                                </view>
                                <image class="menu-date-icon" :src="appImg.menu_date"></image>
                            </view>
                        </picker>
                    </view>
                    <view class="box-grow-0" style="padding: 0 20rpx">至</view>
                    <view class="box-grow-1" style="width: 50%;">
                        <picker
                            mode="date"
                            :fields="dateConfig.fields"
                            :start="(date.begin_at > dateConfig.start && date.begin_at) ? date.begin_at : dateConfig.start"
                            :end="dateConfig.end"
                            @change="changeDateEndSelect"
                        >
                            <view class="dir-left-nowrap cross-center">
                                <view class="m-select cross-center"
                                      :style="{color: date.end_at ? data.in_color : data.place_color}">
                                    {{ date.end_at || data.place_text }}
                                </view>
                                <image class="menu-date-icon" :src="appImg.menu_date"></image>
                            </view>
                        </picker>
                    </view>
                </template>
            </view>
            <!--#ifndef MP-ALIPAY-->
            <picker v-else-if="basicMode" class="box-grow-1"
                    :mode="basicMode"
                    :range-key="setKey[data.type].key"
                    @change="changeSelect"
                    @columnchange="bindMultiPickerColumnChange"
                    :value="multiIndex"
                    :range="infoData">
                <view class="menu-basic dir-left-nowrap cross-center main-between box-grow-1">
                    <template v-if="data.list_style === 3">
                        <view class="_diy-form-label"
                              :style="{ color: data.title_color,padding:0,marginBottom:0,marginRight: '24rpx'}"
                              :class="{required: data.is_required}">
                            {{ calcTextWidth(data.title) }}
                        </view>
                        <view class="dir-left-nowrap cross-center">
                            <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                                {{ multiText || data.place_text }}
                            </view>
                            <view class="f-three"></view>
                        </view>
                    </template>
                    <template v-else>
                        <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                            {{ multiText || data.place_text }}
                        </view>
                        <view class="f-three"></view>
                    </template>
                </view>
            </picker>
            <!--#endif-->
            <!--#ifdef MP-ALIPAY-->
            <picker v-else-if="basicMode === 'selector'" class="box-grow-1"
                    :mode="basicMode"
                    :range-key="setKey[data.type].key"
                    @change="changeSelect"
                    @columnchange="bindMultiPickerColumnChange"
                    :value="multiIndex"
                    :range="infoData">
                <view class="menu-basic dir-left-nowrap cross-center main-between box-grow-1"
                      @click="openMultiLevelSelect">
                    <template v-if="data.list_style === 3">
                        <view class="_diy-form-label box-grow-0"
                              :style="{ color: data.title_color,padding:0,marginBottom:0,marginRight: '24rpx'}"
                              :class="{required: data.is_required}">
                            {{ calcTextWidth(data.title) }}
                        </view>
                        <view class="dir-left-nowrap cross-center">
                            <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                                {{ multiText || data.place_text }}
                            </view>
                            <view class="f-three"></view>
                        </view>
                    </template>
                    <template v-else>
                        <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                            {{ multiText || data.place_text }}
                        </view>
                        <view class="f-three"></view>
                    </template>
                </view>
            </picker>
            <view v-else class="box-grow-1" @click="openMultiLevelSelect">
                <view class="menu-basic dir-left-nowrap cross-center main-between box-grow-1">
                    <template v-if="data.list_style === 3">
                        <view class="_diy-form-label"
                              :style="{ color: data.title_color,padding:0,marginBottom:0,marginRight: '24rpx'}"
                              :class="{required: data.is_required}">
                            {{ calcTextWidth(data.title) }}
                        </view>
                        <view class="dir-left-nowrap cross-center">
                            <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                                {{ multiText || data.place_text }}
                            </view>
                            <view class="f-three"></view>
                        </view>
                    </template>
                    <template v-else>
                        <view class="t-omit" :style="{color: multiText ? data.in_color: data.place_color}">
                            {{ multiText || data.place_text }}
                        </view>
                        <view class="f-three"></view>
                    </template>
                </view>
            </view>
            <!--#endif-->
        </view>
    </view>
</template>

<script>
import {mapState} from "vuex";

export default {
    name: 'diy-form-menu',
    props: {
        index: [Number, String],
        value: Object
    },
    components: {},

    data() {
        return {
            time: {
                begin_time: '',
                end_time: '',
                alone_time: '',
                type: 'time',
                text: '',
            },
            address: {
                type: 'address',
                province_id: 0,
                city_id: 0,
                district_id: 0,
                text: '',
            },
            date: {
                type: 'date',
                begin_at: '',
                end_at: '',
                alone_at: '',
            },
            store: {
                type: 'store',
                store_id: '',
                text: '',
            },
            basic: {
                type: 'basic',
                text: '',
            },
            data: {},
            basicMode: null,
            multiIndex: null,

            setKey: {
                address: {
                    key: 'name',
                    child: 'list',
                },
                basic: {
                    key: 'label',
                    child: 'child',
                },
                store: {
                    key: 'label',
                    child: 'child',
                },
                time: {
                    key: 'label',
                    child: 'child'
                }
            }
        }
    },

    computed: {
        ...mapState({
            appImg: state => state.mallConfig.plugin.diy ? state.mallConfig.plugin.diy.app_image : {},
        }),
        calcTextWidth() {
            return text => text ? text.substring(0, 4) : '';
        },
        boxStyle() {
            let {
                bg_color,
                input_padding,
            } = this.data;
            return {
                backgroundColor: bg_color,
                padding: `20rpx ${input_padding}rpx`,
            }
        },
        inputStyle() {
            let {
                border_color,
                input_radius,
                padding_color,
                list_style,
            } = this.data;
            let style = {
                padding: '0 24rpx',
            }
            if (list_style == 1) {
                Object.assign(style, {
                    borderBottomWidth: '1px',
                    borderBottomStyle: 'solid',
                    borderBottomColor: border_color || padding_color,
                })
            } else {
                Object.assign(style, {
                    border: `1px solid ${border_color || padding_color}`,
                    borderRadius: `${input_radius}rpx`,
                    background: padding_color,
                })
            }
            return style;
        },
        dateConfig() {
            let start, end, fields;
            if (this.data.type === 'date' && this.data.type_data) {
                let {type, is_now, start_at, end_at} = this.data.type_data.date;

                let meYear = new Date().getFullYear();
                let meMonth = new Date().getMonth() + 1;
                meMonth = meMonth.toString().length == 1 ? '0' + meMonth : meMonth
                let meDay = new Date().getDate();
                if (type === 'date') {
                    fields = 'day';
                    start = is_now == 1 ? meYear + '-' + meMonth + '-' + meDay : start_at;
                } else if (type === 'year') {
                    fields = 'year';
                    start = is_now == 1 ? meYear : start_at;
                    start = start ? start.toString() : start;
                } else if (type === 'month') {
                    fields = 'month';
                    start = is_now == 1 ? meYear + '-' + meMonth : start_at;
                }
                end = end_at ? end_at.toString() : end_at;
            }
            return {start, end, fields};
        },
        multiText() {
            return this.data.type !== 'store' ? this.data.type !== 'address'  ? this.data.type !== 'time' ? this.basic.text: this.time.text : this.address.text : this.store.text;
        },
        infoData() {
            function uptime(list, time_data = null){
                let s = new Set(), limit = list.limit_time;

                function all_time(item_time) {
                    let start_1 = Number(item_time[0].split(':')[0]);
                    let start_2 = Number(item_time[0].split(':')[1]);

                    let end_1 = Number(item_time[1].split(':')[0]);
                    let end_2 = Number(item_time[1].split(':')[1]);

                    do {
                        if (start_2 >= 60) {
                            start_2 -= 60;
                            start_1++;
                        }
                        let hour = start_1 < 10 ? '0' + start_1 : start_1,
                            min = start_2 < 10 ? '0' + start_2 : start_2;
                        if (end_2 >= start_2 || end_1 > start_1) {
                            s.add(hour + ':' + min);
                        }
                        start_2 += limit;
                    } while (end_2 >= start_2 || end_1 > start_1)

                    let hour = end_1 < 10 ? '0' + end_1 : end_1,
                        min = end_2 < 10 ? '0' + end_2 : end_2
                    s.add(hour + ':' + min);
                }


                if (time_data === null) {
                    list.start_list.forEach(_ => {
                        all_time(_.time)
                    });
                } else {
                    all_time(time_data)
                }

                let time = Array.from(s);
                time.sort((a, b) => {
                    let a_1 = Number(a.split(':')[0]);
                    let a_2 = Number(a.split(':')[1]);

                    let b_1 = Number(b.split(':')[0]);
                    let b_2 = Number(b.split(':')[1]);
                    if (a_1 === b_1) {
                        return b_2 < a_2 ? 1 : -1;
                    } else {
                        return b_1 < a_1 ? 1: -1
                    }
                })
                time = time.map(_=> {
                    return {label: _};
                });
                return time;
            };

            if (this.basicMode === 'selector') {
                const list = this.data.type_data[this.data.type];
                if (this.data.type === 'time') {
                    if(list.show_type === 'alone'){
                        return uptime(list);
                    } else {
                        let info = [];
                        for(let i of list.start_list){
                            let arr = uptime(list,i.time);
                            while (arr.length > 1){
                                let i = arr.shift();
                                info.push({label: i.label + ' - ' + arr[0].label})
                            }
                        }
                        return info;
                    }
                }
                return this.data.type_data[this.data.type]
            }
            if (this.basicMode === 'multiSelector') {
                let k = this.setKey[this.data.type].child;
                let list = this.data.type_data[this.data.type];

                if (this.data.type === 'time') {
                    let time = uptime(list);
                    let arr = [];
                    for (let index = 1; index < time.length; index++) {
                        if(index + 1 === time.length){
                            continue;
                        }
                        arr.push({label: time[index].label, child: time.slice(index + 1)})
                    }
                    list = arr;
                }
                switch (this.multiIndex.length) {
                    case 2:
                        let first = this.multiIndex[0];
                        return [list, list[first][k]];
                    case 3:
                        let second = this.multiIndex[0];
                        let three = this.multiIndex[1];
                        return [list, list[second][k], list[second][k][three] ? list[second][k][three][k] : []];
                    default:
                        return list;
                }
            }
        },
    },
    created() {
        this.data = this.value;
        let {type, type_data} = this.data;
        let n, multiIndex;
        if (type === 'basic' || type === 'address') {
            n = 0;
            let k = this.setKey[type].child;
            type_data[type].forEach(item1 => {
                n = Math.max(n, 1);
                if (item1[k] && item1[k].length) {
                    n = Math.max(n, 2)
                    item1[k].forEach(item2 => {
                        if (item2[k] && item2[k].length) {
                            n = Math.max(n, 3)
                        }
                    })
                }
            })
            multiIndex = new Array(n).fill(0, 0);
            this.basicMode = multiIndex.length < 2 ? 'selector' : 'multiSelector';
            this.multiIndex = multiIndex.length < 2 ? 0 : multiIndex;
        } else if (type === 'store') {
            this.basicMode = 'selector';
            this.multiIndex = 0;
        } else if (type === 'time') {
            this.basicMode = 'selector';
            this.multiIndex = 0;
        }
    },
    methods: {
        //#ifdef MP-ALIPAY
        calcNewData(list) {
            const self = this;
            return list.map(item => {
                item['name'] = item[self.setKey[self.data.type].key];
                let subList = item[self.setKey[self.data.type].child];
                if (subList && subList.length) {
                    item['subList'] = this.calcNewData(subList);
                } else {
                    item['subList'] = [];
                }
                return item;
            })

        },
        openMultiLevelSelect() {
            const list = this.data.type_data[this.data.type];
            let dellist = JSON.parse(JSON.stringify(this.calcNewData(list)));
            function d(_){
                _.key && delete _.key;
                _.parent_id && delete _.parent_id;
                _.list && delete _.list;
                if(_.subList.length){
                    _.subList.forEach(_ => _ = d(_))
                }
                return _;
            }
            my.multiLevelSelect({
                title: this.data.title,
                list: dellist.map(_ => d(_)),
                success: (res) => {
                    let {success, result} = res
                    if (success) {
                        let arr = [];
                        if (this.data.type === 'address') {
                            let name = '';
                            let address = {
                                province: {id: '', name: ''},
                                city: {id: '', name: ''},
                                district: {id: '', name: ''}
                            };
                            let t = list;
                            while (result.length) {
                                name = result.shift().name;
                                t.forEach(item => {
                                    if (name === item.name) {
                                        arr.push(item.name);
                                        address[item.level] = {
                                            id: item.id,
                                            name: item.name,
                                        }
                                        t = item[this.setKey[this.data.type].child];
                                    }
                                })
                            }
                            this.address.text = arr.join(' - ')
                            this.areaEvent(address);
                        } else {
                            result.forEach(item => arr.push(item.name))
                            this.basic.text = arr.join(' - ')
                            this.$emit('updateValue', {
                                index: this.index,
                                value: this.basic,
                            });
                        }
                    }
                }
            });
        },
        //#endif
        //date
        changeDateBeginSelect({detail}) {
            this.date.begin_at = detail.value;
            this.$emit('updateValue', {
                index: this.index,
                value: this.date,
            });
        },
        changeDateEndSelect({detail}) {
            this.date.end_at = detail.value;
            this.$emit('updateValue', {
                index: this.index,
                value: this.date,
            });
        },
        changeDateAloneSelect({detail}) {
            this.date.alone_at = detail.value;
            this.$emit('updateValue', {
                index: this.index,
                value: this.date,
            });
        },
        ////address
        areaEvent(data) {
            if (data) {
                let {province, city, district} = data;
                this.address.province_id = province.id;
                this.address.city_id = city.id;
                this.address.district_id = district.id;
                //this.address.text = province.name + ' - ' + city.name + ' - ' + district.name
                this.$emit('updateValue', {
                    index: this.index,
                    value: this.address,
                });
            }
        },
        //store
        //other
        bindMultiPickerColumnChange({detail}) {
            let {column, value} = detail;
            this.multiIndex.splice(column, 1, value);
        },
        changeSelect({detail}) {
            this.multiIndex = detail.value;
            let address = {
                province: {id: '', name: ''},
                city: {id: '', name: ''},
                district: {id: '', name: ''}
            };

            if (this.basicMode === 'selector') {
                let item = this.infoData[this.multiIndex];
                if (this.data.type === 'store') {
                    this.store.text = item.label;
                    this.store.store_id = item.value;
                    this.$emit('updateValue', {
                        index: this.index,
                        value: this.store,
                    })
                }
                if (this.data.type === 'address') {
                    Object.assign(address, {
                        province: {id: item.id, name: item.name}
                    })
                    this.address.text = item.name;
                    this.areaEvent(address);
                }
                if (this.data.type === 'time') {
                    this.time.alone_time = item.label;
                    this.time.text = item.label;
                    this.$emit('updateValue', {
                        index: this.index,
                        value: this.time,
                    });
                }
                if (this.data.type === 'basic') {
                    this.basic.text = item.label;
                    this.$emit('updateValue', {
                        index: this.index,
                        value: this.basic,
                    });
                }
            } else {
                let arr = [];
                this.multiIndex.forEach((item, index) => {
                    let label = this.setKey[this.data.type].key;
                    if (this.infoData[index][item] === undefined) {
                        //配置不全情况
                    } else {
                        let content = this.infoData[index][item];
                        if (this.data.type === 'address') {
                            address[content.level] = {
                                id: content.id,
                                name: content.name,
                            }
                        }
                        arr.push(content[label]);
                    }
                })

                if (this.data.type === 'basic') {
                    this.basic.text = arr.join(' - ')
                    this.$emit('updateValue', {
                        index: this.index,
                        value: this.basic,
                    });
                }
                if(this.data.type === 'time'){
                    this.time.begin_time = arr[0];
                    this.time.end_time = arr[1];
                    this.time.text = arr[0] + '-' + arr[1]
                    this.$emit('updateValue', {
                        index: this.index,
                        value: this.time,
                    });
                }
                if (this.data.type === 'address') {
                    this.address.text = arr.join(' - ')
                    this.areaEvent(address);
                }
            }
        }
    }
}
</script>

<style scoped lang="scss">
._diy-form-label {
    padding-left: #{20rpx};
    font-size: #{30rpx};
    white-space: nowrap;
    margin-bottom: #{18rpx};
}

._diy-form-label.required:after {
    content: '*';
    margin-left: 6#{rpx};
    color: #FF4544;
}

.diy-form-menu {
    .menu-basic {
        height: 84#{rpx};
    }

    .menu-basic.date .m-select {
        height: #{84rpx};
    }

    .menu-basic.date {
        position: relative;
    }

    .menu-date-icon {
        height: 30#{rpx};
        width: 30#{rpx};
        margin-left: auto;
    }

    .menu-basic.address > .dir-left-nowrap.cross-center {
        width: 100%;
    }

    .f-three {
        height: 12#{rpx};
        width: 20#{rpx};
        border-top: 10#{rpx} solid #888F9A;
        border-left: 10#{rpx} solid transparent;
        border-right: 10#{rpx} solid transparent;
        border-bottom: 10#{rpx} solid transparent;
        margin-top: 8#{rpx};
        margin-left: 24#{rpx};
    }

    > view {
        font-size: 30#{rpx};
    }
}
</style>
