<template>
  <div>
    <el-form-item label="领取时段" class="is-required">
      <el-radio-group v-model="gtt" @change="changeGtt">
        <el-radio :label="1">不限</el-radio>
        <el-radio :label="-1">指定时段</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="gtt === -1">
      <div class="times">
        <div class="mb15">
          <el-radio-group v-model="getTimeType" @change="timeList = [];addTime()">
            <el-radio v-for="(item, idx) in getTimeTypeList" :key="idx" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </div>
        <div class="inline-block">
          <div v-for="(item, idx) in timeList" :key="idx" class="mb20 limit-item">
            <span class="gray01 mr10 sp">时间{{ idx + 1 }}：</span>
            <!-- 每周时段  每月时段 -->
            <el-select v-if="getTimeType === 3 || getTimeType === 4" class="mr10 w140" clearable v-model="item.date" placeholder="请选择日期">
              <el-option v-for="(v, i) in dateList" :key="i" :label="v.label" :value="v.value"></el-option>
            </el-select>
            <!-- 指定时段 -->
            <template v-if="getTimeType === 5">
              <el-select class="mr10 w140" clearable v-model="item.month" placeholder="请选择日期">
                <el-option v-for="(v, i) in monthList" :key="i" :label="v.label" :value="v.value"></el-option>
              </el-select>
              <el-select class="mr10 w140" clearable v-model="item.day" placeholder="请选择日期">
                <el-option v-for="(v, i) in dateList" :key="i" :label="v.label" :value="v.value"></el-option>
              </el-select>
            </template>
            <!-- {{ item.time1 }} -- {{ item.time2 }} -->
            <!-- <el-time-picker v-model="item.time1" format="HH:mm" :picker-options="pickerOption" class="w140" placeholder="开始时间"></el-time-picker>
            <span class="ml10 mr10 gray02">-</span>
            <el-time-picker v-model="item.time2" format="HH:mm" :picker-options="pickerOption" class="w140" placeholder="结束时间"></el-time-picker> -->
            <el-time-picker class="w350" is-range v-model="item.times" format="HH:mm" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"></el-time-picker>
            <span class="hover-btn" @click="timeList.splice(idx, 1)" v-show="idx !== 0">删除</span>
          </div>
          <el-button @click="addTime" v-if="timeList.length < 10" class="dashed" style="min-width:175px;width:100%" icon="el-icon-plus">添加时段</el-button>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="领取人群" class="is-required">
       <!-- 展架为了让粉丝领取，故不传:regionId="currentAreaId" :resource="3" -->
      <dm-new-people force-show-save :waiting-save.sync="waitingSave" ref="newPeople" v-if="showMember" :disabled="disabled" :re-id="memberSearchId" :reback-flag="rebackFlag" @pass-people-data="receivePeopleData" @reset-condition="memberSearchId = ''" />
    </el-form-item>
    <el-form-item label="领券限制" class="is-required">
      <el-radio-group :disabled="disabled" v-model="getNumType">
        <el-radio :label="1">1 张/人</el-radio>
        <el-radio :label="2">
          每天
          <el-input-number :disabled="getNumType!=2 || disabled" class="mr5 w100" v-model="getNum" controls-position="right" :precision="0" :min="1" :max="10000"></el-input-number>
           张/人
        </el-radio>
      </el-radio-group>
    </el-form-item>
  </div>
</template>

<script>
import { formatDateTimeByType } from '@/utils/index.js';
import { isEmpty } from '@/utils/index';
import { getTimeType } from '@/config/mapping/gic-card';
import { dayList, monthDayList, monthList } from '@/config/mapping/common';
const defaultTime = { time1: '', time2: '', times: [ new Date(2020, 1, 1, 0, 0), new Date(2020, 1, 1, 23, 59) ], date: '', month: '', day: '' };

