<template>
  <div class="height100 bi-filter-contanier" :style="'background:'+backgroundColor">
    <div class="shadeing" v-if="buttonTitle=='收起'" @click="addRemoveDateWinToBody(false)"></div>
    <div class="areaClass" ref="selectarea" v-if="childArea.length>0">
      <template v-if="areaOption&&areaOption.name">
        <div class="titleBox">
          <el-checkbox v-model="areaNow" @change="checkArea">本院</el-checkbox>
        </div>
        <div
          class="area_tag"
          @click="clickArea"
          :class="{area_tag_active:areaOption.isClick}"
        >{{areaOption.name}}</div>
      </template>
      <div class="titleBox">
        <el-checkbox v-model="otherArea" @change="checkChild" :indeterminate="isIndeterminate">院区</el-checkbox>
      </div>
      <div
        class="area_tag"
        @click="clickChildArea(item,index)"
        :class="{area_tag_active:item.isClick}"
        v-for="(item,index) in childArea.slice(0,4)"
        :key="index"
      >{{item.name}}</div>

      <div class="moreButton" @click="clickMore" v-if="childArea&&childArea.length>4">
        {{buttonTitle}}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </div>
      <div
        class="hideBox"
        :style="{'top':winTop,'left':winLeft,'width':winWidth}"
        ref="areaWin"
        v-if="buttonTitle=='收起'"
      >
        <div
          class="area_tag"
          style="margin:2px 5px;"
          @click="clickChildArea(item,index,4)"
          :class="{area_tag_active:item.isClick}"
          v-for="(item,index) in childArea.slice(4)"
          :key="index"
        >{{item.name}}</div>
      </div>
    </div>
    <div class="timeClass" v-if="!noDate">
      <div class="titleBox2">
        <div>时间</div>
      </div>
      <div class="timeBox">
        <div class="timeLine" style="padding:5px 0 5px;">
          <!-- 年 -->
          <div class="time_first">
            <div
              class="time_tag"
              :class="{time_tag_active:item.isClick}"
              @click="clickYear(item,index)"
              v-for="(item,index) in yearList"
              :key="index"
            >{{item.name}}</div>
          </div>
          <!-- 月 -->
          <div class="time_month">
            <!-- <el-checkbox v-model="isAllyear" @change="checkYear" style="padding-right:8px;">全年</el-checkbox> -->
            <div
              class="time_tag padding10"
              :class="{time_tag_active:item.isClick}"
              @click="clickMonth(item,index)"
              v-for="(item,index) in monthList"
              :key="index"
            >{{item.name}}</div>
          </div>
        </div>
        <div class="timeLine">
          <!-- 季度 -->
          <div class="time_first">
            <div
              class="time_tag padding13"
              :class="{time_tag_active:item.isClick}"
              @click="clickQuarter(item,index)"
              v-for="(item,index) in quarter"
              :key="index"
            >{{item.name}}</div>
          </div>
          <!-- 日期 -->
          <div class="time_select">
            <ts-date @done="selectDate" width="250px" ref="tsdate" v-model="realTime"></ts-date>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import targetInfoTab from '../targetInfoTab'
