<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { getOperationSelect, getSelect, getTasks, getTasksId } from '/@/views/reportManage/TaskManage/api';


const props = defineProps({
  showOperationSearch: {
    type: Boolean,
    default: false
  },
  cacheForParent1: Boolean,
  showCompany: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits();
const platformNumberList = ref(localStorage.getItem('platformNumberList') || '');
const platformNameList = ref(localStorage.getItem('platformNameList') || '');
const operationList = ref(localStorage.getItem('operationList') || '');
const usersList = ref(JSON.parse(localStorage.getItem('usersList') || '[]'));
const countryList = ref(JSON.parse(localStorage.getItem('countryList') || '[]'));
const brandNameList = ref(JSON.parse(localStorage.getItem('brandNameList') || '[]'));
const platformList = ref(JSON.parse(localStorage.getItem('platformList') || '[]'));
const departmentList = ref(JSON.parse(localStorage.getItem('departmentList') || '[]'));

const companyList = ref([]);

// const platformNumberOptions = ref([]);
// const platformNameOptions = ref([]);
const usersOptions = ref([]);
const companyOptions = ref([]);

// const operationOptions = ref([]);
const countryOptions = ref([]);
const departmentOptions = ref([]);
const brandNameOptions = ref([]);
const platformOptions = ref([]);

const updateData = ref([]);
const filteredData = ref([]);

function sortByInitial(data) {
  return data.sort((a, b) => a.localeCompare(b));
}

// async function fetchAllTasks() {
//   let page = 1;
//   const limit = 9999;
//   let allData = [];
//   let hasNext = true;
//
//   while (hasNext) {
//     try {
//       const response = await getTasks({ page, limit });
//       const data = response.data;
//       allData = allData.concat(data);
//       hasNext = response.is_next;
//       page += 1;
//     } catch (error) {
//       console.error('Error fetching tasks data:', error);
//       hasNext = false;
//     }
//   }
//
//   // platformNumberOptions.value = [...new Set(allData.map(item => item.platformNumber))];
//   // platformNameOptions.value = [...new Set(allData.map(item => item.platformName))];
//   operationOptions.value = [...new Set(allData.map(item => item.operater))];
//   countryOptions.value = sortCountriesByInitial([...new Set(allData.map(item => item.country))]);
//   brandNameOptions.value = [...new Set(allData.map(item => item.brandName))];
//   platformOptions.value = [...new Set(allData.map(item => item.platform).filter(platform => platform !== null && platform !== undefined && platform !== ''))];
// }
//
async function fetchUsersSelect() {
  try {
    const resp = await getOperationSelect();
    usersOptions.value = resp.data.map((item: any) => {
      return { value: item.id, label: item.name };
    });
  } catch (e) {
    console.error('Failed to fetch operation select:', e);
  }
}

async function fetchSelectData() {
  try {
    const resp = await getSelect();
    countryOptions.value = sortByInitial(resp.data.country)
    departmentOptions.value = resp.data.department
    brandNameOptions.value = resp.data.brandName;
    platformOptions.value = resp.data.platform;
    companyOptions.value = resp.data.company;
  } catch (e) {
    console.error('Failed to fetch select data:', e);
  }
}



async function fetchFilteredData() {
  const filters: any = {};
  const processFilterSingle = (value: any, singleKey: string) => {
    if (value) {
      filters[singleKey] = value;
    }
  };

  const processFilterMultiple = (list: any, singleKey: string, multipleKey: string) => {
    if (list.value.length === 1) {
      filters[singleKey] = list.value[0];
    } else if (list.value.length > 1) {
      filters[multipleKey] = list.value.join(',');
    }
  };

  processFilterSingle(platformNumberList.value, 'platformNumber');
  processFilterSingle(platformNameList.value, 'platformName');
  processFilterSingle(operationList.value, 'operater');
  processFilterMultiple(countryList, 'country', 'countrys');
  processFilterMultiple(brandNameList, 'brandName', 'brandNames');
  processFilterMultiple(platformList, 'platform', 'platforms');
  processFilterMultiple(platformList, 'platform', 'platforms');
  processFilterMultiple(departmentList, 'department', 'department');
  processFilterMultiple(companyList, 'company', 'company');

  if (usersList.value.length > 0) {
    filters.users = usersList.value.join(',');
  }

  filteredData.value = filters;
  try {
    const response = await getTasksId(filters);
    updateData.value = response.data.map(item => item.id).join(',');
  } catch (error) {
    console.error('Error fetching filtered data:', error);
  }
}

async function emitChange() {
  await fetchFilteredData();
  emit('update:filteredData', filteredData);
  emit('update:updateData', updateData);

  // 保存筛选条件到 localStorage
  localStorage.setItem('platformNumberList', platformNumberList.value);
  localStorage.setItem('platformNameList', platformNameList.value);
  localStorage.setItem('operationList', operationList.value);
  localStorage.setItem('usersList', JSON.stringify(usersList.value));
  localStorage.setItem('countryList', JSON.stringify(countryList.value));
  localStorage.setItem('brandNameList', JSON.stringify(brandNameList.value));
  localStorage.setItem('platformList', JSON.stringify(platformList.value));
  localStorage.setItem('departmentList', JSON.stringify(departmentList.value));
}

// 快捷选择美洲区国家
const selectCommonGroup1 = () => {
  countryList.value = ['美国', '加拿大', '墨西哥'];
  emitChange(); // 更新选择后的数据
};

// 快捷选择欧洲+英国国家
const selectCommonGroup2 = () => {
  countryList.value = ['比利时', '德国', '法国', '荷兰', '西班牙', '意大利', '英国', '波兰','葡萄牙'];
  emitChange(); // 更新选择后的数据
};

watch([companyList,countryList, brandNameList, usersList, platformList, departmentList], () => {
  emitChange();
});

onMounted(() => {
  // fetchAllTasks();
  fetchSelectData();
  fetchUsersSelect();
  emitChange();
});

defineExpose({ fetchFilteredData, filteredData, updateData });
</script>

<template>
  <div class="flex gap-2.5 flex-wrap">
    <el-select
      v-if="showCompany"
      v-model="companyList"
      class="flex-item"
      clearable
      collapse-tags
      filterable
      multiple
      placeholder="注册公司"
      style="width: 275px;"
    >
      <el-option v-for="item in companyOptions" :key="item" :label="item" :value="item" />
    </el-select>
    <el-input v-model="platformNumberList" class="flex-item" clearable placeholder="平台编号" style="width: 100px"
              @change="emitChange"></el-input>
    <el-input v-model="platformNameList" class="flex-item" clearable placeholder="平台名称" style="width: 130px"
              @change="emitChange"></el-input>
    <el-select v-model="departmentList" class="flex-item" clearable collapse-tags collapse-tags-tooltip multiple
               placeholder="部门"
               style="width: 145px;">
      <el-option v-for="item in departmentOptions" :key="item" :label="item" :value="item" />
    </el-select>
    <el-input v-model="operationList" class="flex-item" clearable placeholder="运营" style="width: 130px"
              @change="emitChange"></el-input>
    <el-select
        v-model="usersList"
        class="flex-item"
        clearable
        collapse-tags
        filterable
        multiple
        placeholder="填写人"
        style="width: 175px;"
    >
      <el-option
          v-for="item in usersOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
    <el-select v-model="countryList" class="flex-item" clearable collapse-tags collapse-tags-tooltip multiple
               placeholder="国家" style="width: 160px;">
      <el-option v-for="item in countryOptions" :key="item" :label="item" :value="item" />
      <template #footer>
        <el-button size="small" text @click="selectCommonGroup1">美洲区</el-button>
        <el-button size="small" text @click="selectCommonGroup2">欧洲+英国</el-button>
      </template>
    </el-select>
    <el-select v-model="brandNameList" class="flex-item" clearable collapse-tags collapse-tags-tooltip multiple
               placeholder="品牌"
               style="width: 145px;">
      <el-option v-for="item in brandNameOptions" :key="item" :label="item" :value="item" />
    </el-select>
    <el-select v-model="platformList" class="flex-item" clearable collapse-tags collapse-tags-tooltip multiple
               placeholder="平台"
               style="width: 145px;">
      <el-option v-for="item in platformOptions" :key="item" :label="item" :value="item" />
    </el-select>
  </div>
</template>

<style scoped>
.flex-container {
  display: flex;
  /* flex-wrap: wrap; */
  gap: 14.5px; /* 控制间距 */
}

.flex-item {
  /* flex: 1 1 150px; !* 自适应大小并设定最小宽度 *! */
  min-width: 100px;
  /* max-width: 180px; !* 设定最大宽度，确保不会变形 *! */
  /* height: 28px; */
  /* padding-top: 4px; */
}

.el-select {
  /* max-width: 180px; !* 确保下拉框宽度不超过最大宽度 *! */
}
</style>