<template>
    <div class="time-container">
        <!-- 范围选择input -->
        <div class="range-area" :class="{isBorder : isTypes}" v-if="mode === 'timerange'">
            <div class="range" @click="onRangeInput(0)">
                <div class="text" :class="{isSelected : rangeIndex === 0}">{{timeTypeFormatStr(selectedValue[0], timeTypeFormat,valueTimeFormat)}}</div>
            </div>
            <div class="rangeSeparator">{{rangeSeparator}}</div>
            <div class="range" @click="onRangeInput(1)">
                <div class="text" :class="{isSelected : rangeIndex === 1}">{{timeTypeFormatStr(selectedValue[1], timeTypeFormat,valueTimeFormat)}}</div>
            </div>
        </div>
        <!-- 时间picker -->
        <div class="picker-module" :style="{height:`${cItemHeight * rowNumber}px`}">
            <picker-list class="f1" v-for="(l,index) in pickerData" :key="index" :column="l" :boxHeight="boxHeight" :itemHeight="cItemHeight" :defaultIndex="isRange ? selectedIndex[rangeIndex][index] : selectedIndex[index]" :pickerId="index" :rowNumber="getRowNumber" @change="onChange" />
            <div class="mask" :style="maskStyle"></div>
        </div>
        <!-- 取消、确认 -->
        <div class="button-area">
            <!-- <div class="text cancelText" :style="{fontSize:`${confirmTextSize}px`,color:`${cancelTextColor}`,backgroundColor:`${cancelBgColor}`}" @click="onCancel">{{cancelText}}</div> -->
            <!-- <div class="text confirmText" :style="{fontSize:`${cancelTextSize}px`,color:`${confirmTextColor}`,backgroundColor:`${confirmBgColor}`}" @click="onConfirm">{{confirmText}}</div> -->
            <u-button :style="btnStyle" throttle-time="0" shape="circle" @click="onCancel">{{cancelText}}</u-button>
            <u-button :style="btnStyle" throttle-time="0" shape="circle" type="primary" @click="onConfirm">{{confirmText}}</u-button>
        </div>
    </div>
</template>

<script>
import moment from '../common/timePickerContant'
import {
    getWeeksInYear,
    getYearWeek
} from '../common/dateUtils'
import PickerList from './PickerView'
/**
 * 时间范围input时间格式化字符串
 * @type {{month: string, hour: string, year: string, day: string, week: string, quarter: string}}
 */
const valueTimeFormatMap = {
    year: 'YYYY',
    quarter: 'YYYY第Q季度',
    halfyear: 'YYYY年B',
    month: 'YYYY.MM',
    day: 'YYYY.MM.DD',
    hour: 'YYYY.MM.DD HH',
    week: 'YYYY年第W周',
    minute: 'YYYY.MM.DD HH:mm'
};

