<template>
    <!-- 封装一个时间组件，根据时间粒度显示不同的时间格式，实现年月日，班次的功能 -->
    <div class="zj-timegran-date">
        <div v-show="timegran === ''">
            <el-date-picker
                class="disabled"
                style="width: 100%;"
                v-model="date"
                type="date"
                placeholder="请先选择时间粒度"
                disabled
            ></el-date-picker>
        </div>
        <div v-show="timegran !== ''">
            <el-date-picker
                :style="{ 'width': timegranObj[timegran] && timegranObj[timegran].extraInfo && timegranObj[timegran].extraInfo.length > 0 ? 'calc(100% - 63px)' : '100%' }"
                v-model="date"
                :type="el_type"
                placeholder=""
                :value-format="timegranObj[timegran] && timegranObj[timegran].format ? timegranObj[timegran].format : 'yyyy-MM-dd'"
                :format="timegranObj[timegran] && timegranObj[timegran].format ? timegranObj[timegran].format : 'yyyy-MM-dd'"
            ></el-date-picker>
            <el-select
                style="width: 60px;float: right;"
                v-show="timegranObj[timegran] && timegranObj[timegran].extraInfo && timegranObj[timegran].extraInfo.length > 0"
                filterable
                v-model="extraInfo"
                placeholder=""
            >
                <el-option
                    v-for="name of timegranObj[timegran] && timegranObj[timegran].extraInfo ? timegranObj[timegran].extraInfo : [] "
                    :key="name"
                    :value="name"
                    :label="name"
                ></el-option>
            </el-select>
        </div>
    </div>
</template>

