<template>
  <view class="filter-popup">
    <view class="popup-header">
      <!-- <view class="text">筛选</view> -->
      <text class="wk wk-close icon" @click="handleCloseFilter" />
      <view class="wk-tabs">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          :class="{active: activeTab === tab.value}"
          class="wk-tab-item"
          @click="handleToggleTabs(tab.value)">
          {{ tab.label }}
        </view>
      </view>
    </view>
    <view class="popup-content">
      <view
        v-if="activeTab === 'userOrDept'"
        class="filter-user-dept">
        <view
          v-for="item in filterDataTypeOptions"
          :key="item.value"
          :class="{active: filterObj.dataType === item.value}"
          class="data-range-item"
          @click="handleDataRangeChange(item)">
          <text class="text">
            {{ item.label }}
          </text>
          <text v-if="filterObj.dataType === item.value && !item.value !== 0" class="wk wk-check icon" />
          <text v-if="item.value === 0" class="wk wk-arrow-right icon" />
        </view>
      </view>

      <view
        v-if="activeTab === 'time'"
        class="filter-time">
        <view class="title">
          时间
        </view>
        <view class="time-container">
          <view
            v-for="(item, index) in timeOptions"
            :key="index"
            :class="{ active: filterObj.dateFilter === item.value }"
            class="box-item"
            @click="handleTimeRange(item)">
            {{ item.label }}
          </view>
          <view class="box-item empty" />
        </view>

        <view
          v-if="filterObj.dateFilter === 'custom'"
          class="defined-filter">
          <view
            class="start time-box"
            @click="handleChooseDate('startDate')">
            <image
              :src="$static('images/icon/calendar_gray.png')"
              class="calendar-icon" />
            <text v-if="filterObj.startDate">
              {{ filterObj.startDate }}
            </text>
            <text v-else class="wk-placeholder">
              开始时间
            </text>
          </view>

          <text class="ident">
            --
          </text>

          <view
            :class="{ active: !!filterObj.endDate }"
            class="end time-box"
            @click="handleChooseDate('endDate')">
            <image
              :src="$static('images/icon/calendar_gray.png')"
              class="calendar-icon" />
            <text v-if="filterObj.endDate">
              {{ filterObj.endDate }}
            </text>
            <text v-else class="wk-placeholder">
              结束时间
            </text>
          </view>
        </view>
      </view>

      <view
        class="btn-group">
        <button class="button reset-btn" @click="handleReset">
          <image
            :src="$static('images/icon/delete_besom.png')"
            class="icon" />
          重置
        </button>
        <button class="button" @click="emitFilterData">
          确定
        </button>
      </view>
    </view>

    <uni-popup ref="popup" type="picker" @change="childPopupChange">
      <wk-date-picker
        v-model="timeValue"
        type="date"
        @select="handleSelectTime" />
    </uni-popup>
  </view>
</template>

