<template>
  <a-dropdown v-model:open="visible" :trigger="['click']">
    <a-button v-if="!isShowClear" style="margin-left: 12px">
      <align-center-outlined />
      高级筛选
    </a-button>
    <a-button v-else style="margin-left: 12px; color: #40a9ff">
      <align-center-outlined />
      高级筛选
    </a-button>
    <template #overlay>
      <a-form
        :model="formState"
        name="basic"
        autocomplete="off"
        style="width: 458px; padding: 20px"
      >
        <a-form-item
          v-if="functionType != 4 && functionType != 6"
          label="审批单发起人:"
          name="startUserId"
          style="margin-bottom: 12px"
        >
          <a-select
            v-model:value="formState.startUserId"
            placeholder="请选择审批人"
            style="width: 418px"
            :filter-option="false"
            :field-names="{ label: 'text', value: 'id' }"
            :not-found-content="fetching ? undefined : null"
            :options="copyUserIds"
            show-search
            @search="fetchUser"
          >
            <template v-if="fetching" #notFoundContent>
              <a-spin size="small" />
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="提交审批时间:">
          <a-date-picker
            v-model:value="formState.processInstanceStartAfter"
            @change="(_, str) => dateChange(str, 'processInstanceStartAfter')"
          />
          至
          <a-date-picker
            v-model:value="formState.processInstanceStartBefore"
            @change="(_, str) => dateChange(str, 'processInstanceStartBefore')"
          />
        </a-form-item>
        <a-form-item v-if="functionType == 2" label="任务开始时间:">
          <a-date-picker
            v-model:value="formState.taskCreateTimeAfter"
            @change="(_, str) => dateChange(str, 'taskCreateTimeAfter')"
          />
          至
          <a-date-picker
            v-model:value="formState.taskCreateTimeBefore"
            @change="(_, str) => dateChange(str, 'taskCreateTimeBefore')"
          />
        </a-form-item>
        <a-form-item v-if="functionType == 3" label="完成审批时间:">
          <a-date-picker
            v-model:value="formState.taskEndTimeAfter"
            @change="(_, str) => dateChange(str, 'taskEndTimeAfter')"
          />
          至
          <a-date-picker
            v-model:value="formState.taskEndTimeBefore"
            @change="(_, str) => dateChange(str, 'taskEndTimeBefore')"
          />
        </a-form-item>
        <a-form-item
          v-if="functionType == 4 || functionType == 6"
          label="完成审批时间:"
        >
          <a-date-picker
            v-model:value="formState.processInstanceEndAfter"
            @change="(_, str) => dateChange(str, 'processInstanceEndAfter')"
          />
          至
          <a-date-picker
            v-model:value="formState.processInstanceEndBefore"
            @change="(_, str) => dateChange(str, 'processInstanceEndBefore')"
          />
        </a-form-item>
        <a-divider />
        <a-row type="flex" align="middle" justify="space-between">
          <a-col>
            <span v-if="!isShowClear" style="color: #c8c8c9; cursor: pointer">清空搜索条件</span>
            <a v-else @click="clearFilter"> 清空搜索条件</a>
          </a-col>
          <a-col>
            <a-button @click="visible = false">取消</a-button>
            <a-button
              type="primary"
              style="margin-left: 12px"
              @click="searchWorkflow"
            >
              确认
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
  </a-dropdown>
</template>

<script setup>
import Common from '../common/Common';
import { ref, defineEmits, defineProps, watch, onMounted } from 'vue';
import UserResource from '../api/base/UserResource.js';
import { AlignCenterOutlined } from '@ant-design/icons-vue';

const emit = defineEmits(['getSearchParams']);
const props = defineProps({
  functionType: {
    type: Number,
    default: 2,
  },
});
const formState = ref({});
const visible = ref(false);
const fetching = ref(false);
const searchParams = ref({});
const isShowClear = ref(false);
const copyUserIds = ref([]);

// 获取日期string格式
const dateChange = (value, key) => {
  if (value) {
    if (
      key === 'processInstanceStartAfter' ||
      key === 'taskCreateTimeAfter' ||
      key === 'taskEndTimeAfter' ||
      key === 'processInstanceEndAfter'
    ) {
      searchParams.value[key] = value + ' 00:00:00';
    } else {
      searchParams.value[key] = value + ' 23:59:59';
    }
  } else {
    searchParams.value[key] = value;
  }
};
// 将搜索参数传过去
const searchWorkflow = () => {
  visible.value = false;
  const params = JSON.parse(
    JSON.stringify({ ...formState.value, ...searchParams.value }),
  );
  emit('getSearchParams', params);
};

onMounted(() => {
  getUsers();
});

const fetchUser = Common.debounce(value => {
  copyUserIds.value = [];
  fetching.value = true;
  getUsers(value);
}, 500);


// 筛选
// const filterOption = (input, option) => {
//   return option.text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
// };

// 清空搜索条件
const clearFilter = () => {
  formState.value = {};
  searchParams.value = {};
  isShowClear.value = false;
};

watch(
  formState,
  newData => {
    const obj = JSON.parse(JSON.stringify(newData));
    isShowClear.value = validValue(obj);
  },
  { deep: true },
);

// 用来判断是否有高级搜索条件
const validValue = obj => {
  for (const [key, value] of Object.entries(obj)) {
    if (value !== undefined && value !== null && value !== '') {
      return true;
    }
  }
  return false;
};

// 查询审批人
const getUsers = value => {
  const params = {
    range: {
      start: 0,
      length: 1000,
    },
    conditional: value,
  };
  UserResource.listInGroupCompanyByCondition(params).then(
    successData => {
      if (successData != null && successData.resultList != null) {
        successData.resultList.forEach(function (user) {
          user.text = user.name + '(' + user.no + ')' + '(';
          if (user.organizations != null && user.organizations.length > 0) {
            let isFirst = true;
            user.organizations.forEach(item => {
              if (isFirst === true) {
                user.text += item.organizationName;
                isFirst = false;
              } else {
                user.text += ',' + item.organizationName;
              }
            });
          }
          user.text += ')';
        });
        copyUserIds.value = successData.resultList;
      } else {
        copyUserIds.value = [];
      }
      fetching.value = false;
    },
    errorData => {
      fetching.value = false;
      Common.processException(errorData);
    },
  );
};
</script>

<style scoped>
:deep(.ant-form-item-label) > label {
  font-weight: 500;
  font-size: 14px !important;
}
.ant-divider-horizontal {
  margin: 12px 0;
}
</style>