export default {
  name: 'ShelfLimit',
  inject: [ 'parentDisabled' ],
  data() {
    return {
      shelfConditionId: '', // 已经保存过的数据有 更新需要带
      gtt: 1, // 1不限制 -1限制 不传后端
      getTimeType: 1, // 领取时间类型1不限制 2每日时段 3每周时段 4每月时段 5指定日时段
      getNumType: 1, // 1限领一张2每天限领x张
      getNum: 1,
      timeList: [], // 时段list
      monthList,
      rebackFlag: false,
      memberSearchId: '',
      getTimeTypeList: Object.keys(getTimeType).map(v => { return { label: getTimeType[v].label, value: getTimeType[v].value };}).filter(v => v.value != 1),
      pickerOption: {
        selectableRange: '00:00:00 - 23:59:59'
      },
      showMember: false, // 控制人群筛选器重绘
      waitingSave: true, // 人群筛选器是否在保存中
    };
  },
  mounted() {
    this.addTime();
  },
  methods: {
    clean() {
      this.gtt = 1;
      this.getTimeType = 1;
      this.getNumType = 1;
      this.getNum = 1;
      this.timeList = [];
      this.rebackFlag = false;
      this.memberSearchId = '';
      this.showMember = false;
      this.waitingSave = true;
      this.shelfConditionId = '';
      this.addTime();
    },
    add() {
      this.showMember = true;
    },
    edit(data) {
      const { getTimeType, getNumType, getNum, getTimeJson, memberSearchId, shelfConditionId } = data;
      this.gtt = getTimeType == 1 ? 1 : -1;
      this.getTimeType = getTimeType == 1 ? 2 : getTimeType; // 默认为每日
      this.getNumType = getNumType;
      this.getNum = getNum;
      this.timeList = [];
      this.shelfConditionId = shelfConditionId || '';
      this.showMember = true;
      if(memberSearchId) {
        console.log(memberSearchId);
        this.memberSearchId = memberSearchId;
        this.rebackFlag = true;
      }
      // 领取时间类型1不限制 2每日时段 3每周时段 4每月时段 5每年时段
      if(getTimeType == 1) {
        // 领取时段 不限制
        this.addTime();
      } else {
        this.timeList = getTimeJson.map(v => {
          // date: '', month: '', day: ''
          v = { ...defaultTime, ...v, times: [ v.time1, v.time2 ] };
          if(getTimeType == 5) {
            const _d = v.date.split('-');
            v.month = _d[0];
            v.day = _d[1];
            v.date = '';
          }
          return v;
        });
      }
    },
    addTime() {
      this.timeList.push({ ...defaultTime });
    },
    compareTime(time1, time2) {
      const h1 = new Date(time1).getHours();
      const s1 = new Date(time1).getSeconds();
      const h2 = new Date(time2).getHours();
      const s2 = new Date(time2).getSeconds();;
      if(h1 < h2) {
        return true;
      } else if(h1 == h2) {
        return s1 < s2;
      } else {
        return false;
      }
    },
    changeGtt(val) {
      if(val == 1) {
        this.getTimeType = 1;
      } else {
        this.getTimeType = 2; // 默认为每日
      }
      this.timeList = []; // 清空list
      this.addTime();
    },
    // 人群筛选器
    receivePeopleData(data) {
      this.memberSearchId = data.peopleId;
    },
    // 给父组件使用 - 处理数据
    dealData() {
      // 校验数据
      const { gtt, getTimeType, getNumType, memberSearchId, getNum, shelfConditionId } = this;
      if(!this.memberSearchId) {
        this.$tips({ message: '请保存人群筛选器', type: 'error' });
        return;
      } else if(this.waitingSave) {
        this.$tips({ message: '人群筛选器处于编辑状态，请保存', type: 'error' });
        return;
      }
      if(gtt != 1) {
        // 指定时段 判断timeList
        const flag = this.timeList.filter(v => {
          // 领取时间类型1不限制 2每日时段 3每周时段 4每月时段 5指定日时段
          const { date, month, day } = v; // time1, time2,
          if(this.getTimeType == 2) {
            // return time1 && time2;
            return true;
          }
          if (this.getTimeType == 3 || this.getTimeType == 4) {
            // return time1 && time2 && !isEmpty(date);
            return !isEmpty(date);
          }
          if (this.getTimeType == 5) {
            // return time1 && time2 && !isEmpty(month) && !isEmpty(day);
            return !isEmpty(month) && !isEmpty(day);
          }
        }).length;
        if(!flag) {
          this.$tips({ message: '指定时段不完整', type: 'error' });
          return false;
        }
      }
      // if(gtt != 1) {
      //   let flag2 = true;
      //   for(let i = 0, len= this.timeList.length; i < len; i++) {
      //     // 领取时间类型1不限制 2每日时段 3每周时段 4每月时段 5指定日时段
      //     const { time1, time2 } = this.timeList[i];
      //     if(!this.compareTime(time1, time2)) {
      //       flag2 = false;
      //       break;
      //     }
      //   }
      //   if(!flag2) {
      //     this.$tips({ message: '指定时段设置不正确，开始时间不能大于结束时间', type: 'error' });
      //     return false;
      //   }
      // }
      const _getTimeJson = this.getTimeType == 1 ? [] : this.timeList.map(v => {
        // 领取时间类型1不限制 2每日时段 3每周时段 4每月时段 5指定日时段
        const { times, date, month, day } = v;
        const _time1 = formatDateTimeByType(times[0], 'HH:mm').trim();
        const _time2 = formatDateTimeByType(times[1], 'HH:mm').trim();
        if(this.getTimeType == 2) {
          return { time1: _time1, time2: _time2 };
        }
        if (this.getTimeType == 3 || this.getTimeType == 4) {
          return { time1: _time1, time2: _time2, date };
        }
        if (this.getTimeType == 5) {
          return { time1: _time1, time2: _time2, date: `${month}-${day}` };
        }
      });
      // console.log(_getTimeJson);
      // return;
      let data = {
        getTimeType: gtt == 1 ? 1 : getTimeType,
        getNumType: getNumType,
        memberSearchId: memberSearchId,
        getNum: getNum,
        getTimeJson: _getTimeJson,
      };
      if(shelfConditionId) {
        data.shelfConditionId = shelfConditionId; // 有就传
      }
      // if(data.getNumType !== 1) {
      //   data.getNum = this.getNum;
      // }
      return data;
    }
  },
  computed: {
    disabled() {
      return this.parentDisabled();
    },
    dateList() {
      let arr = [];
      switch (this.getTimeType) {
        case 3:
          arr = dayList;
          break;
        case 4:
          arr = monthDayList;
          break;
        case 5:
          arr = monthDayList;
          break;
      }
      return arr;
    }
  },
};
</script>

<style lang="scss" scoped>
.sp {
  width: 60px;
  display: inline-block;
}
.limit-item {
  position: relative;
  &:hover .hover-btn {
    opacity: 1;
  }
  .hover-btn {
    position: absolute;
    right: -40px;
    top: 0;
    opacity: 0;
    transition: all 0.2s;
  }
}
.times {
  background: #F5F7FA;
  padding: 20px;
  max-width: 935px;
}
</style>