<script>
  import { timeOptions } from '@/utils/data.js'
  import { deepCopy } from '@/utils/lib.js'
  import moment from 'moment'

  export default {
    name: 'WorkbenchFilter',
    props: {
      filterData: {
        type: Object,
        default: () => {}
      },
      defaultTab: {
        type: String,
        default: 'userOrDept'
      }
    },
    data() {
      return {
        guid: null,
        tabs: [
          { label: '员工与部门', value: 'userOrDept' },
          { label: '时间筛选', value: 'time' },
        ],
        activeTab: 'userOrDept',

        filterDataTypeOptions: [
          { label: '仅本人', value: 1 },
          { label: '本人及下属', value: 2 },
          { label: '仅本部门', value: 3 },
          { label: '本部门及下属部门', value: 4 },
          { label: '自定义', value: 0 }
        ],
        timeOptions: timeOptions,
        timeValue: '',
        dateField: null,

        filterObj: {
          dataType: 2,
          dateFilter: 'month',
          startDate: '',
          endDate: '',
          userList: [],
          deptList: []
        }
      }
    },
    watch: {
      defaultTab: {
        handler() {
          this.activeTab = this.defaultTab
        },
        immediate: true
      },
      filterData: {
        handler(val) {
          const data = deepCopy(val || {})
          this.filterObj = {
            dataType: !this.filterData ? 2 : this.filterData.dataType,
            dateFilter: !this.filterData ? 'month' : this.filterData.dateFilter,
            startDate: !this.filterData ? null : this.filterData.startDate,
            endDate: !this.filterData ? null : this.filterData.endDate,
            userList: !this.filterData ? [] : this.filterData.userList,
            userListObj: [],
            deptList: !this.filterData ? [] : this.filterData.deptList,
            deptListObj: []
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      this.guid = this.$guid()
    },
    methods: {
      /**
       * 切换tab
       * @param {String} tab
       */
      handleToggleTabs(tab) {
        this.activeTab = tab
      },
      childPopupChange(evt) {
        this.$emit('popup-change', evt.show)
      },
      closeChildPopup() {
        this.$refs.popup.close()
      },

      /**
       * 修改数据范围
       * @param {Object} item
       */
      handleDataRangeChange(item) {
        this.filterObj.dataType = item.value
        if (item.value === 0) {
          getApp().globalData.selectedValBridge.userAndDept = {
            guid: this.guid,
            defaultVal: {
              userList: this.filterObj.userListObj,
              deptList: this.filterObj.deptListObj
            }
          }
          uni.$on('selected-user-and-dept', this.selectedUserOrDept)
          this.$Router.navigateTo({
            url: '/pages_common/selectList/userAndDept'
          })
        } else {
          this.filterObj.userList = []
          this.filterObj.userListObj = []
          this.filterObj.deptList = []
          this.filterObj.deptListObj = []
          // this.emitFilterData()
        }
      },
      /**
       * 选择员工部门回调
       * @param {Object} data
       */
      selectedUserOrDept(data) {
        if (data.guid === this.guid) {
          uni.$off('selected-user-and-dept')
          let {deptList = [], userList = []} = data.data
          this.filterObj.deptList = deptList.map((item, index) => {
            return item.deptId
          })
          this.filterObj.userList = userList.map((item, index) => {
            return item.userId
          })
          if (deptList.length === 0 && userList === 0) {
            setTimeout(() => {
              this.$toast('请选择员工或部门')
            }, 200)
          } else {
            this.emitFilterData()
          }
        }
      },

      /**
       * 修改时间区间
       * @param {Object} item
       */
      handleTimeRange(item) {
        if (item.value === 'custom') {
          this.filterObj.startDate = null
          this.filterObj.endDate = null
        }
        this.filterObj.dateFilter = item.value
      },

      /**
       * 去自定义选择时间
       * @param {Object} field
       */
      handleChooseDate(field) {
        this.timeValue = this.filterObj[field]
        this.dateField = field
        this.$refs.popup.open()
      },

      /**
       * 选择时间回调
       * @param {Object} date
       * @param {Object} next
       */
      handleSelectTime(date, next) {
        next()
        this.filterObj[this.dateField] = date
        let start = this.filterObj.startDate || null
        let end = this.filterObj.endDate || null
        if (start && end) {
          if (start > end) {
            this.filterObj[this.dateField] = ''
            this.$toast('开始时间不能大于结束时间')
          }
        }
      },

      /**
       * 重置时间区间
       */
      handleReset() {
        this.filterObj = {
          dataType: 2,
          dateFilter: 'month',
          startDate: null,
          endDate: null,
          userList: [],
          userListObj: [],
          deptList: [],
          deptListObj: []
        }
      },

      /**
       * 派发关闭事件
       */
      handleCloseFilter() {
        this.$emit('close')
      },

      /**
       * 派发筛选条件
       */
      emitFilterData() {
        if (this.filterObj.dataType === 0) {
          if (
            this.$isEmpty(this.filterObj.userList) &&
            this.$isEmpty(this.filterObj.deptList)
          ) {
            this.$toast('请选择员工或部门')
            return
          }
        }

        if (this.filterObj.dateFilter === 'custom') {
          const start = this.filterObj.startDate || null
          const end = this.filterObj.endDate || null
          if (!start || !end) {
            this.$toast('请选择筛选时间段')
            return
          }
        }
        this.$emit('change', this.filterObj)
        this.handleCloseFilter()
      }
    }
  }
</script>

<style scoped lang="scss">
	.wk-tabs {
		.wk-tab-item {
			padding: 15rpx 0;
			// &::after {
			// 	width: 50%;
			// }
			&.active {
				color: $theme-color;
			}
		}
	}

	.filter-popup {
		padding: 10rpx 36rpx 20rpx 36rpx;
    position: relative;
		.popup-header {
			position: relative;
			@include center;
			.text {
				font-size: $wk-font-large;
			}
			.icon {
				position: absolute;
				left: -20rpx;
				top: 50%;
				transform: translateY(-50%);
				color: $gray;
				font-size: $wk-font-medium;
				padding: 20rpx;
			}
		}

		.popup-content {
			width: 100%;
			height: 750rpx;
			margin-top: 20rpx;
			overflow: auto;
			display: flex;
			align-items: flex-start;
			justify-content: flex-start;
			flex-direction: column;
      padding-bottom: 100rpx;
			.filter-user-dept {
				width: 100%;
				.data-range-item {
					color: $dark;
					font-size: $wk-font-base;
					border-bottom: 1rpx solid $border-color;
					padding: 22rpx 0;
					@include left;

					.text {
						flex: 1;
					}
					.icon {
						font-size: $wk-font-medium;
						color: inherit;
						line-height: 1;
					}

					&.active {
						color: $theme-color;
					}
				}
			}

			.filter-time {
				flex: 1;
				width: 100%;
				.title {
					font-size: $wk-font-base;
					font-weight: bold;
					color: $dark;
				}

				.time-container {
					width: 100%;
					display: flex;
					justify-content: space-between;
					flex-wrap: wrap;

					.box-item {
						width: 32%;
						height: 60rpx;
						color: #666;
						font-size: $wk-font-base;
						background-color: #f4f4f4;
						border-radius: 10rpx;
						margin-top: 20rpx;
						@include center;

						&.active {
							color: $theme-color;
							background-color: #E7F0FF;
						}
						&.empty {
							visibility: hidden;
						}
					}
				}

				.defined-filter {
					font-size: $wk-font-base;
					margin-top: 25rpx;
					@include left;

					.time-box {
						flex: 1;
						text-align: center;
						border: 1rpx solid #E1E1E1;
						border-radius: 6rpx;
						padding: 10rpx 15rpx;
						@include left;

						&.active {
							color: #333;
						}

						.calendar-icon {
							width: 38rpx;
							height: 38rpx;
							margin-right: 10rpx;
						}
						.wk-placeholder {
							font-size: inherit;
						}
					}
					.ident {
						color: #CDCDCD;
						padding: 0 30rpx;
					}
				}
			}

			.btn-group {
				width: 100%;
				@include center;
        position: absolute;
        bottom: 0rpx;
        left: 0;
        right: 0;
        padding:0 38rpx 30rpx;
        background: white;
        border-top: 1px solid white;
				.button {
					flex: 1;
					height: 80rpx;
					color: white;
					font-size: $wk-font-base;
					background-color: $theme-color;
					border-radius: 12rpx;
					@include center;
				}

				.reset-btn {
					width: 180rpx;
					flex-shrink: 0;
					flex: unset;
					color: $dark;
					background-color: #F5F5F5;
					margin-right: 30rpx;

					.icon {
						width: 32rpx;
						height: 32rpx;
						vertical-align: baseline;
						margin-right: 10rpx;
					}
				}
			}
		}
	}
</style>