export default {
  name: 'biFilter',
  props: {
    value: {
      type: [Object, String],
      default: () => {
        return {}
      }
    },
    noDate: {
      // 不显示日期
      type: Boolean,
      default: false
    },
    backgroundColor: {
      type: String,
      default: '#F3F8FE'
    }
  },
  data() {
    return {
      isAllyear: false,
      winWidth: '100%',
      winTop: '33px',
      winLeft: '0',
      buttonTitle: '更多',
      areaCode: '',
      nowYear: '',
      nowMonth: '',
      nowQuater: '',
      realTime: '',
      isIndeterminate: false,
      yearList: [
        // {name:'2019年',code:'2019',isClick:false},
        // {name:'2020年',code:'2020',isClick:true},
        // {name:'2021年',code:'2021',isClick:false}
      ],
      monthList: [
        { name: '全年', code: 'all', isClick: false },
        { name: '1月', code: '01', isClick: false },
        { name: '2月', code: '02', isClick: false },
        { name: '3月', code: '03', isClick: false },
        { name: '4月', code: '04', isClick: false },
        { name: '5月', code: '05', isClick: false },
        { name: '6月', code: '06', isClick: false },
        { name: '7月', code: '07', isClick: false },
        { name: '8月', code: '08', isClick: false },
        { name: '9月', code: '09', isClick: false },
        { name: '10月', code: '10', isClick: false },
        { name: '11月', code: '11', isClick: false },
        { name: '12月', code: '12', isClick: false }
      ],
      quarter: [
        { name: '1季度', code: '01', isClick: false },
        { name: '2季度', code: '02', isClick: false },
        { name: '3季度', code: '03', isClick: false },
        { name: '4季度', code: '04', isClick: false }
      ],
      areaOption: {
        // name:'益阳市第三人民医院',
        // code:'01',
        // isClick:true
      },
      childArea: [],
      areaNow: true,
      otherArea: false,
      layObj: {
        title: '指标详情', // 标题
        width: '100%', // 宽
        height: '100%', // 高
        closeBtn: true // 关闭按钮区域，boolean 默认：false
      },
      item: this.isEditable
    }
  },
  created() {
    // this.areaOption = global.areaOption || {}
    // this.childArea = global.childArea || []
      this.areaOption = sessionStorage.getItem("areaOption")? JSON.parse(sessionStorage.getItem("areaOption")): {}
    this.childArea = sessionStorage.getItem("childArea") ? JSON.parse(sessionStorage.getItem("childArea")) : []
    this.areaCode = this.areaOption.code

    // this.getArea2()
  },
  mounted() {
    if (!this.noDate) {
      // 存在日期
      this.initDate()
    } else {
      this.$emit('change', { area: this.areaCode })
    }
  },
  deactivated(val) {
    this.buttonTitle = '更多'
    this.addRemoveDateWinToBody(false)
  },
  methods: {
    getHide() {
      this.addRemoveDateWinToBody(false)
    },
    getArea2() {
      let _this = this
      this.$api({
        url: '/ts-query/api/user/query/table/query',
        method: 'post',
        data: {
          id: '611786aca31d827e6268556c'
        }
      }).then(res => {
        _this.allAreaList = res.rows
        if (_this.allAreaList.length && _this.allAreaList.length > 0) {
          this.initArea(_this.allAreaList)
        }
      })
    },
    getArea() {
      let _this = this
      this.$api({
        url: 'ts-system/dept/deptlist',
        method: 'get',
        data: {
          rows: 15,
          page: 1,
          // sidx: 'deptcode',
          // deptcode:'430903000000',
          pdcode: '430903000000',
          // nd:new Date().getTime(),
          _search: true,
          status: 1
        }
      }).then(res => {
        _this.allAreaList = res.rows
        if (_this.allAreaList.length && _this.allAreaList.length > 0) {
          this.initArea(_this.allAreaList)
        }
      })
    },
    initArea(data) {
      let i = data.findIndex(res => res.HOSP_FLAG == 1)
      this.areaOption = data.splice(i, 1)[0]
      this.areaOption.name = this.areaOption.NAME
      this.areaOption.code = this.areaOption.CODE
      this.areaOption.isClick = true
      data.forEach((res, index) => {
        res.name = res.NAME
        res.code = res.CODE
        res.isClick = false
      })
      this.childArea = data
    },
    clickMore() {
      if (this.buttonTitle == '更多') {
        this.buttonTitle = '收起'
        this.$nextTick(() => {
          // this.addRemoveDateWinToBody(true)
        })
      } else {
        // this.addRemoveDateWinToBody(false)
      }
    },

    addRemoveDateWinToBody(type) {
      // const elm = this.$refs.selectarea.getBoundingClientRect()
      // this.winLeft = elm.left + 'px'
      // this.winTop = elm.top + 33 + 'px'
      // this.winWidth = elm.width + 'px'
      // this.$nextTick(() => {
      //   const body = document.querySelector('body')
        if (type) {
      //     // 显示
      //     let areaWin = this.$refs.areaWin
      //     let pTabName = areaWin.parentNode ? areaWin.parentNode.tagName : ''
      //     if (pTabName != 'body') {
      //       // 未加入，body，选择加入
      //       if (body.append) {
      //         body.append(areaWin)
      //       } else {
      //         body.appendChild(areaWin)
      //       }
      //     }
        } else {
          this.buttonTitle = '更多'
      //     // 隐藏
      //     body.removeChild(body.lastChild)
        }
      // })
    },
    selectDate(e) {
      this.resetOther(this.monthList)
      this.resetOther(this.quarter)
      this.isAllyear = false
      this.nowMonth = ''
      this.nowQuater = ''
      this.changeEmit()
    },
    //默认当前月
    initDate() {
      let nowDate = new Date()
      if (this.realTime) {
        //假如有初始值
        let arr = this.realTime.split(' ~ ')
        nowDate = new Date(arr[0])
      }
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth()
      this.nowYear = year
      this.nowMonth = month
      for (let i = 2; i >= 0; i--) {
        this.yearList.push({
          name: year - i + '年',
          isClick: year == year - i,
          code: year - i
        })
      }
      this.monthList[month].isClick = true
      this.realTime = this.getRangeTime('month', year, month)
    },
    //获取当前选中的时间
    getRangeTime(type, year, num) {
      let realTime = ''
      if (type == 'month') {
        //获取某一个月第一天和最后一天
        this.isAllyear = false
        let nowDate = new Date(year, num, 1)
        let nextMonth = num
        let nextMonthFirstDay = new Date(nowDate.getFullYear(), nextMonth, 1)
        let oneDay = 1000 * 60 * 60 * 24
        let lastTime = new Date(nextMonthFirstDay - oneDay)
        let endMonth = parseInt(lastTime.getMonth() + 1)
        let endDay = lastTime.getDate()
        if (endMonth < 10) {
          endMonth = '0' + endMonth
        }
        if (endDay < 10) {
          endDay = '0' + endDay
        }
        let startTime = year + '-' + (num < 10 ? '0' + num : num) + '-01'
        let endTime = year + '-' + endMonth + '-' + endDay
        realTime = startTime + ' ~ ' + endTime
      } else if (type == 'quarter') {
        //获取某个季度第一天和最后一天
        this.isAllyear = false
        if (num == 1) {
          realTime = year + '-01-01' + ' ~ ' + year + '-03-31'
        } else if (num == 2) {
          realTime = year + '-04-01' + ' ~ ' + year + '-06-30'
        } else if (num == 3) {
          realTime = year + '-07-01' + ' ~ ' + year + '-09-30'
        } else if (num == 4) {
          realTime = year + '-10-01' + ' ~ ' + year + '-12-31'
        }
      } else if (type == 'year') {
        //获取某一年第一天和最后一天
        this.isAllyear = true
        realTime = year + '-01-01' + ' ~ ' + year + '-12-31'
      }
      let dateArr = realTime.split(' ~ ')
      let obj = {
        area: this.areaCode,
        s: dateArr[0],
        e: dateArr[1]
      }
      this.$emit('change', obj)
      return realTime
    },
    checkYear() {
      this.resetOther(this.monthList)
      this.resetOther(this.quarter)
      this.realTime = this.getRangeTime('year', this.nowYear)
    },
    checkArea() {
      this.areaOption.isClick = this.areaNow
      this.areaCode = this.getCode(this.childArea)
    },
    clickArea() {
      this.areaOption.isClick = !this.areaOption.isClick
      this.areaNow = this.areaOption.isClick
      this.areaCode = this.getCode(this.childArea)
    },
    checkChild() {
      this.isIndeterminate = false
      if (this.otherArea) {
        this.resetOther(this.childArea, true)
      } else {
        this.resetOther(this.childArea)
      }
      this.areaCode = this.getCode(this.childArea)
    },
    //分院点击
    clickChildArea(item, index, num) {
      if (item.isClick == false) {
        this.childArea[index + (num || 0)].isClick = true
        this.isIndeterminate = true
      } else {
        this.childArea[index + (num || 0)].isClick = false
      }
      //  获取选取的院区节点
      this.areaCode = this.getCode(this.childArea)
      //是否全选分院
      this.otherArea = this.childArea.every(res => res.isClick)
      let isOne = this.childArea.some(res => res.isClick)
      if (!isOne) {
        this.isIndeterminate = false
      } else {
        this.isIndeterminate = true
      }
      if (this.otherArea) {
        this.isIndeterminate = false
      }
    },
    getCode(data) {
      //本院区
      let mainArea = this.areaOption.isClick ? this.areaOption.code : ''
      let codeArr = []
      let childCode = ''
      if (data && data.length > 0) {
        data.forEach(res => {
          if (res.isClick) {
            codeArr.push(res.code)
          }
        })
      }
      childCode = codeArr.length > 0?childCode = codeArr.join(','):''
      if (mainArea && childCode) {
        return mainArea + ',' + childCode
      } else {
        if (mainArea) {
          return mainArea
        } else if (childCode) {
          return childCode
        } else {
          return ''
        }
      }
    },
    //选择年份
    clickYear(item, index) {
      if (item.isClick == false) {
        this.resetOther(this.yearList)
        this.yearList[index].isClick = true

        this.nowYear = item.code
        let type = this.nowQuater ? 'quarter' : this.nowMonth ? 'month' : 'year'
        let num = this.nowQuater || this.nowMonth
        this.realTime = this.getRangeTime(type, this.nowYear, num)
      }
    },
    resetOther(data, type) {
      if (type) {
        //假如有值
        data.forEach(res => {
          res.isClick = type
        })
      } else {
        data.forEach(res => {
          res.isClick = false
        })
      }
    },
    //选择月份
    clickMonth(item, index) {
      if (item.isClick == false) {
        this.resetOther(this.monthList)
        this.resetOther(this.quarter)
        this.monthList[index].isClick = true
        if (index == 0) {
          this.realTime = this.getRangeTime('year', this.nowYear)
          return
        }
        this.nowMonth = index
        this.nowQuater = ''
        //点击当前月
        this.realTime = this.getRangeTime('month', this.nowYear, index)
      } else {
        //取消当前月
        this.monthList[index].isClick = false
        this.nowMonth = ''
        this.nowQuater = ''
        this.realTime = this.getRangeTime('year', this.nowYear)
      }
    },
    // 选择季度
    clickQuarter(item, index) {
      if (item.isClick == false) {
        this.resetOther(this.quarter)
        this.resetOther(this.monthList)
        this.quarter[index].isClick = true
        this.nowMonth = ''
        this.nowQuater = index + 1
        this.realTime = this.getRangeTime('quarter', this.nowYear, index + 1)
      } else {
        this.nowMonth = ''
        this.nowQuater = ''
        this.realTime = this.getRangeTime('year', this.nowYear)
        this.quarter[index].isClick = false
      }
    },
    changeEmit() {
      if (this.noDate) {
        // 取消日期
        this.$emit('change', { area: this.areaCode })
      } else {
        let dateArr = this.realTime.split(' ~ ')
        let obj = {
          area: this.areaCode,
          s: dateArr[0],
          e: dateArr[1]
        }
        this.$emit('change', obj)
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        //初始值
         this.$refs.tsdate.valueInit =true //初始化为true
          this.realTime = val
      }
    },
    areaCode: {
      handler(n,o) {
        if (o == ''&&!n) { // 首次进入
          return
        }
        this.changeEmit()
      }
    },
    realTime: {
      handler(val) {
        this.$emit('input', val)
      }
    }
  },
  //   deactivated(){
  //     
  //  this.buttonTitle="更多"
  //     this.addRemoveDateWinToBody(false)
  //   },
  beforeDestroy: function() {
    this.buttonTitle = '更多'
    this.addRemoveDateWinToBody(false)
  }
}
</script>
<style lang="less" scoped>
.bi-filter-contanier {
  // border: 1px solid var(--border_color);
  box-sizing: border-box;
  // background: #f3f8fd;
  width: 100%;
  /deep/.el-checkbox__input.is-checked + .el-checkbox__label {
    color: #606266;
  }
  .moreButton {
    height: 24px;
    width: 80px;
    line-height: 22px;
    font-size: 12px;
    border: 1px solid #e7e7e7;
    background: #fff;
    cursor: pointer;
    text-align: center;
    border-radius: 4px;
  }
  /deep/.form__box {
    margin-bottom: 0;
  }
  .time_month {
    padding-left: 12px;
    display: flex;
    align-items: center;
  }
  .time_select {
    padding-left: 15px;
  }
  .time_first {
    width: 275px;
    display: flex;
    justify-content: space-between;
  }
  .hideBox {
    box-sizing: border-box;
    width: 100%;
    min-height: 60px;
    height: auto;
    padding: 2px 10px 10px 80px;
    background: #fff;
    position: absolute;
    transition: all 2s ease;
    z-index: 999;
    position: fixed;
    // animation: sideOut 0.5s ease;
  }
  @keyframes sideOut {
    from {
      opacity: 0.8;
      top: 25px;
    }
    to {
      opacity: 1;
      top: 33px;
    }
  }

  .time_tag {
    cursor: pointer;
    margin: 0 3px;
    background-color: #fff;
    display: inline-block;
    height: 24px;
    padding: 0 20px;
    line-height: 22px;
    font-size: 12px;
    color: var(--base-black);
    border: 1px solid rgb(242, 242, 242);
    border-radius: 4px;
    box-sizing: border-box;
    white-space: nowrap;
  }
  .time_tag:hover {
    color: var(--base-acv);
  }
  .time_tag_active:hover {
    color: #fff;
  }
  .padding13 {
    padding: 0 13px !important;
  }
  .padding10 {
    padding: 0 10px !important;
  }
  .time_tag_active {
    color: #fff;
    border: 1px solid #d9ecff;
    background-color: var(--base-acv);
  }
  .area_tag {
    background-color: #fff;
}
  .titleBox2 {
    width: 45px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    padding: 0 10px 0 15px;
    height: 100%;
    text-align: right;
  }
  .titleBox {
    width: 45px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    height: 100%;
    padding: 0 10px 0 15px;
    text-align: right;
  }
  .timeBox {
    height: 100%;
    flex: 1;
    .timeLine {
      height: auto;
      display: flex;
      align-items: center;
    }
  }
  .timeClass {
    height: 60px;
    display: flex;
    // padding: 0 5px 5px;
    font-size: 12px;
  }
}
</style>
