<template>
  <div>
    <el-form :model="queryForm" label-width="auto" :inline="true" ref="formRef">
      <div class="select-group">
        <el-form-item label="问题来源：" prop="source">
          <el-select
            v-model="queryForm.source"
            placeholder="全部"
            clearable
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in sourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型：" prop="issueType">
          <!-- <el-select
            v-model="queryForm.issueType"
            placeholder="全部"
            clearable
            :disabled="typeDisable"
          >
            <el-option v-for="item in options" :label="item.name" :value="item.id" />
          </el-select> -->
          <el-cascader
            v-model="issueTypeValue"
            :options="options"
            :props="issueMainTypeProp"
            :show-all-levels="false"
            clearable
            :disabled="typeDisable"
            @change="handleIssueMainTypeChange"
          />
        </el-form-item>
        <el-form-item label="地点：" prop="workspaceId">
          <el-cascader
            v-model="workLocation"
            :options="locationOptions"
            :props="location"
            clearable
            collapse-tags
            :show-all-levels="false"
            @change="handleCascaderChange"
          />
        </el-form-item>
        <el-form-item label="状态：" prop="issueState">
          <el-select v-model="tempState" clearable @change="handleIssueStateChange">
            <el-option
              v-for="item in issueStateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期：">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            unlink-panels
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
            @change="handleDateChange"
          />
        </el-form-item>
      </div>
      <div class="btn-group">
        <el-form-item>
          <el-button class="search-btn" type="primary" @click="handleSearch">查询</el-button>
          <el-button class="reset-btn" @click="handleReset">重置</el-button>
          <el-button class="reset-btn" @click="handleExport" v-if="!isShowTab">导出</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import type { FormInstance } from 'element-plus';
  import { computed, reactive, ref } from 'vue';
  import { sourceOptions, issueStateOptions } from './constant.question';

  interface Props {
    isShowTab: boolean; // true展示数据，false默认数据
    aiOptions: Array<any>;
    manualOptions: Array<any>;
    locationOptions: Array<any>;
  }
  const props = defineProps<Props>();
  const emits = defineEmits(['onSearch', 'onReset', 'onExport']);

  interface QueryModel {
    pageNumber: number;
    pageSize: number;
    source?: number; // 来源
    issueMainType?: number; // 一级类型
    issueType?: number; // 类型
    workspaceId?: number[]; // 地点=工位id
    issueState?: number[]; // 状态
    startTime?: string; // 开始时间（默认）
    endTime?: string; // 结束时间（默认）
  }

  const formRef = ref<FormInstance>();
  const queryForm = reactive<QueryModel>({
    pageNumber: 1,
    pageSize: 10,
  });

  type MainOption = {
    value: number;
    label: string;
    children: {
      value: number;
      label: string;
    }[];
  };

  const options = ref<MainOption[]>([]);
  const typeDisable = ref(true);
  const workLocation = ref([]); // 级联选择器，为二维数组（提取workspaceId）
  const location = { multiple: true }; // 级联选择器（打开多选）
  const tempState = ref(''); // 状态，字符串转number[]
  const dateRange = ref([]); // 时间段，拆分成startTime/endTime
  const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
  ]);
  const issueTypeValue = ref([]); // 问题类型，级联选择器
  const issueMainTypeProp = computed(() => {
    if (props.isShowTab) return { expandTrigger: 'hover' as const, checkStrictly: false };
    else return { expandTrigger: 'hover' as const, checkStrictly: true };
  });
  const workShopIds = ref([]);

  const handleSearch = () => {
    emits('onSearch', queryForm);
  };

  const handleReset = () => {
    workShopIds.value = [];
    issueTypeValue.value = [];
    typeDisable.value = true;
    workLocation.value = [];
    tempState.value = '';
    dateRange.value = [];
    Reflect.deleteProperty(queryForm, 'startTime');
    Reflect.deleteProperty(queryForm, 'endTime');
    Reflect.deleteProperty(queryForm, 'issueMainType');
    formRef.value?.resetFields();
    emits('onReset', queryForm);
  };

  const handleExport = () => {
    emits('onExport', queryForm, workShopIds.value);
  };

  const handleSelectChange = () => {
    if (Number(queryForm.source) === 1) {
      typeDisable.value = false;
      options.value = props.aiOptions;
    } else if (Number(queryForm.source) === 2) {
      typeDisable.value = false;
      options.value = props.manualOptions;
    } else {
      typeDisable.value = true;
      options.value = [];
      queryForm.issueMainType = undefined;
      queryForm.issueType = undefined;
    }
  };

  const handleIssueMainTypeChange = () => {
    if (issueTypeValue.value) {
      queryForm.issueMainType = issueTypeValue.value[0];
      queryForm.issueType = issueTypeValue.value[1];
    } else {
      Reflect.deleteProperty(queryForm, 'issueMainType');
      Reflect.deleteProperty(queryForm, 'issueType');
    }
  };

  const handleCascaderChange = () => {
    const arr = [];
    workShopIds.value = [];
    workLocation.value.forEach((item) => {
      arr.push(item[1]);
      workShopIds.value.push(item[0]);
    });
    queryForm.workspaceId = arr;
    workShopIds.value = [...new Set(workShopIds.value)];
  };

  const handleIssueStateChange = () => {
    if (tempState.value) queryForm.issueState = JSON.parse(tempState.value);
  };

  const handleDateChange = () => {
    if (dateRange.value != null) {
      queryForm.startTime = dateRange.value[0];
      queryForm.endTime = dateRange.value[1];
    } else {
      Reflect.deleteProperty(queryForm, 'startTime');
      Reflect.deleteProperty(queryForm, 'endTime');
    }
  };
</script>

<style scoped lang="scss">
  .el-form {
    display: flex;
    justify-content: space-between;
  }

  :deep(.el-form--inline .el-form-item) {
    margin-right: 0;
  }

  :deep(.el-form-item__label) {
    padding: 0;
  }

  .select-group {
    flex: 1;
  }

  .btn-group {
    .search-btn {
      width: 65px;
      height: 32px;
      background: #1890ff;
      border-radius: 2px;
    }

    .reset-btn {
      width: 65px;
      height: 32px;
      border-radius: 2px;
      border: 1px solid #1890ff;
      color: #1890ff;
    }
  }

  .el-select {
    --el-select-width: 215px;
  }
</style>
