<template>
    <div class="tagfiltrate-wrapper" id="tagfiltrate-wrapper" v-show="!hide" :class="{'dark-model': ifDarkModel}">
        <div class="dropdown-part">
            <template v-for="(items, idx) in queryFieldsForWidget">
                <van-tag
                    v-if="items.type == 'on-off'"
                    :key="idx"
                    class="tagfiltrate-tag tagfiltrate-item"
                    round
                    size="large"
                    :class="{'selected': items.title}"
                    @click="handleSelTag(items.children[0], idx)"
                >
                    <span class="tagfiltrate-tag__text text-ellipsis-one">
                        {{ items.title || items.group }}
                    </span>
                    <van-badge class="tag-badge" v-if="items.children[0].badge" :content="items.children[0].badge" />
                    <template v-if="!items.val && items.title">
                        <i class="iconfont icon-wrong_light" @click.stop="handleSelTag(items.children[0], idx)"></i>
                    </template>
                </van-tag>
                <van-tag
                    v-else-if="items.type == 'year-month'"
                    :key="idx"
                    class="tagfiltrate-tag tagfiltrate-item"
                    round
                    size="large"
                    :class="{'selected': items.title}"
                    @click="handleClickDateTime(items.children[0], idx)"
                >
                    <span class="tagfiltrate-tag__text text-ellipsis-one">
                        {{ items.value | ymDateFilter }}
                    </span>
                    <!-- <template v-if="!items.val && items.value != -1"> -->
                    <template v-if="!items.val && items.title">
                        <i class="iconfont icon-wrong_light" @click.stop="handleReset(idx)"></i>
                    </template>
                </van-tag>
                <!-- <van-badge :content="20" class=" tagfiltrate-item" :key="idx" v-if="items.type == 'on-off'">
                    <van-tag
                        class="tagfiltrate-tag"
                        round
                        size="large"
                        
                        :class="{'selected': items.title}"
                        @click="handleSelTag(items.children[0], idx)"
                    >
                        <span>
                            {{ items.title || items.group }}
                        </span>
                    </van-tag>
                </van-badge> -->
                <van-popover
                    :key="idx"
                    v-else
                    v-model="items.val"
                    trigger="click"
                    class="tabs-recommend-popover tagfiltrate-item"
                    overlay
                    :close-on-click-outside="false"
                    get-container=".body"
                >
                    <template #reference>
                        <van-tag
                            class="tagfiltrate-tag"
                            round
                            size="large"
                            :class="{'selected': items.title}"
                        > 
                            <span class="text-ellipsis-one">
                                {{ items.title || items.group }}
                            </span>
                            <template v-if="!items.val && items.title">
                                <i class="iconfont icon-wrong_light" @click.stop="handleReset(idx)"></i>
                            </template>
                            <template v-else>
                                <i class="iconfont" :class="items.val ? 'icon-up' : 'icon-down'"></i>
                            </template>
                        </van-tag>
                    </template>
                    <component
                        :is="items.type | widgetNameFilter"
                        :key="idx"
                        :data="items"
                        :active-item="items.value"
                        resetBtn
                        @confirm="handleConfirm(arguments, idx)"
                        @reset="handleReset(idx)"
                        model="bottomFilter"
                    ></component>
                </van-popover>
            </template>

            <van-popup v-model="showPopover" position="bottom" get-container="body">
                <van-datetime-picker
                    v-model="currentDate"
                    type="year-month"
                    title="选择年月"
                    :min-date="minDate"
                    :max-date="maxDate"
                    :formatter="formatter"
                    @confirm="handleConfirmDTPicker(arguments, dateTimePickerIdx)"
                    @cancel="showPopover = false"
                />
            </van-popup>
        </div>
        <slot name="right" :clickRightBtn="handleClickRight">
        </slot>
    </div>
</template>

<script>
import WidgetDropDownRadio from "./widget-radio"
import WidgetDropDownCascader from "./widget-cascader"