<script>
import { formatDate } from '@/utils/util.js';
export default {
    name: 'timegranDate',
    // model: {
    //     prop: 'value',
    //     event: 'input'
    // },
    props: {
        value: {
            type: [String, Array],
            default: function () {
                return '';
            }
        },
        timegranId: {
            type: [String, Array],
            default: function () {
                return 'DAY';
            }
        },
        timegranObj: {
            type: Object,
            default: function () {
                return {
                    // 'DAY': {
                    //     name: '日',
                    //     format: 'yyyy-MM-dd',
                    //     extraInfo: []
                    // }
                };
            }
        },
        type: {
            type: String,
            default: function () {
                return '';
            }
        },
        oneFoo: {
            type: Function,
            default: function () {
                return null;
            }
        },
        defaultOffset: {
            type: Number,
            default: function () {
                return 0;
            }
        },
        custom: {
            type: Number,
            default: function () {
                return 0;
            }
        }
    },
    data () {
        return {
            one: true,
            date: '',
            timegran: '',
            extraInfo: '',
            el_type: 'date',
            ii: 0,
            upValue: true
        };
    },
    watch: {
        'value': function (newVal, oldVal) {
            // 传入参数功能可能有问题，不推荐使用
            if (this.upValue) {
                // console.log('clock：\n__old：' + oldVal + '\n__new：' + newVal);
                if (this.value instanceof Array) {
                    if (this.date instanceof Array) {
                        this.date = this.value;
                    } else {
                        this.date = this.value[0] || '';
                        this.extraInfo = this.value[1] || '';
                    }
                } else {
                    this.date = this.value || '';
                }
            }
            this.upValue = true;
        },
        'timegranId':  function (newVal, oldVal) {
            if (newVal instanceof Array) {
                if (newVal.length > 1) {
                    let timegran = '';
                    let size = 0;
                    for (let item of newVal) {
                        if (this.timegranObj[item]) {
                            // 将数组中时间格式最细的一项作为时间显示格式
                            let size_ls = 0;
                            if (/[H]+/.test(this.timegranObj[item].format)) {
                                size_ls = 4;
                            } else if (/[d]+/.test(this.timegranObj[item].format)) {
                                size_ls = 3;
                            } else if (/[M]+/.test(this.timegranObj[item].format)) {
                                size_ls = 2;
                            } else if (/[y]+/.test(this.timegranObj[item].format)) {
                                size_ls = 1;
                            }
                            if (size < size_ls) {
                                size = size_ls;
                                timegran = item;
                            }
                        }
                    }
                    this.timegran = timegran;
                } else if (newVal.length === 1) {
                    this.timegran = newVal[0];
                } else {
                    this.timegran = '';
                }
            } else {
                this.timegran = newVal;
            }
        },
        'timegran': function (newVal, oldVal) {
            if (newVal !== oldVal) {
                // console.log('timegranId：\n__old：' + oldVal + '\n__new：' + newVal);
                if (this.timegran) {
                    if (!this.timegranObj[this.timegran]) {
                        this.getTimeFormatAll();
                    } else if (this.timegranObj[this.timegran].format) {
                        this.setType(this.timegranObj[this.timegran].format);
                    } else {
                        this.date = '';
                    }
                } else {
                    this.date = '';
                }
                this.extraInfo = this.timegranObj[this.timegran] && this.timegranObj[this.timegran].extraInfo && this.timegranObj[this.timegran].extraInfo.length > 0 ? this.timegranObj[this.timegran].extraInfo[0] : '';
                this.setValue();
            }
        },
        'timegranObj': function (newVal, oldVal) {
            if (newVal !== oldVal) {
                // console.log('timegranObj：\n__old：' + oldVal + '\n__new：' + newVal);
                this.date = '';
                this.extraInfo = this.timegranObj[this.timegran] && this.timegranObj[this.timegran].extraInfo && this.timegranObj[this.timegran].extraInfo.length > 0 ? this.timegranObj[this.timegran].extraInfo[0] : '';
                this.setValue();
            }
        },
        'date': function (newVal, oldVal) {
            if (newVal !== oldVal) {
                // console.log('date：\n__old：' + oldVal + '\n__new：' + newVal);
                this.setValue();
            }
        },
        'extraInfo': function (newVal, oldVal) {
            if (newVal !== oldVal) {
                // console.log('extraInfo：\n__old：' + oldVal + '\n__new：' + newVal);
                this.setValue();
            }
        },
        'type': function (newVal, oldVal) {
            // console.log('type：\n__old：' + oldVal + '\n__new：' + newVal);
            this.el_type = newVal;
        }
    },
    mounted () {
        let that = this;
        if (that.type) {
            that.el_type = that.type;
        }
        that.getTimeFormatAll();
    },
    methods: {
        // 获取所有时间粒度对应的时间格式
        getTimeFormatAll () {
            let that = this;
            let url = 'pass/ems/v1/tcmtimedefinitions/?isdefault=1';
            that.axios.get(url)
                .then(function (res) {
                    if (res.code === '0') {
                        for (let item of res.data.list) {
                            let obj = {};
                            let extraInfoArr = [];
                            if (item.extrainfo) {
                                extraInfoArr = item.extrainfo.split(',');
                            }
                            obj = {
                                name: item.defname,
                                format: item.timeformat,
                                extraInfo: extraInfoArr
                            }
                            that.timegranObj[item.timegranid] = that.timegranObj[item.timegranid] || obj;
                        }
                        if (that.timegranId instanceof Array) {
                            if (that.timegranId.length > 1) {
                                let timegran = '';
                                let size = 0;
                                for (let item of that.timegranId) {
                                    if (that.timegranObj[item]) {
                                        // 将数组中时间格式最细的一项作为时间显示格式
                                        let size_ls = 0;
                                        if (/[H]+/.test(that.timegranObj[item].format)) {
                                            size_ls = 4;
                                        } else if (/[d]+/.test(that.timegranObj[item].format)) {
                                            size_ls = 3;
                                        } else if (/[M]+/.test(that.timegranObj[item].format)) {
                                            size_ls = 2;
                                        } else if (/[y]+/.test(that.timegranObj[item].format)) {
                                            size_ls = 1;
                                        }
                                        if (size < size_ls) {
                                            size = size_ls;
                                            timegran = item;
                                        }
                                    }
                                }
                                that.timegran = timegran;
                            } else if (that.timegranId.length === 1) {
                                that.timegran = that.timegranId[0];
                            } else {
                                that.timegran = '';
                            }
                        } else {
                            that.timegran = that.timegranId;
                        }
                        // if (item.timegran) {
                        //     that.setType(that.timegranObj[item.timegran].format);
                        // }
                        if (that.timegranObj[that.timegran] && that.timegranObj[that.timegran].format) {
                            that.setType(that.timegranObj[that.timegran].format);
                        }
                        // that.setValue();
                    } else {
                        that.$message.error(res.message);
                    }
                });
        },
        // // 获取时间粒度对应的时间格式
        // getTimeFormat () {
        //     let that = this;
        //     let timegran = that.timegran;
        //     let url = 'pass/ems/v1/tcmtimedefinitions/?isdefault=1&timegranid=' + timegran;
        //     that.axios.get(url)
        //         .then(function (res) {
        //             if (res.code === '0') {
        //                 let obj = {};
        //                 if (res.data.list[0]) {
        //                     let item = res.data.list[0];
        //                     let extraInfoArr = [];
        //                     if (item.extrainfo) {
        //                         extraInfoArr = item.extrainfo.split(',');
        //                     }
        //                     obj = {
        //                         name: item.defname,
        //                         format: item.timeformat,
        //                         extraInfo: extraInfoArr
        //                     }
        //                     that.timegranObj[timegran] = obj;
        //                     that.setType(obj.format);
        //                 }
        //             } else {
        //                 that.$message.error(res.message);
        //             }
        //         });
        // },
        // 根据时间格式自动改变_type
        setType (timeformat) {
            let that = this;
            let setDate = new Date();
            let endDate = new Date();
            if (!that.type) {
                if (/[H]+/.test(timeformat)) {
                    that.el_type = 'datetime';
                    setDate.setHours((setDate.getHours() + that.defaultOffset));
                } else if (/[d]+/.test(timeformat)) {
                    that.el_type = 'date';
                    setDate.setDate((setDate.getDate() + that.defaultOffset));
                } else if (/[M]+/.test(timeformat)) {
                    that.el_type = 'month';
                    setDate.setMonth((setDate.getMonth() + that.defaultOffset));
                } else if (/[y]+/.test(timeformat)) {
                    that.el_type = 'year';
                    setDate.setFullYear((setDate.getFullYear() + that.defaultOffset));
                }
                that.date = formatDate(setDate, timeformat);
            } else if (that.type === 'daterange' || that.type === 'datetimerange' || that.type === 'monthrange') {
                if (/[H]+/.test(timeformat)) {
                    setDate.setHours((setDate.getHours() + that.defaultOffset));
                } else if (/[d]+/.test(timeformat)) {
                    setDate.setDate((setDate.getDate() + that.defaultOffset));
                } else if (/[M]+/.test(timeformat)) {
                    setDate.setMonth((setDate.getMonth() + that.defaultOffset));
                } else if (/[y]+/.test(timeformat)) {
                    setDate.setFullYear((setDate.getFullYear() + that.defaultOffset));
                }
                // 定制版，月初-月末
                if (that.custom && that.custom === 1) {
                    setDate.setDate(1);
                    // 本月最后一天
                    endDate = new Date(new Date().getFullYear(), new Date().getMonth() + 1, '01');
                    endDate = new Date(endDate - 1);
                    that.date = [formatDate(setDate, timeformat), formatDate(endDate, timeformat)];
                } else {
                    that.date = [formatDate(setDate, timeformat), formatDate(setDate, timeformat)];
                }
            }
            that.extraInfo = that.timegranObj[that.timegran] && that.timegranObj[that.timegran].extraInfo && that.timegranObj[that.timegran].extraInfo.length > 0 ? that.timegranObj[that.timegran].extraInfo[0] : '';
            // console.log(that.date)
        },
        // 返回值到父级
        setValue () {
            if (this.date) {
                if (this.extraInfo) {
                    // this.$emit('input', this.date + ' ' + this.extraInfo);
                    this.$emit('input', [this.date[0], this.date[1], this.extraInfo]);
                    this.runOneFoo();
                } else {
                    this.$emit('input', this.date);
                    this.runOneFoo();
                }
            } else {
                this.$emit('input', '');
            }
            this.upValue = false;
        },
        // 加载完成后执行一次父级的方法
        runOneFoo () {
            if (this.one) {
                this.one = false;
                if (this.oneFoo) {
                    setTimeout(() => {
                        this.oneFoo();
                    }, 200);
                }
            }
        }
    }
}
</script>

<style lang="less">
.zj-timegran-date {
    width: 100%;
    .disabled .el-input__inner::placeholder {
        color: #000;
    }
}
</style>