export default {
    name: 'DateTimePanel',
    data() {
        return {
            rowNumber: 5,
            timeTypeFormat: null,
            isRange: null,
            rangeIndex: 0, //时间范围开始时间0，结束时间1
            pickerData: null, //picker数据
            selectedIndex: null, //已选index数组
            selectedValue: null, //已选值数组
            curValueStr: null, //当前时间
            //定义参考../props.js
            mode: null,
            itemHeight: null,
            unit: null,
            startYear: null,
            endYear: null,
            disabledDate: null,
            lastMonths: null,
            rangeSeparator: null,
            cancelText: null,
            cancelTextSize: null,
            cancelTextColor: null,
            cancelBgColor: null,
            confirmText: null,
            confirmTextSize: null,
            confirmTextColor: null,
            confirmBgColor: null,
            isWeekIso: null,
        }
    },
    inject: ["config"],
    watch: {
        compConfig: {
            immediate: true,
            handler: function (val) {
                const {
                    cancelTextSize,
                    cancelText,
                    cancelTextColor,
                    cancelBgColor,
                    confirmTextSize,
                    confirmBgColor,
                    confirmTextColor,
                    confirmText,
                    rangeSeparator,
                    lastMonths,
                    disabledDate,
                    endYear,
                    startYear,
                    unit,
                    itemHeight,
                    mode,
                    isWeekIso
                } = val
                this.mode = mode
                this.itemHeight = itemHeight
                this.unit = unit
                this.startYear = startYear
                this.endYear = endYear
                this.disabledDate = disabledDate
                this.lastMonths = lastMonths
                this.confirmText = confirmText
                this.confirmTextSize = confirmTextSize
                this.confirmTextColor = confirmTextColor
                this.confirmBgColor = confirmBgColor
                this.cancelTextSize = cancelTextSize
                this.cancelText = cancelText
                this.cancelTextColor = cancelTextColor
                this.cancelBgColor = cancelBgColor
                this.rangeSeparator = rangeSeparator
                this.isWeekIso = isWeekIso
                const {
                    rangeIndex, //时间范围开始时间0，结束时间1
                    pickerData, //picker数据
                    selectedIndex, //已选index数组
                    selectedValue, //已选值数组
                    curValueStr //当前时间
                } = this.init(val)
                this.rangeIndex = rangeIndex
                this.pickerData = pickerData
                this.selectedIndex = selectedIndex
                this.selectedValue = selectedValue
                this.curValueStr = curValueStr
            }
        },
        valueList: {
            immediate: true,
            handler: function (val) {
                const config = {
                        ...this.compConfig,
                        ...{
                            tab: this.typeSelected
                        }
                    }
                const {
                    rangeIndex, //时间范围开始时间0，结束时间1
                    pickerData, //picker数据
                    selectedIndex, //已选index数组
                    selectedValue, //已选值数组
                    curValueStr //当前时间
                } = this.init(config)
                this.rangeIndex = rangeIndex
                this.pickerData = pickerData
                this.selectedIndex = selectedIndex
                this.selectedValue = selectedValue
                this.curValueStr = curValueStr
            }
        },
        typeSelected: {
            immediate: true,
            handler: function (val, old) {
                if (val && old && val !== old) {
                    const config = {
                        ...this.compConfig,
                        ...{
                            tab: val
                        }
                    }
                    const {
                        rangeIndex, //时间范围开始时间0，结束时间1
                        pickerData, //picker数据
                        selectedIndex, //已选index数组
                        selectedValue, //已选值数组
                        curValueStr //当前时间
                    } = this.init(config)
                    this.rangeIndex = rangeIndex
                    this.pickerData = pickerData
                    this.selectedIndex = selectedIndex
                    this.selectedValue = selectedValue
                    this.curValueStr = curValueStr
                }
            }
        }
    },
    props: {
        typeSelected: {
            type: String,
        },
        onPickerConfirm: {
            type: Function,
            default: null //function 点击确定触发，返回(时间),最近12个月返回‘lastMonths’
        },
        onPickerCancel: {
            type: Function,
            default: null //点击取消触发
        },
        valueList:{
            type:[Array,Date],
            default: ()=> []
        }
    },
    computed: {
        isTypes() {
            return this.compConfig.tabList && !!this.compConfig.tabList.length
        },
        cItemHeight() {
            let itemHeight = parseInt(this.itemHeight)
            itemHeight = itemHeight ? itemHeight : DEFTAULT_ITEM_HEIGHT
            if (this.compConfig.theme == 'care' || (uni.$u || {}).theme == 'care') {
                itemHeight = itemHeight / 3 * 4
            }
            return itemHeight
        },
        boxHeight() {
            let itemHeight = parseInt(this.itemHeight)
            itemHeight = itemHeight ? itemHeight : DEFTAULT_ITEM_HEIGHT
            if (this.compConfig.theme == 'care' || (uni.$u || {}).theme == 'care') {
                itemHeight = itemHeight / 3 * 4
            }
            return itemHeight * this.getRowNumber
        },
        getRowNumber() {
            if (this.rowNumber < 3) {
                return 3
            }
            return this.rowNumber % 2 === 0 ? this.rowNumber + 1 : this.rowNumber
        },
        maskStyle() {
            let style = {
                backgroundSize: '100% 88px'
            }
            if (this.getRowNumber === 3) {
                style = {
                    backgroundSize: '100% 44px'
                }
            }
            return style
        },
        btnStyle() {
            let width = 240
            if (this.compConfig.theme == 'care' || (uni.$u || {}).theme == 'care') {
                width = width / 3 * 4
            }
            return {
                width: width + 'rpx'
            }
        },
        timeTypeFormatStr() {
            return function(v, timeTypeFormat, valueTimeFormat) {
                if(v[1] === '上半年' || v[1] === '下半年'){
                    return v.join('')
                }
                return moment(v.join('-'), timeTypeFormat).format(valueTimeFormat)
            }
        },
        getValue(){
            return props => {
                // #ifndef VUE3
                return props.value;
                // #endif
                // #ifdef VUE3
                return props.modelValue;
                // #endif
            }
        },
        compConfig () {
            return this.config();
        }
    },
    // filters: {
    //     timeTypeFormatStr: function (v, timeTypeFormat, valueTimeFormat) {
    //         return moment(v.join('-'), timeTypeFormat).format(valueTimeFormat)
    //     }
    // },
    components: {
        PickerList
    },
    methods: {
        /**
         * 切换时间段区域
         * @param {Object} index
         */
        onRangeInput(index) {
            if (this.rangeIndex === index) {
                return
            }
            this.rangeIndex = index
            const {
                pickerData,
                selectedIndex,
                selectedValue
            } = this._getDateList(this.selectedValue);
            this.pickerData = pickerData
            this.selectedIndex = selectedIndex
            this.selectedValue = selectedValue
        },
        /**
         * state初始化
         * @param props
         * @returns {{rangeIndex: number, curValueStr: (*[]|any), pickerData: Array, selectedValue, selectedIndex: Array}}
         * @private
         */
        init(props) {
            let isWeek = false
            if (props && (!props.tab || !this.getValue(props))) {
                this.timeType = !props.tab ? 'day' : props.tab; //时间类型：year、quarter、month、week、day、hour
                this.isRange = this.timeType && this.timeType.indexOf('range') > -1; //是否为时间范围
                isWeek = this.timeType && this.timeType.indexOf('week') > -1
                this.timeTypeFormat = this._timeFormatInit(this.timeType); //各时间类型时间格式化字符串
                if (isWeek && !this.isWeekIso) {
                    this.valueTimeFormat = 'YYYY年第w周'; //时间范围input格式化字符串 YYYY.MM.DD HH
                } else {
                    this.valueTimeFormat = valueTimeFormatMap[this.timeType]; //时间范围input格式化字符串 YYYY.MM.DD HH
                }
                this.tab = this.timeType;
                this.value = this.getValue(props) ? this.getValue(props) : this.isRange ? [new Date(), new Date()] : new Date();
            } else {
                this.isRange = props.tab && props.tab.indexOf('range') > -1;
                this.timeType = this.isRange ? props.tab.substr(0, props.tab.length - 5) : props.tab;
                isWeek = this.timeType && this.timeType.indexOf('week') > -1
                this.timeTypeFormat = this._timeFormatInit(this.timeType);
                if (isWeek && !this.isWeekIso) {
                    this.valueTimeFormat = 'YYYY年第w周'; //时间范围input格式化字符串 YYYY.MM.DD HH
                } else {
                    this.valueTimeFormat = valueTimeFormatMap[this.timeType]; //时间范围input格式化字符串 YYYY.MM.DD HH
                }
                this.tab = props.tab;
                this.value = this.getValue(props);
            }
            if ((this.timeType !== 'year' || props.tab === 'yearrange') && this.value === 'lastMonths') {
                this.value = this.isRange ? [new Date(), new Date()] : new Date();
            }
            //已选值数组['2020年', '10月', '9日']
            let selectedValueStr = null;
            if (this.isRange) {
                let startValue = this.value && this.value[0] ? moment(this.value[0]) : moment().add(-1, this.timeType + 's');
                let endValue = this.value && this.value[1] ? moment(this.value[1]) : moment();
                selectedValueStr = [startValue.format(this.timeTypeFormat).split('-'), endValue.format(this.timeTypeFormat).split(
                    '-')];
            } else {
                selectedValueStr = this.value === 'lastMonths' ? ['最近12个月'] : this.value ? moment(this.value).format(this.timeTypeFormat)
                    .split('-') : moment().format(this.timeTypeFormat).split('-');
                if (this.timeType === 'week') {
                    selectedValueStr = this.value ? moment(this.value).add(1, 'days').format(this.timeTypeFormat).split('-') : moment()
                        .format(this.timeTypeFormat).split('-');
                }
            }
            //picker列表数据、已选Index[117,9,8]、已选值['2020年', '10月', '9日']
            const {
                pickerData,
                selectedIndex,
                selectedValue
            } = this._getDateList(selectedValueStr);
            const curValueStr = this.isRange ? [JSON.parse(JSON.stringify(selectedValue[0])), JSON.parse(JSON.stringify(
                selectedValue[1]))] : JSON.parse(JSON.stringify(selectedValue));
            return {
                rangeIndex: 0, //时间范围开始时间0，结束时间1
                pickerData, //picker数据
                selectedIndex, //已选index数组
                selectedValue, //已选值数组
                curValueStr //当前时间
            };
        },
        /**
         * 时间格式化字符串设置，根据unit
         * @param type
         * @private
         */
        _timeFormatInit(type) {
            let unit = this.unit;
            switch (type) {
                case 'year':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '');
                case 'quarter':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('Q', unit &&
                        unit[1] ? (unit[1] !== '月' ? unit[1] : '第X季度') : '');
                case 'halfyear':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('B', unit &&
                        unit[1] ? (unit[1] !== '月' ? unit[1] : 'X') : '');
                case 'month':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('M', unit &&
                        unit[1] ? unit[1] : '');
                case 'week':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit(this.isWeekIso ? 'W' : 'w', unit &&
                        unit[1] ? (unit[1] !== '月' ? unit[1] : '第X周') : '');
                case 'day':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('M', unit &&
                        unit[1] ? unit[1] : '') + '-' + this._valueFormatByUnit('D', unit && unit[2] ? unit[2] : '');
                case 'hour':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('M', unit &&
                        unit[1] ? unit[1] : '') + '-' + this._valueFormatByUnit('D', unit && unit[2] ? unit[2] : '') + '-' + this._valueFormatByUnit(
                            'H', unit && unit[3] ? unit[3] : '');
                case 'minute':
                    return this._valueFormatByUnit('YYYY', unit && unit[0] ? unit[0] : '') + '-' + this._valueFormatByUnit('M', unit &&
                        unit[1] ? unit[1] : '') + '-' + this._valueFormatByUnit('D', unit && unit[2] ? unit[2] : '') + '-' + this._valueFormatByUnit(
                            'H', unit && unit[3] ? unit[3] : '') + '-' + this._valueFormatByUnit(
                            'm', unit && unit[4] ? unit[4] : '');
                default:
                    break;
            }
        },
        /**
         * 查询设置开始时间、结束时间已选index和value
         * @param valueList ['2020年','10月'，'10日'] | [['2020年','10月'，'10日'],['2020年','10月'，'11日']]
         * @param index 年0 季度|月1 日2 时3
         * @param list 可选数据
         * @param selectedIndex
         * @param selectedValue
         * @returns {{endValue: null, startValue: *}}
         * @private
         */
        _selectedIndexValueDeal(valueList, index, list, selectedIndex, selectedValue, listAll, rangeIndex) {
            // console.log(list);
            // console.log(valueList);
            // console.log(index);
            //开始时间
            const startValue = (() => {
                if (!this.isRange) {
                    return valueList && valueList[index] && list.indexOf(valueList[index]) !== -1 ? valueList[index] : list[list.length -
                        1];
                } else {
                    if(rangeIndex === 0) {
                        return valueList && valueList[0] && valueList[0][index] && list.indexOf(valueList[0][index]) !== -1 ? valueList[
                            0][index] : list[list.length - 1];
                    } else {
                        return valueList && valueList[0] && valueList[0][index] && listAll.indexOf(valueList[0][index]) !== -1 ? valueList[
                            0][index] : listAll[listAll.length - 1];
                    }
                }
            })();
            //结束时间
            let endValue = null;
            if (this.isRange) {
                if(rangeIndex === 0) {
                    endValue = valueList && valueList[1] && valueList[1][index] && listAll.indexOf(valueList[1][index]) !== -1 ? valueList[1][index] : listAll[listAll.length - 1]
                } else {
                    endValue = valueList && valueList[1] && valueList[1][index] && list.indexOf(valueList[1][index]) !== -1 ? valueList[1][index] : list[list.length - 1]
                }
            }
            // 非时间段选择（时间点）
            if (!this.isRange) {
                selectedValue.push(startValue);
                selectedIndex.push(list.indexOf(startValue));
            } else {
                selectedValue[0].push(startValue);
                selectedIndex[0].push(list.indexOf(startValue));
                selectedValue[1].push(endValue);
                selectedIndex[1].push(list.indexOf(endValue));
            }
            return {
                startValue,
                endValue
            };
        },
        /**
         * 时间携带单位处理
         * @param value 时间值 String|Number
         * @param unit 单位 （年|第X季度|第X周）值替换X
         */
        _valueFormatByUnit(value, unit) {
            if (!unit) {
                return value;
            } else {
                if (unit.indexOf('X') > -1) {
                    return unit.replace(/X/, value);
                } else {
                    return value + '' + unit;
                }
            }
        },
        /**
         * 获取picker时间列表数据  -- 核心逻辑，根据时间初始化应该选择的列表项
         * @param valueList ['2020年', '10月', '9日']
         * @returns {{pickerData: Array, selectedIndex: Array}} pickerData[['1990年','1991年'....],['1月','2月'...]...]
         */
        _getDateList(valueList) {
            let unit = this.unit;
            const currentYear = new Date().getFullYear();
            const timeType = this.timeType || (this.isRange ? this.tab.substr(0, this.tab.length - 5) : this.tab);
            const rangeIndex = !this ? 0 : this.rangeIndex;
            //年单位
            let yearUnit = unit && unit[0] ? unit[0] : '';
            //月、季度、周单位
            let monthUnit = unit && unit[1] ? unit[1] : '';
            //日单位
            let dayUnit = unit && unit[2] ? unit[2] : '';
            //小时单位
            let hourUnit = unit && unit[3] ? unit[3] : '';
            //分单位
            let minuteUnit = unit && unit[4] ? unit[4] : '';
            //时间数据
            let pickerData = [];

            let selectedIndex = this.isRange ? [
                [],
                []
            ] : []; //已选index
            let selectedValue = this.isRange ? [
                [],
                []
            ] : []; //已选value

            if (timeType === 'year' || timeType === 'quarter' || timeType === 'halfyear' || timeType === 'month' || timeType === 'week' || timeType ===
                'day' || timeType === 'hour' || timeType === 'minute') {
                //年数据
                let years = [];
                let yearsAll = [];
                let startYear = this.startYear;
                let endYear = this.endYear;
                for (let i = 0; i < endYear + 1 - startYear; i++) {
                    const yearItem = i + startYear;
                    yearsAll.push(this._valueFormatByUnit(yearItem, yearUnit));
                    //禁用日期验证
                    if (this.disabledDate && this.disabledDate(moment(yearItem, 'YYYY').startOf('year').toDate())) {
                        continue;
                    }
                    years.push(this._valueFormatByUnit(yearItem, yearUnit));
                }
                // if (timeType === 'year' && this.type !== 'yearrange' && this.lastMonths === true) {
                // 	years.push('最近12个月');
                // }
                pickerData.push(years);
                //已选年, 2020年
                const yearValueRange = this._selectedIndexValueDeal(valueList, 0, years, selectedIndex, selectedValue, yearsAll, rangeIndex);
                //开始年
                const yearValue = yearValueRange.startValue;
                //结束年
                const yearEndValue = yearValueRange.endValue;

                if (timeType !== 'year') {
                    //季度
                    if (timeType === 'quarter') {
                        let quarters = [];
                        let quartersAll = [];
                        for (let i = 1; i < 5; i++) {
                            const quarterItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + i;
                            quartersAll.push(this._valueFormatByUnit(i, monthUnit === '月' ? '第X季度' : monthUnit));
                            if (this.disabledDate && this.disabledDate(moment(quarterItem, 'YYYY年-Q').startOf('quarter').toDate())) {
                                continue;
                            }
                            quarters.push(this._valueFormatByUnit(i, monthUnit === '月' ? '第X季度' : monthUnit));
                        }
                        pickerData.push(quarters);
                        //已选季度，4
                        this._selectedIndexValueDeal(valueList, 1, quarters, selectedIndex, selectedValue, quartersAll, rangeIndex);
                    }else if (timeType === 'halfyear') {
                        let quarters = [];
                        let quartersAll = [];
                        const dic = {
                            0:'上半年',
                            1:'下半年',
                        }
                        for (let i = 0; i < 2; i++) {
                            const quarterItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + (i * 6 + 1);
                            quartersAll.push(dic[i]);
                            if (this.disabledDate && this.disabledDate(moment(quarterItem, 'YYYY年-M').startOf('month').toDate())) {
                                continue;
                            }
                            quarters.push(dic[i]);
                        }
                        pickerData.push(quarters);
                        //已选季度，4
                        this._selectedIndexValueDeal(valueList, 1, quarters, selectedIndex, selectedValue, quartersAll, rangeIndex);
                    } else if (timeType === 'week') {
                        const weekCount = getWeeksInYear(moment(rangeIndex === 0 ? yearValue : yearEndValue, 'YYYY年').year(), this.isWeekIso);
                        const currentWeek = getYearWeek(new Date(), this.isWeekIso);
                        let weeks = [];
                        let weeksAll = [];
                        for (let i = 1; i <= 53; i++) {
                            weeksAll.push(this._valueFormatByUnit(i, monthUnit === '月' ? '第X周' : monthUnit));
                        }
                        for (let i = 1; i <= weekCount; i++) {
                            // 默认以周一开始时间，跨年周影响下，周数会向前推移， 否则
                            // const quarterItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + i;
                            // if (this.props.disabledDate && this.props.disabledDate(moment(quarterItem, 'YYYY年-W').subtract(0, 'weeks').startOf('week').toDate())) {
                            //     continue;
                            // }
                            const quarterItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + i;
                            if (this.disabledDate && this.disabledDate(moment(quarterItem, this.isWeekIso ? 'YYYY年-W' : 'YYYY年-w').startOf('week').toDate())) {
                                continue;
                            }
                            // 保证数据加层时间超出判定
                            if (i > currentWeek && parseInt(yearValue) === currentYear) {
                                continue;
                            }
                            weeks.push(this._valueFormatByUnit(i, monthUnit === '月' ? '第X周' : monthUnit));
                        }
                        pickerData.push(weeks);
                        // console.log('周数据处理');
                        //已选周，4
                        this._selectedIndexValueDeal(valueList, 1, weeks, selectedIndex, selectedValue,weeksAll, rangeIndex);
                    } else {
                        //月数据
                        let months = [];
                        let monthsAll = [];
                        for (let i = 1; i < 13; i++) {
                            const monthItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + i;
                            monthsAll.push(this._valueFormatByUnit(i, monthUnit));
                            if (this.disabledDate && this.disabledDate(moment(monthItem, 'YYYY年-M').startOf('month').toDate())) {
                                continue;
                            }
                            months.push(this._valueFormatByUnit(i, monthUnit));
                        }
                        pickerData.push(months);
                        //已选月，10月
                        const monthValueRange = this._selectedIndexValueDeal(valueList, 1, months, selectedIndex, selectedValue, monthsAll, rangeIndex);
                        //开始月
                        const monthValue = monthValueRange.startValue;
                        //结束月
                        const monthEndValue = monthValueRange.endValue;
                        if (timeType === 'day' || timeType === 'hour' || timeType === 'minute') {
                            //日数据
                            let days = [];
                            let daysAll = [];
                            let curYear = rangeIndex === 0 ? yearValue : yearEndValue;
                            let curMonth = rangeIndex === 0 ? monthValue : monthEndValue;
                            let dayCount = this.getDaysInOneMonth(curYear.substr(0, curYear.length - yearUnit.length), curMonth.substr(
                                0, curMonth.length - monthUnit.length));
                            for (let i = 1; i <= 31; i++) {
                                daysAll.push(this._valueFormatByUnit(i, dayUnit));
                            }
                            for (let i = 1; i <= dayCount; i++) {
                                const dayItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + (rangeIndex === 0 ? monthValue :
                                    monthEndValue) + '-' + i;
                                if (this.disabledDate && this.disabledDate(moment(dayItem, 'YYYY年-M月-D').startOf('day').toDate())) {
                                    continue;
                                }
                                days.push(this._valueFormatByUnit(i, dayUnit));
                            }
                            pickerData.push(days);
                            //已选日，9日
                            const dayValueRange = this._selectedIndexValueDeal(valueList, 2, days, selectedIndex, selectedValue, daysAll, rangeIndex);
                            //开始日
                            const dayValue = dayValueRange.startValue;
                            //结束日
                            const dayEndValue = dayValueRange.endValue;
                            if (timeType === 'hour' || timeType === 'minute') {
                                //小时数据
                                let hours = [];
                                let hoursAll = [];
                                for (let i = 0; i < 24; i++) {
                                    const hourItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + (rangeIndex === 0 ? monthValue :
                                        monthEndValue) + '-' + (rangeIndex === 0 ? dayValue : dayEndValue) + '-' + i;
                                    hoursAll.push(this._valueFormatByUnit(i, hourUnit));
                                    if (this.disabledDate && this.disabledDate(moment(hourItem, 'YYYY年-M月-D日-H').startOf('hour').toDate())) {
                                        continue;
                                    }
                                    hours.push(this._valueFormatByUnit(i, hourUnit));
                                }
                                pickerData.push(hours);
                                //已选小时
                                const hourValueRange = this._selectedIndexValueDeal(valueList, 3, hours, selectedIndex, selectedValue, hoursAll, rangeIndex);
                                //开始小时
                                const hourValue = hourValueRange.startValue;
                                //结束小时
                                const hourEndValue = hourValueRange.endValue;
                                if (timeType === 'minute') {
                                    //分钟数据
                                    let minutes = [];
                                    let minutesAll = [];
                                    for (let i = 0; i < 60; i++) {
                                        const minuteItem = (rangeIndex === 0 ? yearValue : yearEndValue) + '-' + (rangeIndex === 0 ? monthValue :
                                            monthEndValue) + '-' + (rangeIndex === 0 ? dayValue : dayEndValue) + '-' + (rangeIndex === 0 ? hourValue : hourEndValue) + '-' + i;
                                        minutesAll.push(this._valueFormatByUnit(i, minuteUnit));
                                        if (this.disabledDate && this.disabledDate(moment(minuteItem, 'YYYY年-M月-D日-H-m').startOf('second').toDate())) {
                                            continue;
                                        }
                                        minutes.push(this._valueFormatByUnit(i, minuteUnit));
                                    }
                                    pickerData.push(minutes);
                                    //已选分钟
                                    this._selectedIndexValueDeal(valueList, 4, minutes, selectedIndex, selectedValue, minutesAll, rangeIndex);
                                }
                            }
                        }
                    }
                }
            }
            // console.log(selectedIndex);
            return {
                pickerData: pickerData,
                selectedIndex: selectedIndex,
                selectedValue: selectedValue
            };
        },
        getDaysInOneMonth(year, month) {
            let d = new Date(year, month, 0);
            return d.getDate();
        },
        /**
         * 点击取消按钮或者遮罩关闭picker，重置picker已选为当前时间
         * @private
         */
        cancelPicker() {
            const {
                pickerData,
                selectedIndex,
                selectedValue
            } = this._getDateList(this.curValueStr);
            this.pickerData = pickerData
            this.selectedIndex = selectedIndex
            this.selectedValue = selectedValue
            // this.setState({
            // 	pickerData,
            // 	selectedIndex,
            // 	selectedValue
            // });
            this.onCancel && this.onCancel();
        },
        subtractOneTime() {
            if (this.isRange) {
                return;
            }
            if (this.selectedIndex && this.selectedIndex.length) {
                let temp = JSON.parse(JSON.stringify(this.selectedIndex));
                let lastIndex = temp.length - 1;
                if (temp[lastIndex] > 0) {
                    temp.splice(lastIndex, 1, temp[lastIndex] - 1);
                }
                this.selectedIndex = temp
            }
        },
        /**
         * 取消按钮
         */
        onCancel() {
            const {
                pickerData,
                selectedIndex,
                selectedValue
            } = this._getDateList(this.curValueStr);
            this.pickerData = pickerData
            this.selectedIndex = selectedIndex
            this.selectedValue = selectedValue
            this.onPickerCancel && this.onPickerCancel();
        },
        /**确认按钮
         * @param {Object} selectedValue
         */
        onConfirm() {
            let selectedValueDate = null;
            if (this.isRange) {
                selectedValueDate = [];
                let startDate = null;
                let endDate = null;
                if(this.typeSelected === 'halfyearrange'){
                    const dic = {
                            '上半年':'1',
                            '下半年':'7',
                        }
                    startDate = moment(`${parseInt(this.selectedValue[0][0])}-${dic[this.selectedValue[0][1]]}`).startOf('month').toDate()
                    endDate = moment(`${parseInt(this.selectedValue[1][0])}-${dic[this.selectedValue[1][1]]}`).endOf('month').toDate()
                }else{
                    startDate = moment(this.selectedValue[0].join('-'), this.timeTypeFormat).startOf(this.timeType).toDate();
                    endDate = moment(this.selectedValue[1].join('-'), this.timeTypeFormat).endOf(this.timeType).toDate();
                }
                //时间范围开始时间大于结束时间
                if (moment(startDate).isAfter(moment(endDate))) {
                    // console.log('开始时间不能大于结束时间')
                    new Error('开始时间不能大于结束时间')
                    uni.showToast({
                        title: '开始时间不能大于结束时间',
                        icon: 'none',
                        mask: true
                    })
                    return;
                }
                selectedValueDate.push(startDate);
                selectedValueDate.push(endDate);
            } else {
                const curValue = this.selectedValue.join('-');
                if(curValue === '最近12个月'){
                    selectedValueDate = 'lastMonths'
                }else if(this.typeSelected === 'halfyear'){
                    const dic = {
                            '上半年':'1',
                            '下半年':'7',
                        }
                    const timeStr = `${parseInt(this.selectedValue[0])}-${dic[this.selectedValue[1]]}`
                    selectedValueDate = moment(timeStr).startOf('month').toDate()
                } else {
                    getWeeksInYear(moment(this.value).year(), this.isWeekIso);
                    selectedValueDate = moment(curValue, this.timeTypeFormat).startOf(this.timeType).toDate();
                }
            }
            this.curValueStr = this.selectedValue
            this.onPickerConfirm && this.onPickerConfirm(selectedValueDate);
        },
        //选项变化
        onChange(toValue, pickerId, selectIndex) {
            if (toValue) {
                //picker列表数据、已选Index[117,9,8]、已选值['2020年', '10月', '9日']
                //重新getDateList实现联动
                let selectedValueCopy = JSON.parse(JSON.stringify(this.selectedValue));
                if (this.tab.indexOf('range') > -1) {
                    selectedValueCopy[this.rangeIndex][pickerId] = toValue;
                } else {
                    selectedValueCopy[pickerId] = toValue;
                }
                const {
                    pickerData,
                    selectedIndex,
                    selectedValue
                } = this._getDateList(selectedValueCopy);
                this.pickerData = pickerData
                this.selectedIndex = selectedIndex
                this.selectedValue = selectedValue
            }
        }
    },
}
</script>

