<template>
  <div :key="'simple-filter-panel-' + windowNo + '-tabIndex-' + tabIndex" style="width: 400;">
    <a-input-search
      id="simple-filter-panel-input" v-model:value="simpleConditionValue"
      :placeholder="$t('lang.simpleFilterPanel.inputCondition')" :disabled="disabled" enter-button style="width: 240px"
      @search="commonSearchOk" @focus="showHistoryQueryCondition = true"
      @input="$emit('update:searchText', $event.target.value)"
    >
      <template #prefix>
        <UnorderedListOutlined :style="{ color: searchText ? 'red' : undefined }" @click="clearSearchCondition" />
      </template>
    </a-input-search>

    <a-button type="link" @click="$emit('showComplexFilterPanel')">
      更多筛选条件
    </a-button>

    <a-dropdown
      v-if="showHistoryQueryCondition && conditions.length > 0" v-model:open="showHistoryQueryCondition"
      v-click-outside="onClickOutside" trigger="click"
    >
      <div style="position: absolute; width: 0; height: 0" />
      <template #overlay>
        <a-menu class="history-menu">
          <template v-for="(item, index) in conditions" :key="'history-query-condition-' + item.id">
            <a-menu-item @click="selectCommonHistoryQueryCondition(item)">
              <div class="history-item">
                <span class="history-text">{{ item.condition }}</span>
                <CloseOutlined class="delete-icon" @click.stop="deleteHistoryQueryById($event, item.id)" />
              </div>
            </a-menu-item>
            <a-menu-divider v-if="index !== conditions.length - 1" />
          </template>
          <a-menu-divider />
          <a-menu-item class="clear-history">
            <a type="link" @click="deleteHistoryQuery()">
              {{ $t('lang.simpleFilterPanel.clearHistoryRecord') }}
            </a>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script>
