<template>
  <el-card
    v-show="visible"
    v-hasPerm="[`${searchConfig.pageName}:query`]"
    shadow="never"
    class="mb-[10px]"
  >
    <el-form ref="queryFormRef" :model="queryParams" :inline="inline">
      <template v-for="(item, index) in formItems" :key="item.prop">
        <el-form-item
          v-show="isExpand ? true : index < showNumber"
          :label="item.label"
          :prop="item.prop"
        >
          <!-- Label -->
          <template v-if="item.tips" #label>
            <span>
              {{ item.label }}
              <el-tooltip
                placement="bottom"
                effect="light"
                :content="item.tips"
                :raw-content="true"
              >
                <el-icon style="vertical-align: -0.15em" size="16">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <!-- Input 输入框 -->
          <template v-if="item.type === 'input' || item.type === undefined">
            <el-input
              v-model="queryParams[item.prop]"
              v-bind="item.attrs"
              @keyup.enter="handleQuery"
            />
          </template>
          <!-- radio-button radio按钮组 -->
          <template v-if="item.type === 'radio-button'">
            <el-radio-group v-model="queryParams[item.prop]" v-bind="item.attrs">
              <template v-for="option in item.options" :key="option.value">
                <el-radio-button :label="option.label" :value="option.value" />
              </template>
            </el-radio-group>
          </template>
          <!-- InputTag 标签输入框 -->
          <template v-if="item.type === 'input-tag'">
            <div class="flex-center">
              <el-tag
                v-for="tag in inputTagMap[item.prop].data"
                :key="tag"
                class="mr-2"
                :closable="true"
                v-bind="inputTagMap[item.prop].tagAttrs"
                @close="handleCloseTag(item.prop, tag)"
              >
                {{ tag }}
              </el-tag>
              <template v-if="inputTagMap[item.prop].inputVisible">
                <el-input
                  :ref="(el: HTMLElement) => (inputTagMap[item.prop].inputRef = el)"
                  v-model="inputTagMap[item.prop].inputValue"
                  v-bind="inputTagMap[item.prop].inputAttrs"
                  @keyup.enter="handleInputConfirm(item.prop)"
                  @blur="handleInputConfirm(item.prop)"
                />
              </template>
              <template v-else>
                <el-button
                  v-bind="inputTagMap[item.prop].buttonAttrs"
                  @click="handleShowInput(item.prop)"
                >
                  {{ inputTagMap[item.prop].buttonAttrs.btnText }}
                </el-button>
              </template>
            </div>
          </template>
          <!-- Select 选择器 -->
          <template v-else-if="item.type === 'select'">
            <el-select v-model="queryParams[item.prop]" v-bind="item.attrs">
              <template v-for="option in item.options" :key="option.value">
                <el-option
                  :label="option.label || option.name"
                  :value="option.value || option.id"
                />
              </template>
            </el-select>
          </template>
          <!-- TreeSelect 树形选择 -->
          <template v-else-if="item.type === 'tree-select'">
            <el-tree-select v-model="queryParams[item.prop]" v-bind="item.attrs" />
          </template>
          <!-- DatePicker 日期选择器 -->
          <template v-else-if="item.type === 'date-picker'">
            <el-radio-group
              class="mr-5"
              v-if="item.attrs && item.attrs.showFastEdit"
              v-model="timeValue"
              @change="timeChange($event, item.prop)"
            >
              <el-radio-button value="">全部</el-radio-button>
              <el-radio-button value="0">今天</el-radio-button>
              <el-radio-button value="-1">昨天</el-radio-button>
              <el-radio-button value="-7">最近7天</el-radio-button>
              <el-radio-button value="-30">最近30天</el-radio-button>
              <el-radio-button value="week">本周</el-radio-button>
              <el-radio-button value="month">本月</el-radio-button>
              <el-radio-button value="custom">自定义</el-radio-button>
            </el-radio-group>
            <div class="flex" v-if="timeValue === 'custom' || !item.attrs?.showFastEdit">
              <el-date-picker v-model="queryParams[item.prop]" v-bind="item.attrs" />
            </div>
          </template>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
        <el-button icon="refresh" @click="handleReset">重置</el-button>
        <!-- 展开/收起 -->
        <el-link
          v-if="isExpandable && formItems.length > showNumber"
          class="ml-2"
          type="primary"
          :underline="false"
          @click="isExpand = !isExpand"
        >
          <template v-if="isExpand">
            收起
            <el-icon>
              <ArrowUp />
            </el-icon>
          </template>
          <template v-else>
            展开
            <el-icon>
              <ArrowDown />
            </el-icon>
          </template>
        </el-link>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import type { FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import type { IObject, ISearchConfig } from "./types";
import dayjs from "dayjs";

// 定义接收的属性
const props = withDefaults(
  defineProps<{
    searchConfig: ISearchConfig;
    isOpenAutoSearch?: boolean;
  }>(),
  {
    isOpenAutoSearch: true,
  }
);
// 自定义事件
const emit = defineEmits<{
  queryClick: [queryParams: IObject];
  resetClick: [queryParams: IObject];
}>();

const queryFormRef = ref<FormInstance>();
//form表单展示形式
const inline = ref<boolean>(
  props.searchConfig.inline === undefined ? true : !!props.searchConfig.inline
);
// 是否显示
const visible = ref(true);
// 响应式的formItems
const formItems = reactive(props.searchConfig.formItems);
// 是否可展开/收缩
const isExpandable = ref(props.searchConfig.isExpandable ?? true);
// 是否已展开
const isExpand = ref(props.searchConfig.isExpand ?? false);
// 表单项展示数量，若可展开，超出展示数量的表单项隐藏
const showNumber = computed(() => {
  if (isExpandable.value === true) {
    return props.searchConfig.showNumber ?? 3;
  } else {
    return formItems.length;
  }
});
// 搜索表单数据
const queryParams = reactive<IObject>({});
const inputTagMap = reactive<IObject>({});
for (const item of formItems) {
  item.initFn && item.initFn(item);
  if (item.type === "input-tag") {
    inputTagMap[item.prop] = {
      data: Array.isArray(item.initialValue) ? item.initialValue : [],
      inputVisible: false,
      inputValue: "",
      inputRef: null,
      buttonAttrs: {
        size: item.attrs?.size ?? "default",
        btnText: item.attrs?.btnText ?? "+ New Tag",
        style: "color: #b0b2b7",
      },
      inputAttrs: {
        size: item.attrs?.size ?? "default",
        clearable: item.attrs?.clearable ?? false,
        style: "width: 150px",
      },
      tagAttrs: {
        size: item.attrs?.size ?? "default",
      },
    };
    queryParams[item.prop] = computed({
      get() {
        return typeof item.attrs?.join === "string"
          ? inputTagMap[item.prop].data.join(item.attrs.join)
          : inputTagMap[item.prop].data;
      },
      set(value) {
        // resetFields时会被调用
        inputTagMap[item.prop].data =
          typeof item.attrs?.join === "string"
            ? value.split(item.attrs.join).filter((item: any) => item !== "")
            : value;
      },
    });
  } else {
    queryParams[item.prop] = item.initialValue ?? "";
  }
}

// 重置操作
function handleReset() {
  queryFormRef.value?.resetFields();
  timeValue.value = "";
  emit("resetClick", queryParams);
}

// 查询操作
function handleQuery() {
  emit("queryClick", queryParams);
}

// 获取分页数据
function getQueryParams() {
  return queryParams;
}

// 显示/隐藏 SearchForm
function toggleVisible() {
  visible.value = !visible.value;
}

// 关闭标签
function handleCloseTag(prop: string, tag: string) {
  inputTagMap[prop].data.splice(inputTagMap[prop].data.indexOf(tag), 1);
}
// 添加标签
function handleInputConfirm(prop: string) {
  if (inputTagMap[prop].inputValue) {
    inputTagMap[prop].data.push(inputTagMap[prop].inputValue);
  }
  inputTagMap[prop].inputVisible = false;
  inputTagMap[prop].inputValue = "";
}
// 显示标签输入框
function handleShowInput(prop: string) {
  inputTagMap[prop].inputVisible = true;
  nextTick(() => {
    inputTagMap[prop].inputRef.focus();
  });
}

function setQueryValue(key: string, val: any) {
  queryParams[key] = val;
}

//时间筛选
const timeValue = ref("");
// 切换时间
function timeChange(e: any, key: string) {
  const format = ["YYYY-MM-DD 00:00:00", "YYYY-MM-DD 23:59:59"];
  switch (e) {
    case "":
      // 全部
      queryParams[key] = [];
      break;
    case "0":
      // 今天
      queryParams[key] = [dayjs().format(format[0]), dayjs().format(format[1])];
      break;
    case "-1":
      // 昨天
      queryParams[key] = [
        dayjs().add(-1, "d").format(format[0]),
        dayjs().add(-1, "d").format(format[1]),
      ];
      break;
    case "-7":
      // 最近7天
      queryParams[key] = [dayjs().add(-7, "d").format(format[0]), dayjs().format(format[1])];
      break;
    case "-30":
      // 最近7天
      queryParams[key] = [dayjs().add(-30, "d").format(format[0]), dayjs().format(format[1])];
      break;
    case "week":
      // 本周
      queryParams[key] = [
        dayjs().startOf("week").format(format[0]),
        dayjs().endOf("week").format(format[1]),
      ];
      break;
    case "month":
      // 本周
      queryParams[key] = [
        dayjs().startOf("month").format(format[0]),
        dayjs().endOf("month").format(format[1]),
      ];
      break;
    case "custom":
      // 自定义
      queryParams[key] = [];
      break;
    default:
      break;
  }
}

// 判断除input输入框之外的表单项是否有变化
function isChange(newval: any, oldval: any) {
  const watchKeys = props.searchConfig.formItems
    .filter((v) => v.type != "input" && v.type !== undefined)
    .map((v) => v.prop);

  return watchKeys.some((key) => newval[key] != oldval[key]);
}
// 监听搜索条件变化
watch(
  () => {
    return {
      ...queryParams,
    };
  },
  (newval, oldval) => {
    if (props.isOpenAutoSearch && isChange(newval, oldval)) {
      handleQuery();
    }
  }
);

// 暴露的属性和方法
defineExpose({ getQueryParams, toggleVisible, setQueryValue });
</script>

<style lang="scss" scoped></style>