<style lang="scss">
@import "../style/uview.theme.scss";
.f1{
	flex: 1;
}

.time-container {
	bottom: 0;
}

.range-area {
	font-size: 16px;
	height: 64px;
	line-height: 64px;
	background: #fff;
	display: flex;
	align-items: center;
	color: themed("u-tips-color");

	.isSelected {
		color: themed("u-main-color");
		border-bottom: 3px solid themed("u-type-primary");
		font-weight: bold;
	}

	.rangeSeparator {
		font-size: 14px;
	}

	.range {
		flex: 1;
		height: 100%;
		text-align: center;
	}

	.text {
		display: inline-block;
		height: 100%;
		box-sizing: border-box;
	}
}

.isBorder {
	border-top: 1px solid $u-border-color;
}

.button-area {
	height: 64px;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: space-around;

	.text {
		min-width: 120px;
		height: 36px;
		line-height: 36px;
		display: inline-block;
		text-align: center;
		border-radius: 18px;
	}

	.cancelText {
		border: 1px solid $u-border-color;
	}

	.confirmText {
		color: #fff;
		background-color: $u-type-primary;
	}
}

.picker-module {
	background: #fff;
	// background: linear-gradient(180deg, #F5F8FA 0%, #FFFFFF 50%, #FFFFFF 90%, #F5F8FA 100%) 0% 0% no-repeat padding-box;
	display: flex;
	text-align: center;
	position: relative;
	padding: 10px 0;
	font-size: 14px;
	box-sizing: content-box;
	.mask {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 2;
		width: 100%;
		height: 100%;
		background-image: linear-gradient(
				180deg,
				rgba(245, 248, 250, 1),
				rgba(255, 255, 255, 0.4)
			),
			linear-gradient(
				0deg,
				rgba(245, 248, 250, 1),
				rgba(255, 255, 255, 0.4)
			);
		background-repeat: no-repeat;
		background-position: top, bottom;
		backface-visibility: hidden;
		pointer-events: none;
		background-size: 100% 88px;
	}

	.hairline {
		position: absolute;
		top: 50%;
		left: 0;
		z-index: 3;
		width: 100%;
		transform: translateY(-50%);
		pointer-events: none;
		height: 44px;

		&::after {
			position: absolute;
			box-sizing: border-box;
			content: " ";
			pointer-events: none;
			top: -50%;
			right: -50%;
			bottom: -50%;
			left: -50%;
			border: 0 solid #ebedf0;
			-webkit-transform: scale(0.5);
			transform: scale(0.5);
			border-width: 1px 0;
		}
	}
}
</style>