export default {
    name: 'LjTabsQuick',
    components: {
        WidgetDropDownRadio,
        WidgetDropDownCascader
    },
    data() {
        return {
            queryFieldsForWidget: [], // queryFields数据转换
            currentQueryField: {}, // 当前筛选的值
            currentQueryTitle: {}, // 当前筛选的名
            hide: false,
            showPopover: false,
            showPopover2: false,
            actions: [{ text: '选项一' }, { text: '选项二' }, { text: '选项三' }],
            minDate: new Date(2020, 0, 1),
            maxDate: new Date(2025, 10, 1),
            currentDate: new Date(),
            dateTimePickerIdx: -1,
        };
    },
    props: {
        queryFields: {
            type: Array
            // {
            //     title: 字段描述
            //     property：字段属性名
            //     type: 默认为文字input，可选radio： 单选， checkbox：多选；cell：（）;date：日期, switch: 开关
            //     selectOptions：数据源
                        // optionsApi: 动态获取数据接口名称,
                        // valueMap: 自定义 options 结构中的字段, 例如{ text: 'text', value: 'value', children: 'children' },
                        // extraOptions: 额外的数据数组，通常用于网络请求数据，附加“全部”选项用，如[{scid: -1, scname: "全部"}]
                        // options: 已下载数据列表Array
            //     hint：输入框提示信息
            //     disabled： 是否不可用
            //     initValue：初始值
            //     initDateAdd：初始日期递推，如-7，默认值为当前时间前7日
            //     staticDateInit: 初始日期，只用于用户没有用户习惯之前的值
            //     valueMap： 用于条件值输出时，checkbox类型的值转换，默认[0,1]，如需输出boolean类型，需声明为[false,true]
            // }
        },
        // 用于读写用户习惯，此筛选条件对应的key
        habitKey: {
            type: String
        },
        // 不可修改的强制条件，会集成在on-query-submit事件的参数输出
        // （如包含在queryFields中，则显示为不可用状态，否则不显示）
        hardParms: {
            type: Object,
            default: function () {
                return {}
            }
        },
        // 绑定外部数据源，当外部数据发生改变，相应筛选条件的值也会同步
        bindingParms: {
            type: Object
        },
        // showScan: {
        //     type: Boolean,
        //     default:false
        // },
        // // 是否自动刷新
        // autoRefresh: {
        //     type: Boolean,
        //     default: true
        // },
        // 获取单据列表的接口的接口
        apiName: {
            type: String,
            required: true
        },
        // 深色模式下，使用浅色样式
        ifDarkModel: {
            type: Boolean,
            default: false
        },
    },
    computed: {
        isDropdownDisable(items) {
            return function(items) {
                // console.log(' items :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(items));
                if (items.children.length > 0 && items.children[0].selectOptions.hasOwnProperty('options')) {
                    return !items.children[0].selectOptions.options.length
                }
                return false
            }
        },
        // isDropdownCls(items) {
        //     return function(items) {
        //         console.log('isDropdownCls  items.value:>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(items));
        //         if (items.children.length > 0 && items.children[0].selectOptions.hasOwnProperty('options') && !items.children[0].selectOptions.options.length) {
        //             return ''
        //         } else if (items.children.length > 0 && items.value != undefined){
        //             let titleList = $lj.getUserFilterTitle(this.apiName);
        //             console.log(' this.titleList :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(titleList));
        //             if (items.children[0].initValue != items.value && titleList[items.property]) {
        //                 return 'selected'
        //             }
        //         } else {
        //             return ''
        //         }
        //     }
        // }
    },
    created() {
        this.initQueryField();
    },
    methods: {
        /**事件：单击清除属性——快捷重置 */
        handleClearSingleProp() {

        },
        formatter(type, val) {
            if (type === 'year') {
                return `${val}年`;
            } else if (type === 'month') {
                return `${val}月`;
            }
            return val;
        },
        handleConfirmDTPicker(arg, index) {
            console.log(' index :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(index));
            let date = new Date(arg[0])
            let year = date.getFullYear().toString();
            let month = date.getMonth() + 1;
            if (month < 10) {
                month = "0" + month;
            }
            console.log(' year :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(year));
            console.log(' month :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(month));
            let yearMonth = year + month;
            this.showPopover = false;
            // arg: [items, title, value]
            this.$set(this.queryFieldsForWidget[index], 'title', yearMonth);
            this.$set(this.queryFieldsForWidget[index], 'value', Number(yearMonth));
            this.currentQueryField[this.queryFieldsForWidget[index].property] = Number(yearMonth);
            this.currentQueryTitle[this.queryFieldsForWidget[index].property] = yearMonth;
            this.$emit('confirm', this.currentQueryField, this.currentQueryTitle);
        },
        handleClickDateTime(item, idx) {
            this.dateTimePickerIdx = idx
            this.showPopover = true;
        },
        fnhide(bool) {
            console.log(' bool :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(bool));
            this.hide = bool;
        },
        onSelect(action) {
            console.log(' action :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(action));
            // Toast(action.text);
        },
        /**读取历史搜索 */
        initSearched(keywordObj, keywordObjTitle) {
            for (let i = 0; i < this.queryFieldsForWidget.length; i++) {
                let property = this.queryFieldsForWidget[i].property;
                this.$set(this.queryFieldsForWidget[i], 'val', false);
                if (keywordObj[property] !== '' && keywordObj[property] != -1) {
                    this.$set(this.queryFieldsForWidget[i], 'value', keywordObj[property]);
                    this.$set(this.queryFieldsForWidget[i], 'title', keywordObjTitle[property]);
                }
            }
        },
        /**组件重置属性 */
        handleReset(idx) {
            this.fnResetProp(idx);
            let property = this.queryFieldsForWidget[idx].property;
            let objField = {}, objTitle = {};
            objField[property] = this.currentQueryField[property];
            objTitle[property] = this.currentQueryTitle[property];
            this.$emit('confirm', objField, objTitle);
            this.close();
        },
        fnResetProp(idx){
            this.$set(this.queryFieldsForWidget[idx], 'value', this.queryFieldsForWidget[idx].children[0].initValue);
            this.$set(this.queryFieldsForWidget[idx], 'title', '');
            this.$set(this.queryFieldsForWidget[idx], 'val', false);
            this.currentQueryField[this.queryFieldsForWidget[idx].property] = this.queryFieldsForWidget[idx].value
            this.currentQueryTitle[this.queryFieldsForWidget[idx].property] = '';
        },
        /**父组件调用-主动清除状态 */
        fnResetTabs(prop) {
            console.log('fnResetTabs 冲突属性 prop :>> ', prop);
            let index = -1;
            for (let i = 0; i < this.queryFieldsForWidget.length; i++) {
                if (this.queryFieldsForWidget[i].property == prop) {
                    index = i;
                    break;
                }
            }
            if (index > -1) {
                this.fnResetProp(index);
            }
        },
        /**转换数据模型 */
        initQueryField() {
            let groupArr = [];
            this.queryFields.forEach((field) => {
                if (groupArr.indexOf(field.group) > -1) {
                    let idx = groupArr.indexOf(field.group);
                    this.queryFieldsForWidget[idx].children.push(field);
                } else {
                    let obj = {
                        group: field.group || field.title,
                        type: field.type,
                        children: [field],
                        value: field.initValue || '',
                        title: '',
                        property: field.property
                    }
                    groupArr.push(obj.group);
                    this.queryFieldsForWidget.push(obj);
                }
            });
            // this.queryFieldsForWidget
        },
        handleSelTag(item, index) {
            if (!this.queryFieldsForWidget[index].title) {
                this.$set(this.queryFieldsForWidget[index], 'title', item.title);
                this.$set(this.queryFieldsForWidget[index], 'value', item.optionValue);
                this.currentQueryField[this.queryFieldsForWidget[index].property] = item.optionValue;
                this.currentQueryTitle[this.queryFieldsForWidget[index].property] = item.title;
                this.$emit('confirm', this.currentQueryField, this.currentQueryTitle);
            } else {
                this.handleReset(index)
            }
        },
        /**确认事件 */
        handleConfirm(arg, index) { // arg: [items, title, value]
            this.$set(this.queryFieldsForWidget[index], 'val', false);
            this.$set(this.queryFieldsForWidget[index], 'title', arg[1]);
            this.$set(this.queryFieldsForWidget[index], 'value', arg[2]);
            this.currentQueryField[this.queryFieldsForWidget[index].property] = arg[2];
            this.currentQueryTitle[this.queryFieldsForWidget[index].property] = arg[1];
            this.$emit('confirm', this.currentQueryField, this.currentQueryTitle);
            this.close();
        },
        fnSetValue(property, title, value) {
            for (let i = 0; i < this.queryFieldsForWidget.length; i++) {
                if (this.queryFieldsForWidget[i].property == property) {
                    this.$set(this.queryFieldsForWidget[i], 'title', title);
                    this.$set(this.queryFieldsForWidget[i], 'value', value);
                    break;
                }
            }
            this.currentQueryField[property] = value;
            this.currentQueryTitle[property] = title;
            // this.$emit('confirm', this.currentQueryField, this.currentQueryTitle);
            this.close();
        },
        /**关门下拉菜单 */
        close() {
            for (let i = 0; i < this.queryFieldsForWidget.length; i++) {
                // this.$refs[`dropDownItem${i}`][0].toggle(false);
                this.queryFieldsForWidget[i].val = false;
            }
        },
        /**点击右插槽 */
        handleClickRight() {
            this.$emit('click-right-btn');
            this.close();
        }
    },
    // watch: {
    //     queryFields: {
    //         handler(val) {
    //             console.log('watch queryFields val :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(val));
    //         },
    //         deep: true
    //     }
    // },
    filters: {
        widgetNameFilter(type) {
            let component = '';
            switch (type) {
                case 'radio1': // 单选，排版：单行
                case 'radio2': // 单选，排版：一行两个
                case 'radio3': // 单选，排版：一行三个
                case 'radioFree': // 单选，排版：自由
                    component = WidgetDropDownRadio;
                    break;
                case 'cascader': // 层级选择
                    component = WidgetDropDownCascader;
                    break;
                case 'checkbox': // 多选
                    
                    break;
                case 'date':  // 日期
                    
                    break;
                case 'switch': // 开关
                    
                    break;
                default: // 默认：input

                    break;
            }
            return component
        },
        ymDateFilter(data) {
            if (data == -1) return "月份" 
            return data.toString().substring(0,4) + "年" + data.toString().substring(4,6) + "月"
        }
    }
};
</script>

<style lang="less">
    .tagfiltrate-wrapper {
        position: relative;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 100%;
        height: 36px;
        // padding: 0 16px;
        // z-index: 1;

        .tagfiltrate-tag {
            padding-left: 10px;
            padding-right: 10px;
            // background-color: @light-fill-tertiary;
            background-color: transparent;
            color: @light-label-primary;
            border: 1px solid transparent;
            
            // flex: 1;
            // min-width: 40px;
            // width: max-content;
            // display: flex;
            white-space: nowrap;

            .iconfont {
                font-size: 16px;
            }
            .tagfiltrate-tag__text {
                max-width: 80px;
            }
            &.selected {
                // border: 1px solid @musePrimary;
                color: @musePrimary;
                background: @light-fill-quarternary;
                // color: @light-label-primary;
            }
            .tag-badge {
                margin-left: 2px;
                border-color: transparent;
            }
        }
        &.dark-model .tagfiltrate-tag {
            color: @light-barkground-elevated-secondary;
            background-color: transparent;

            &.selected {
                border: 1px solid transparent;
                color: @light-barkground-elevated-primary;
                // background-color: @colorPassThr;
                background: @light-barkground-elevated-quarternary;
            }
        }
        .tagfiltrate-item + .tagfiltrate-item {
            margin-left: 6px;
        }

        .van-popover {
            width: -moz-calc(~"100% - 20px");
            width: -webkit-calc(~"100% - 20px");
            width: calc(~"100% - 20px");
            left: 10px!important;
            right: 10px!important;
            .van-popover__action {
                width: 100%;
            }
        }
        .van-popover__arrow {
            display: none;
        }
        // .van-dropdown-menu__bar {
        //     // width: fit-content;
        //     box-shadow: unset;
        //     height: 36px;
        // }
        // .van-dropdown-menu__item {
        //     // width: 100px !important;
        //     flex: 1;
        //     min-width: 100px;
        // }
        .dropdown-part {
            padding-left: 16px;
            flex: 1;
            overflow: auto;
            display: flex;
            position: relative;

            .dropdown-item-main {
                max-height: 30vh;

            }
            .selected {
                color: @musePrimary;
            }
        }
        .right-part {
            flex-shrink: 0;
            position: relative;
            display: flex;
            justify-content:  center;
            align-items: center;
            margin-right: 10px;
            padding-left: 15px;

            .iconfont {
                font-size: 16px;
                padding-left: 2px;
            }
            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                width: 15px;
                background-color: #fff;
                z-index: 1;
            }
            &::after{
                content: '';
                position: absolute;
                bottom: 0;
                top: 0;
                left: 0;
                width: 0;
                height: 16px;
                margin: auto;
                box-shadow: 1px 0px 8px 2px rgba(0, 0, 0, 0.2);
                transition: all 0.2s ease-in-out;
                z-index: 0;
            }
            &.filtering {
                color: @musePrimary;
            }
        }
        &.dark-model .right-part {
            color: @light-barkground-elevated-secondary;

            &::before, &::after {
                content: none;
            }

            &.not-click {
                color: @light-barkground-elevated-quarternary;
            }

        }
    }
    .van-dropdown-item__content {
        box-shadow: 0px 4px 4px 0px rgba(0,0,0,0.04), 0px 0px 6px 0px rgba(0,0,0,0.12);
    }
    .van-overlay {
        background-color: rgba(0, 0, 0, 0.3);
    }
    .tagfiltrate-wrapper.dark-model .lj-imgemp.selected {
        color: @light-barkground-elevated-primary!important;
        // background-color: @colorPassThr;
        background: @light-barkground-elevated-quarternary;
        border-radius: 12px;
    }
</style>