import Common from '../../common/Common.js';
import { SearchOutlined, UnorderedListOutlined, CloseOutlined } from '@ant-design/icons-vue';
import HistoryQueryResource from '../../api/system/HistoryQueryResource.js';
import vClickOutside from 'click-outside-vue3';
import { Notify, Uuid } from 'pc-component-v3';
export default {
  directives: {
    clickOutside: vClickOutside.directive,
  },
  components: {
    SearchOutlined,
    UnorderedListOutlined,
    CloseOutlined,
  },

  props: {
    /**
     * CURD窗口编号
     */
    windowNo: {
      type: String,
      default: null,
    },
    /**
     * 页签顺序号
     */
    tabIndex: {
      type: Number,
      default: null,
    },
    /**
     * 过滤方案
     */
    filterSchema: {
      type: Object,
      default: null,
    },
    /**
     * 简单过滤方案只读
     */
    disabled: {
      type: Boolean,
      default: false,
    },
    /**
     * 搜索的文本
     */
    searchText: {
      type: String,
      default: '',
    },
  },

  emits: ['simpleSearch', 'showComplexFilterPanel', 'update:searchText'],



  data: function () {
    return {
      simpleConditionValue: '',
      showHistoryQueryCondition: false,
      conditions: [],
      simpleFilterHistoryQueryNumber: 10,     //简单查询显示记录数
    };
  },

  watch: {
    /**
     * 切换窗口(页签Id发生改变)的时候重新加载数据
     */
    showHistoryQueryCondition: {
      handler: function (newValue, oldValue) {
        if (newValue === true) {
          this.getHistoryQueries();
        }
      },
    },
    searchText: {
      handler: function (newValue, oldValue) {
        this.simpleConditionValue = newValue;
      },
    },
  },


  methods: {

    /**
     * 简单查询
     */
    commonSearchOk: function () {
      var _self = this;

      if (this.disabled === true) {
        return;
      }

      if (this.filterSchema == undefined || this.filterSchema.filterSchemaSimpleLines == undefined) {
        Notify.error('错误:未定义过滤方案', '请联系系统管理员定义过滤方案', false);
        return;
      }

      var historyQuery = {
        type: 'SimpleFilter',
        condition: _self.simpleConditionValue,
        queryName: '',
        windowNo: _self.windowNo,
        tabIndex: _self.tabIndex,
      };

      HistoryQueryResource.save(historyQuery).then(successData => {
        _self.getHistoryQueries();
      }, errorData => {
        Common.processException(errorData);
      });

      this.showHistoryQueryCondition = false;

      this.$emit('simpleSearch');
    },


    /**
     * 选择了历史查询条件
     */
    selectCommonHistoryQueryCondition: function (item) {
      this.simpleConditionValue = item.condition;
      this.$emit('update:searchText', item.condition);
      this.showHistoryQueryCondition = false;
      this.commonSearchOk();
    },


    /**
     * 清空搜索条件
     */
    clearSearchCondition: function () {
      this.simpleConditionValue = '';
      this.showHistoryQueryCondition = false;
      this.$emit('update:searchText', '');
      this.$emit('simpleSearch');
    },


    /**
     * 获取查询历史条件
     */
    getHistoryQueries: function () {
      var _self = this;

      _self.conditions = [];

      if (_self.windowNo == null
        || _self.windowNo === ''
        || _self.tabIndex == null
        || _self.tabIndex === '') {
        return;
      }

      HistoryQueryResource.listByCondition('SimpleFilter', _self.simpleFilterHistoryQueryNumber, _self.windowNo, _self.tabIndex).then(successData => {
        _self.conditions = successData;
      }, errorData => {
        Common.processException(errorData);
      });

    },

    /**
     * 删除查询历史条件
     */
    deleteHistoryQuery: function () {
      var _self = this;
      HistoryQueryResource.deleteByType('SimpleFilter', _self.windowNo, _self.tabIndex).then(successData => {
        _self.getHistoryQueries();
        _self.showHistoryQueryCondition = false;
        _self.$emit('update:searchText', '');
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
     * 根据id删除查询历史条件
     */
    deleteHistoryQueryById: function (event, id) {
      event.stopPropagation();
      var _self = this;
      HistoryQueryResource.deleteById('SimpleFilter', id).then(successData => {
        _self.getHistoryQueries();
        _self.showHistoryQueryCondition = false;
      }, errorData => {
        Common.processException(errorData);
      });
    },


    /**
     * 当点击'历史查询条件列表'以外的DOM，隐藏'历史查询条件列表'
     */
    onClickOutside: function (e) {
      // 检查点击的元素是否是输入框本身或其子元素
      const searchInput = document.getElementById('simple-filter-panel-input');
      if (searchInput && (searchInput === e.target || searchInput.contains(e.target))) {
        return;
      }
      this.showHistoryQueryCondition = false;
    },
  },
};

</script>

<style scoped>
/* 下拉菜单容器 */
:deep(.history-menu) {
  min-width: 200px;
  padding: 4px 0;
  border: 1px solid #cccccc;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 菜单项 */
:deep(.ant-dropdown-menu-item) {
  padding: 8px 12px;
  margin: 0;
}

:deep(.ant-dropdown-menu-item:hover) {
  background-color: #f5f5f5;
}

/* 历史记录项布局 */
.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-width: 200px;
}

/* 历史记录文本 */
.history-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
}

/* 删除图标 */
.delete-icon {
  color: #999;
  font-size: 12px;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s;
  cursor: pointer;
}

.delete-icon:hover {
  color: #ff4d4f;
  background-color: rgba(255, 77, 79, 0.1);
}

/* 清除历史按钮 */
.clear-history {
  text-align: center;
}

:deep(.clear-history a) {
  color: #1890ff;
}

:deep(.clear-history a:hover) {
  color: #40a9ff;
}

/* 分隔线 */
:deep(.ant-dropdown-menu-item-divider) {
  margin: 4px 0;
  background-color: #f0f0f0;
}

/* 下拉菜单动画 */
:deep(.ant-dropdown) {
  animation-duration: 0.2s;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  :deep(.history-menu) {
    min-width: 150px;
  }

  :deep(.ant-dropdown-menu-item) {
    padding: 12px;
  }

  .delete-icon {
    padding: 8px;
  }
}
</style>