<template>
  <uni-popup ref="popup" type="center" :mask-click="false">
    <view class="bg-white rounded overflow-hidden" style="width: 690rpx;">
      <view class="px-15 py-12 text-center text-lg font-semibold text-dark border-b">
        全部筛选
      </view>
      <view class="py-15">
        <scroll-view scroll-y="true" style="max-height: 60vh;">
          <view class="px-15">
            <view class="text-base font-semibold text-dark">任务状态</view>
            <view class="flex flex-wrap">
              <view v-for="(i, idx) in tabs" :key="i.value"
                class="mt-10 w-72 py-5 text-sm text-center leading-normal text-dark rounded-sm"
                :class="[form.eventStatus === i.value ? 'bg-primary border-primary text-white' : 'border', idx % 4 === 0 ? '' : 'ml-5']"
                @click="form.eventStatus = i.value">
                {{ i.label }}
              </view>
            </view>
            <view class="pt-10 text-base font-semibold text-dark">任务类型</view>
            <view class="flex flex-wrap">
              <view v-for="(i, idx) in eventTypeList" :key="i.value"
                class="mt-10 w-72 py-5 text-sm text-center leading-normal text-dark truncate rounded-sm"
                :class="[selectedType[i.value] ? 'bg-primary border-primary text-white' : 'border', idx % 4 === 0 ? '' : 'ml-5']"
                @click="changeEvent(i.value)">
                {{ i.label }}
              </view>
            </view>
            <view class="py-10 text-base font-semibold text-dark">所属团队</view>
            <view class="flex items-center justify-between px-10 py-5 border rounded-sm" @click="selectTeam()">
              <view class="mr-10 w-0 flex-grow text-base" :class="teamName ? 'text-dark' : 'text-gray'">
                {{ teamName || '全部' }}
              </view>
              <view class="flex-shrink-0" @click="clearTeam()">
                <uni-icons v-if="teamName" type="closeempty" size="16" color="#999"></uni-icons>
                <uni-icons v-else type="down" size="16" color="#999"></uni-icons>
              </view>
            </view>
            <view class="py-10 text-base font-semibold text-dark">计划日期</view>
            <view class="flex items-center justify-between px-10 py-5 border rounded-sm">
              <view class="mr-10 w-0 flex-grow text-base truncate">
                <uni-datetime-picker v-model="form.dates" type="daterange">
                  <view class="w-full truncate">
                    <text v-if="form.dates.length" class="text-base text-dark">
                      {{ form.dates[0] }} - {{ form.dates[1] }}
                    </text>
                    <text v-else class="text-base text-gray">请选择计划日期</text>
                  </view>
                </uni-datetime-picker>
              </view>
              <view class="flex-shrink-0" @click="clearDates()">
                <uni-icons v-if="form.dates.length" type="closeempty" size="16" color="#999"></uni-icons>
                <uni-icons v-else type="down" size="16" color="#999"></uni-icons>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="flex justify-center items-center px-15 py-12 text-center">
        <view class="mr-10 py-5 flex-grow border text-base text-dark rounded-sm" @click="close()">取消</view>
        <view class="mr-10 py-5 flex-grow border-auto text-base text-primary rounded-sm" @click="reset()">重置</view>
        <view class="py-5 flex-grow bg-primary text-base text-white rounded-sm" @click="confirm()">确定</view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { storeToRefs } from "pinia";
import dayjs from 'dayjs';
import { ToDoEventType } from '@/baseData';
import useTeamStore from "@/store/team.js";

const emits = defineEmits(['close', 'confirm'])
const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const tabs = [
  { label: "全部", value: "all" },
  { label: "待处理", value: "processing" },
  { label: "未开始", value: "notStart" },
  { label: "已完成", value: "treated" },
  { label: "已取消", value: "cancelled" },
  { label: "已过期", value: "expired" },
];
const eventTypeList = [{ label: '全部', value: 'all' }, ...Object.keys(ToDoEventType).map(key => ({ label: ToDoEventType[key], value: key }))];

const popup = ref();
const { teams } = storeToRefs(useTeamStore());
const { getTeams } = useTeamStore();
const form = ref({ eventStatus: 'processing', dates: [], eventType: ['all'], teamId: '' });
const selectedType = computed(() => form.value.eventType.reduce((m, item) => {
  m[item] = true;
  return m
}, {}))

const teamName = computed(() => {
  const t = teams.value.find(i => i.teamId === form.value.teamId);
  return t ? t.name : ''
})

function changeEvent(val) {
  if (val === 'all') {
    form.value.eventType = ['all'];
    return
  }
  if (selectedType.value[val]) {
    let newList = form.value.eventType.filter(i => i !== val);
    newList = newList.length ? newList : ['all'];
    form.value.eventType = newList;
  } else {
    let newList = [...form.value.eventType].filter(i => i !== 'all');
    newList.push(val);
    form.value.eventType = newList;
  }
}

function clearDates() {
  if (form.value.dates.length) {
    form.value.dates = [];
  }
}

function clearTeam() {
  form.value.teamId = '';
}

function close() {
  emits('close')
}

function confirm() {
  const data = {eventStatus: form.value.eventStatus};
  if (form.value.eventType.length && form.value.eventType[0] !== 'all') {
    data.eventType = form.value.eventType;
  }
  if (form.value.teamId) {
    data.executeTeamId = form.value.teamId;
  }
  if (form.value.dates.length) {
    data.startDate = form.value.dates[0];
    data.endDate = form.value.dates[1];
  }
  emits('confirm', data)
  close()
}

function init() {
  const data = props.data || {};
  const tab = tabs.find(i => i.value === data.eventStatus);
  form.value.eventStatus = tab ? tab.value : 'all';
  const eventType = Array.isArray(data.eventType) ? data.eventType : ['all'];
  form.value.eventType = eventType;
  form.value.teamId = data.executeTeamId || '';
  const startDate = data.startDate && dayjs(data.startDate).isValid() ? dayjs(data.startDate).format('YYYY-MM-DD') : '';
  const endDate = data.endDate && dayjs(data.endDate).isValid() ? dayjs(data.endDate).format('YYYY-MM-DD') : '';
  if (startDate && endDate) {
    form.value.dates = [startDate, endDate];
  } else {
    form.value.dates = [];
  }
}

function reset() {
  form.value = { eventStatus: 'processing', dates: [], eventType: ['all'], teamId: '' };
}


function selectTeam() {
  const list = teams.value.map(i => i.name);
  uni.showActionSheet({
    itemList: ['全部', ...list],
    success: res => {
      const index = res.tapIndex - 1;
      form.value.teamId = index === -1 ? '' : teams.value[index].teamId;
    }
  })
}


watch(() => props.visible, async n => {
  if (n) {
    if (teams.value.length === 0) {
      getTeams();
    }
    init()
    popup.value && popup.value.open()
  } else {
    popup.value && popup.value.close()
  }
})
</script>

<style lang="scss" scoped>
.ml-5 {
  margin-left: 10rpx;
}

.w-72 {
  width: 144rpx;
}
</style>