<!-- eslint-disable vue/v-on-event-hyphenation -->
<template>
  <a-form-item style="margin-bottom: 0; margin-top: 0">
    <div
      :class="focusObj.divFocus ? 'ns-input-filter-long-focus' : 'ns-input-filter'"
      ref="nsInputFilter">
      <!-- 整个组件范围 -->
      <div
        :class="
          focusObj.divFocus ? 'ns-input-filter-input-show-focus' : 'ns-input-filter-input-show'
        "
        @click.stop="focus">
        <!-- 组件第二层 -->
        <div style="display: inline-block">
          <!-- 选中后展示 -->
          <ns-input-filter-input-showSpan
            ref="inputShowSpan"
            :filterArrayShowList="filterArrayShow"
            :filterList="filterListOperation"
            :selectedFilterList="selectedFilter"
            :focusObjProp="focusObj"
            :defaultFilterObj="defaultFilter"
            @change="showSpanChage"
            @filterformatconvert="filterformatconvert"
            @searchFilter="searchFilter"
            @processSelected="processSelected"
            @chooseSingleOptions="chooseSingleOptions"
            @chooseMultiOptions="chooseMultiOptions" />
          <!-- 输入框部分 -->
          <div class="input-and-placeholder">
            <div
              class="ns-input-content"
              :style="focusObj.divFocus ? '' : 'display:none'"
              ref="inputAndPlaceholder">
              <div v-if="!chooseItem.isChoose" class="ns-input-content-1">
                <a-input
                  ref="aInputFilter"
                  AutoComplete="off"
                  :autofocus="focusObj.focus"
                  v-model:value="filterValue"
                  @keydown="onKeyUpDelete"
                  @pressEnter="pressEnter"
                  @change="valueChange"
                  @focus="inputFocus">
                  <template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
                    <slot :name="item" v-bind="data || {}"> </slot>
                  </template>
                </a-input>
                <span
                  style="
                    position: absolute;
                    top: -9999px;
                    left: 0px;
                    white-space: pre;
                    font-size: 12px;
                  ">
                  {{ filterValue }}
                </span>
              </div>
              <!-- NsInput形态 -->
              <div v-else-if="chooseItem.componentType == 'NsInput'" class="ns-input-content-2">
                <ns-input-filter-input
                  ref="filterInput"
                  :value="filterValue"
                  :chooseItem="chooseItem"
                  :autofocus="focusObj.focus"
                  @change="nsInputChange"
                  @pressEnter="pressEnter"
                  @chooseIsEmptyLabel="chooseIsEmptyLabel" />
              </div>
              <div
                v-else-if="chooseItem.componentType == 'NsSingleSearch'"
                class="ns-single-search">
                <ns-input-filter-singleSearch
                  ref="filterSingSearch"
                  :value="filterValue"
                  :chooseItem="chooseItem"
                  :autofocus="focusObj.focus"
                  :fileValue="filterArray"
                  @change="nsInputChange"
                  @chooseOptions="chooseSingleOptions"
                  @pressEnter="singlePressEnter" />
              </div>
              <div v-else-if="chooseItem.componentType == 'NsMultiSearch'" class="ns-multi-search">
                <ns-input-filter-multiSearch
                  ref="filterMultiSearch"
                  :value="filterValue"
                  :chooseItem="chooseItem"
                  @change="nsInputChange"
                  @canel="canel"
                  @chooseOptions="chooseMultiOptions" />
              </div>
            </div>
            <div class="placeholder" :style="focusObj.divFocus ? '' : 'margin-left:6px'">
              <!-- ，多个过滤标签用回车键分割 多个关键字用竖线"｜"分割 -->
              <span>请输入关键字</span>
            </div>
            <!-- 下拉过滤标签 -->
            <div v-if="focusObj.filterLabelFocus" class="ns-input-filter-content">
              <div class="ns-input-filter-list">
                <ul
                  v-for="(item, index) in realTimeFilterList"
                  :key="index"
                  class="filter-list-text">
                  <li v-if="index == 0" class="is-disabled"> 选择资源属性进行过滤</li>
                  <li @click="chooseLabel(item, index)">
                    {{ item.label }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <!-- 全部删除 搜索图标 -->
          <span class="all-close-span all-close-icon" v-if="focusObj.divFocus" @click.stop="delAll">
          </span>
          <span class="search-icon" @click.stop="searchIcon"> </span>
        </div>
      </div>
    </div>
  </a-form-item>
</template>
<script lang="ts">
  import { defineComponent, computed, ref, nextTick, watch, onMounted } from 'vue';
  import { onClickOutside } from '@vueuse/core';
  import { NsMessage } from '/nerv-lib/component/message';
  import { http } from '/nerv-lib/util';
  import NsInputFilterInput from './input-filter-input.vue';
  import NsInputFilterSingleSearch from './input-filter-singleSearch.vue';
  import NsInputFilterMultiSearch from './input-filter-multiSearch.vue';
  import NsInputFilterInputShowSpan from './input-filter-input-showSpan.vue';
  import { onBeforeRouteLeave, useRouter } from 'vue-router';
  import * as utils from './input-filter-util';

  export default defineComponent({
    name: 'NsInputFilter',
    components: {
      'ns-input-filter-input': NsInputFilterInput,
      'ns-input-filter-singleSearch': NsInputFilterSingleSearch,
      'ns-input-filter-multiSearch': NsInputFilterMultiSearch,
      'ns-input-filter-input-showSpan': NsInputFilterInputShowSpan,
    },
    props: {
      filterList: {
        type: Array,
        default: () => [],
      },
      placeholder: String,
      isNeedHttpGet: Boolean,
      type: String,
      terraceType: String,
      api: String,
      defaultFilterList: Boolean,
    },
    emits: ['change', 'search'],
    setup(props, ctx) {
      // console.log(props);
      const thisRouter = ref(null);
      const router = useRouter();

      const filterListOperation = ref(props.filterList);
  
      if (props.defaultFilterList) {
        filterListOperation.value.unshift(
          {
            componentType: 'NsInput', //组件形态 NsInput-普通输入
            defaultSearch: true, //是否是默认搜索标签
            componentProps: {
              rule: {},
            },
            label: 'ID', //展示的过滤标签
            notEmpty: false, //是否允许选择非空值
            key: 'selector=name', //传入后端的key
            empty: false, //是否允许选择空值
          },
          {
            componentType: 'NsInput', //组件形态 NsInput-普通输入
            defaultSearch: true, //是否是默认搜索标签
            componentProps: {
              rule: {},
            },
            label: '名称', //展示的过滤标签
            notEmpty: false, //是否允许选择非空值
            key: 'selector=spec.display_name', //传入后端的key
            empty: false, //是否允许选择空值
          },
          {
            componentType: 'NsInput', //组件形态 NsInput-普通输入
            defaultSearch: false, //是否是默认搜索标签
            componentProps: {
              rule: {},
            },
            label: '状态', //展示的过滤标签
            notEmpty: false, //是否允许选择非空值
            key: 'selector=status.status', //传入后端的key
            empty: false, //是否允许选择空值
          },
          {
            componentType: 'NsSingleSearch', //'NsSingleSearch' 单选 /'NsMultiSearch' 多选,
            defaultSearch: false,
            componentProps: {
              //请求头需要配置的参数 例如cookie等
              headers: '',
              //候选值选中传入后端vaule字段path
              valueFieldPath: '.data[*].tenant',
              requestMethod: 'GET',
              api: '/api/passport/passport/objs/Tenant',
              //候选值展示字段path
              labelFieldPath: '.data[*].tenant',
              //获取候选值接口参数 只接受固定值
              params: 'order=created_at%20desc&pageSize=1000',
              //是否为请求接口的搜索即非固定候选值    有api默认为请求接口的搜索
              interfaceGet: true,
            },
            label: '租户',
            notEmpty: false,
            key: 'selector=spec.tenant',
            empty: false,
          },
          {
            componentType: 'NsSingleSearch', //'NsSingleSearch' 单选 /'NsMultiSearch' 多选,
            defaultSearch: false,
            componentProps: {
              //请求头需要配置的参数 例如cookie等
              headers: '',
              //候选值选中传入后端vaule字段path
              valueFieldPath: '.projects[*].projectID',
              requestMethod: 'GET',
              api: '/api/passport/passport/objs/Tenant/Projects',
              getParams: {
                tenant: 'selector=spec.tenant',
              },
              //候选值展示字段path
              labelFieldPath: '.projects[*].projectName',
              //获取候选值接口参数 只接受固定值
              params: 'order=created_at%20desc&pageSize=1000',
              //是否为请求接口的搜索即非固定候选值    有api默认为请求接口的搜索
              interfaceGet: true,
            },
            label: '项目',
            notEmpty: false,
            key: 'labels=noe.dingcloud.io/project-id',
            empty: false,
          },
        );
      }
      //下拉标签数据,props.filterList
      //const filterListOperation = ref(props.filterList);
      //默认搜索标签
      let defaultFilter = ref([]);
      const aInputFilter = ref(null);
      const filterInput = ref(null);
      const filterSingSearch = ref(null);
      const filterMultiSearch = ref(null);
      const inputShowSpan = ref(null);

      /**
       * 请求后端过滤标签接口
       * /api/dataworks-gateway/dataworks-gateway/objs/dataSource/listFilter?type=datasource-list
       */
      if (props.isNeedHttpGet) {
        let api = props.api
          ? props.api
          : `/api/dataworks-gateway/dataworks-gateway/objs/${props.terraceType}/listFilter`;
        http
          .get(api, {
            type: props.type,
          })
          .then((res) => {
            filterListOperation.value = props.filterList;
            filterListOperation.value.push(...res.data);
            initDefaultFilter();
          })
          .catch((err) => {
            initDefaultFilter();
            console.log(err);
          });
      } else {
        initDefaultFilter();
      }

      //各焦点控制值
      let focusObj = ref({
        //整个div焦点,展示边框颜色、删除标志
        divFocus: false,
        //过滤标签的焦点
        filterLabelFocus: false,
        //输入框的焦点
        focus: false,
      });

      const nsInputFilter = ref(null);

      /**
       * 选中div区域外
       */
      onClickOutside(nsInputFilter, () => {
        focusObj.value.divFocus =
          focusObj.value.filterLabelFocus =
          focusObj.value.focus =
          chooseItem.value.isChoose =
            false;
        nextTick(() => {
          inputShowSpan.value != null ? inputShowSpan.value.onClickOutsideArrayShow() : {};
        });
      });

      const inputAndPlaceholder = ref(null);

      onClickOutside(inputAndPlaceholder, () => {
        focusObj.value.filterLabelFocus = false;
      });

      /**
       * 先找到默认搜索的标签
       * 初始化默认标签
       * 1.有默认标签就使用默认
       * 2.无默认用第一个
       */
      function initDefaultFilter() {
        let defaultFilterObj: any;
        defaultFilterObj = filterListOperation.value.filter(function (elem: any) {
          return elem.defaultSearch == true;
        });
        defaultFilterObj.length >= 1
          ? (defaultFilterObj = defaultFilterObj[0])
          : (defaultFilterObj = filterListOperation.value[0]);
        defaultFilter.value = defaultFilterObj;
        nextTick(() => {
          inputShowSpan.value != null
            ? inputShowSpan.value.setDefaultFilter(defaultFilter.value)
            : {};
        });
      }

      //当前选中的标签
      const chooseItem = ref({
        isChoose: false,
        isEdit: false,
        componentType: '',
        item: {},
        empty: false,
        notEmpty: false,
        isShowEmptyDiv: false,
        showEmptyOption: [],
      });

      //input输入框绑定值
      let filterValue = ref();

      //计算input宽度
      let inputWidth = computed(() => {
        if (typeof filterValue.value == 'undefined') {
          return 8 + 'px';
        }
        return DataLength(filterValue.value) + 'px';
      });

      //实时过滤用户输入标签
      let realTimeFilterList = computed(() => {
        let list: any[] = [];
        if (typeof filterValue.value != 'undefined' && filterValue.value != '') {
          list = filterListOperation.value.filter(function (elem: any) {
            return elem.label.indexOf(filterValue.value) != -1;
          });
        } else {
          list = JSON.parse(JSON.stringify(filterListOperation.value));
        }
        if (selectedFilter.value.length > 0) {
          list = differenceBy(selectedFilter.value, list, 'label');
        }
        return list;
      });

      //二次过滤，比较list与selectedFilter（已选中）
      const differenceBy = (array1: string | any[], array2: string | any[], key: string) => {
        var result = [];
        for (var i = 0; i < array2.length; i++) {
          var obj = array2[i];
          var num = obj[key];
          var isExist = false;
          if (num && num !== 0) {
            for (var j = 0; j < array1.length; j++) {
              var aj = array1[j];
              var n = aj[key];
              if (n === num) {
                isExist = true;
                break;
              }
            }
            if (!isExist) {
              result.push(obj);
            }
          }
        }
        return result;
      };

      //选中后展示的标签与值
      const filterArrayShow = ref([]);
      //传入后端/表格filter字段
      const filterArray = ref([]);
      //已选中的标签
      const selectedFilter = ref([]);

      //获取session中的数据
      // if (sessionStorage.getItem('filterArrayShow')) {
      //   if (!check()) return;
      //   // console.log('sessionShow', JSON.parse(sessionStorage.getItem('filterArrayShow')));
      //   filterArrayShow.value = JSON.parse(sessionStorage.getItem('filterArrayShow'));
      //   selectedFilter.value = [];
      //   filterArrayShow.value.forEach((item: any) => {
      //     item.isEdit = false;
      //     selectedFilter.value.push(item.item);
      //   });
      // }
      // if (sessionStorage.getItem('filterArray')) {
      //   filterArray.value = JSON.parse(
      //     sessionStorage.getItem(`${router.currentRoute.value.fullPath}/filterInfo`),
      //   );
      //   nextTick(() => {
      //     inputShowSpan.value != null
      //       ? inputShowSpan.value.setFilterArrayList(filterArray.value)
      //       : '';
      //   });
      // }
      if (sessionStorage.getItem(`${router.currentRoute.value.fullPath}/filterInfo`)) {
        let filterInfo =
          sessionStorage.getItem(`${router.currentRoute.value.fullPath}/filterInfo`) || '{}';
        filterInfo = JSON.parse(filterInfo);
        filterArrayShow.value = filterInfo.filterArrayShow;
        selectedFilter.value = [];
        filterArrayShow.value.forEach((item: any) => {
          item.isEdit = false;
          selectedFilter.value.push(item.item);
        });
        filterArray.value = filterInfo.filterArray;
        nextTick(() => {
          inputShowSpan.value != null
            ? inputShowSpan.value.setFilterArrayList(filterArray.value)
            : '';
        });
      }

      // function check() {
      //   let getFormModel = sessionStorage.getItem(router.currentRoute.value.fullPath) || '{}';
      //   getFormModel = JSON.parse(getFormModel);
      //   console.log('router.currentRoute.value.fullPath', router.currentRoute.value.fullPath);
      //   console.log('getFormModel', getFormModel);
      //   if (!getFormModel['formModel'] || Object.keys(getFormModel['formModel']).length <= 0) {
      //     sessionStorage.removeItem('filterArrayShow');
      //     sessionStorage.removeItem('filterArray');
      //     return false;
      //   }
      //   return true;
      // }

      //触发焦点，展示过滤标签
      function focus() {
        focusObj.value.divFocus = true;
        focusObj.value.focus = true;
        if (chooseItem.value.componentType != '') {
          chooseItem.value.isChoose = true;
        }
        setTimeout(() => {
          aInputFilter.value != null
            ? aInputFilter.value.input.focus({
                cursor: 'start', // 聚焦在文本的开始位置
              })
            : '';
        }, 100);
      }

      function inputFocus() {
        focusObj.value.filterLabelFocus = true;
      }

      /**
       * 选中了某个标签
       * 1.判断组件类型--确定展示形态
       * 2.是否不为空--是否要给用户选择
       * @param item
       * @param index
       */
      function chooseLabel(item: any) {
        // closeOptions();
        if (
          item.componentType != 'NsInput' &&
          item.componentType != 'NsSingleSearch' &&
          item.componentType != 'NsMultiSearch'
        ) {
          NsMessage.error('暂未支持' + item.componentType + '形态！');
          return;
        }
        focusObj.value.focus = true;
        filterValue.value = String(item.label + '：');
        focusObj.value.filterLabelFocus = false;
        pushChooseItem(item, true);
      }

      //处理是否空值选中信息
      function pushChooseItem(item: any, isShowDiv: boolean) {
        //将选中的信息放在chooseItem中
        chooseItem.value.item = item;
        chooseItem.value.componentType =
          typeof item.componentType != 'undefined' ? item.componentType : 'NsInput';
        chooseItem.value.isChoose = isShowDiv;
        //判断空值
        if (typeof item.empty != 'undefined') chooseItem.value.empty = item.empty;
        if (typeof item.notEmpty != 'undefined') chooseItem.value.notEmpty = item.notEmpty;
        if (chooseItem.value.empty) {
          chooseItem.value.isShowEmptyDiv = isShowDiv;
          chooseItem.value.showEmptyOption.push({ label: '空', value: 'empty' });
        }
        if (chooseItem.value.notEmpty) {
          chooseItem.value.isShowEmptyDiv = isShowDiv;
          chooseItem.value.showEmptyOption.push({ label: '不为空', value: 'notEmpty' });
        }
      }

      //监听输入内容
      function valueChange(text: { data: string }) {
        if (typeof text.data != 'undefined' && text.data == '：') {
          let label = filterValue.value.split('：');
          let chooseItem = filterListOperation.value.filter(function (elem) {
            return elem.label == label[0];
          });
          if (chooseItem.length > 0 && label.length <= 2) {
            chooseLabel(chooseItem[0]);
          }
        }
      }

      //监听键盘删除
      function onKeyUpDelete(event: { key: string }) {
        if (event.key == 'Backspace') {
          if (typeof filterValue.value != 'undefined' && filterValue.value != '') {
            return;
          }
          filterArrayShow.value.pop();
          filterArray.value.pop();
          selectedFilter.value.pop();
          emitData();
        }
      }

      //搜索图标
      function searchIcon() {
        //判断是否有正在修改的span
        isEditSpanIng();
        //用户有输入的内容
        if (typeof filterValue.value != 'undefined' && filterValue.value != '') {
          let valueFormat = filterValue.value.split('：');
          if (valueFormat.length > 1 && valueFormat[1] == '') {
            emitData();
          } else {
            pressEnter();
          }
        }
        //无输入内容，用原来的搜索
        else {
          emitData();
        }
      }

      /**
       * 是否有正在修改的span，点击搜索icon时默认已完成输入
       */
      function isEditSpanIng() {
        nextTick(() => {
          inputShowSpan.value != null ? inputShowSpan.value.isEditSpanIng() : '';
        });
      }

      function singlePressEnter(value: any) {
        filterValue.value = value;
        pressEnter();
      }

      /**
       * 用户点了回车
       * 处理输入的值为想要的格式
       */
      function pressEnter() {
        console.log('huiche');
        console.log(filterValue.value);
        //判断是否有正在修改的span
        isEditSpanIng();
        if (typeof filterValue.value == 'undefined') {
          return;
        }
        var arr = Object.keys(chooseItem.value.item);
        let valueArray = filterValue.value.split('：');
        let length = valueArray.length;
        //如果输入框用户没输入
        if (
          filterValue.value &&
          length >= 1 &&
          valueArray[1] == '' &&
          filterValue.value.indexOf('：') == -1
        ) {
          return;
        }
        if (filterValue.value) {
          //用户输入 有:且内容只有一个:
          if (length >= 1 && filterValue.value.indexOf('：') != -1) {
            let label = filterValue.value.split('：')[0];
            //用户手输入 key：value 校验是否存在在标签列表中
            let checkItem = filterListOperation.value.filter(function (elem) {
              return elem.label == label;
            });
            if (checkItem.length <= 0) {
              let filterinputValue = filterValue.value;
              pushDefaultFilterValue(filterinputValue);
            }
          } else if (arr.length == 0 || filterValue.value.indexOf('：') == -1) {
            let filterinputValue = filterValue.value;
            pushDefaultFilterValue(filterinputValue);
          }
        }
        focusObj.value.filterLabelFocus = false;
        if (chooseItem.value.componentType == 'NsInput') {
          filterformatconvert(undefined, undefined);
        } else if (defaultFilter.value.componentType == 'NsSingleSearch') {
          chooseItem.value.isChoose = true;
          filterformatconvertSingle();
        } else if (defaultFilter.value.componentType == 'NsMultiSearch') {
          chooseItem.value.isChoose = true;
          filterformatconvertMulti();
        }
      }

      /**
       * 换filter为默认标签值
       */
      function pushDefaultFilterValue(filterinputValue: string) {
        filterValue.value = defaultFilter.value.label + '：' + filterinputValue;
        pushChooseItem(defaultFilter.value, false);
      }

      /**
       * input场景数据格式转换
       * @param data
       * @param dataFormatType
       */
      const dataFormatFun = (data: string | number, dataFormatType: any) => {
        switch (dataFormatType) {
          case 'int':
            data = parseInt(data);
            break;
          case 'string':
            data = data.toString();
            break;
          case 'any':
            break;
          default:
            break;
        }
        return data;
      };

      /**
       *
       */
      function filterformatconvertSingle() {
        nextTick(() => {
          filterSingSearch.value != null ? filterSingSearch.value.checkDefault() : {};
        });
      }

      /**
       *
       */
      function filterformatconvertMulti() {
        nextTick(() => {
          filterMultiSearch.value != null ? filterMultiSearch.value.checkDefault() : {};
        });
      }

      /**
       * 处理数据格式
       * 需要注意：
       * 是否是已选择搜索过的标签
       */
      function filterformatconvert(empty: string | undefined, isEmptyValue: string | undefined) {
        /**
         * 处理输入的值
         * 判断是否是已选择搜索过的标签
         * 是--改变之前对应标签的值
         * 否--找到选中的标签配置数据 去做校验、转换
         *     处理search的值
         *     处理选中后展示的标签与值 filterArrayShow
         *     处理选中后的过滤标签及新的输入框
         * 空/不为空需要做个处理
         */
        //filterValue 示例 名称：123
        let label: string | any[] = [];
        typeof isEmptyValue != 'undefined'
          ? (label = isEmptyValue.split('：'))
          : (label = filterValue.value.split('：'));
        if (label.length <= 1) {
          let filterinputValue = filterValue.value;
          filterValue.value = defaultFilter.value.label + '：' + filterinputValue;
          label = filterValue.value.split('：');
        }
        //输入数据转换 注意"|"的形式
        let itemValue = '';
        //空/不为空值
        if (empty) {
          itemValue = empty + '&empty';
        } else {
          if (label.length == 1) {
            itemValue = label[1];
          } else {
            let sliceIndex = filterValue.value.indexOf('：') + 1;
            itemValue = filterValue.value.slice(sliceIndex);
          }
        }
        // filterValue.value = '';
        //判断是否是已存在的搜索值
        let isExistence = selectedFilter.value.filter(function (elem) {
          return elem.label == label[0];
        });
        /**
         * isExistence.length>0 说明有已选择标签中存在相同的标签，那么就改对应标签的值就好了
         */
        if (isExistence.length > 0) {
          existenceLabelChangeData(itemValue, label[0]);
          return;
        }
        /**
         * 已选择的标签中没有相同的标签 先校验数据
         */
        let chooseObj = filterListOperation.value.filter(function (elem) {
          return elem.label == label[0];
        });
        let checkRes = itemValue.indexOf('&empty') != -1 ? true : checkData(chooseObj, itemValue);
        //处理选中后展示的标签与值 filterArrayShow
        processSelected(chooseObj, itemValue);
        setTimeout(() => {
          //处理search的值
          searchFilter(chooseObj, itemValue, checkRes);
        }, 100);
      }

      /**
       * 存在已选择的标签场景
       * 已选择的值selectedFilter---标签的配置信息所以不用改
       * 传入后端的值 filterArray
       * 页面展示的值 filterArrayShow
       * 校验数据看是否出发搜索
       * @param label
       * @param itemValue
       */
      function existenceLabelChangeData(itemValue: string, label: any) {
        let isExistenceItem = selectedFilter.value.filter(function (elem) {
          return elem.label == label;
        });
        filterArrayShow.value.forEach((elem, index) => {
          if (elem.label == label) {
            if (itemValue.indexOf('&empty') != -1) {
              switch (itemValue.split('&')[0]) {
                case 'empty':
                  elem.value = '空';
                  break;
                case 'notEmpty':
                  elem.value = '不为空';
                  break;
                default:
                  break;
              }
              // filterArrayShow.value[index].isEdit = false;
              // setTimeout(() => {
              //   filterArrayShow.value[index].isEdit = false;
              // }, 1000);
              elem.isEdit = false;
              elem.isShowEmptyDiv = false;
            } else {
              elem.value = itemValue;
              elem.componentType = '';
            }
          }
        });
        filterArray.value.forEach((elem, index) => {
          if (elem.name == isExistenceItem[0].key) {
            if (itemValue.indexOf('&empty') != -1) {
              switch (itemValue.split('&')[0]) {
                case 'empty':
                  if (typeof elem['notEmpty'] != 'undefined') delete elem.notEmpty;
                  break;
                case 'notEmpty':
                  if (typeof elem['empty'] != 'undefined') delete elem.empty;
                  break;
                default:
                  break;
              }
              elem[itemValue.split('&')[0]] = true;
              delete elem.value;
            } else {
              elem.value = itemValue.split('|');
            }
          }
        });
        if (itemValue.indexOf('&empty') != -1) {
          emitData();
        } else if (checkData(isExistenceItem, itemValue)) {
          filterArray.value.forEach((elem, index) => {
            if (elem.name == isExistenceItem[0].key) {
              typeof elem.rule != 'undefined' ? delete elem.rule : '';
            }
          });
          emitData();
        } else if (!checkData(isExistenceItem, itemValue)) {
          filterArray.value.forEach((elem, index) => {
            if (elem.name == isExistenceItem[0].key) {
              elem.rule = isExistenceItem[0].componentProps.rule;
              elem.value = itemValue;
            }
          });
          emitData();
        }
        setTimeout(() => {
          filterValue.value = '';
          focusObj.value.divFocus = true;
          reductionChooseItem();
        }, 100);
      }

      /**
       * input场景数据校验
       * @param chooseObj
       * @param itemValue
       */
      function checkData(chooseObj: { componentProps: { rule: any } }[], itemValue: string) {
        if (
          typeof chooseObj[0].componentType != 'undefined' &&
          chooseObj[0].componentType != 'NsInput'
        )
          return;
        let value = itemValue.split('|');
        let rule =
          typeof chooseObj[0].componentProps.rule != 'undefined' &&
          JSON.stringify(chooseObj[0].componentProps.rule) != '{}'
            ? chooseObj[0].componentProps.rule.pattern
            : 'any';
        let result = true;
        switch (rule) {
          case 'any':
            break;
          default:
            try {
              rule = new RegExp(rule.split('/')[1]);
              value.forEach((elem, index) => {
                result = rule.test(elem);
                if (!result) {
                  throw new Error('不符合');
                }
              });
            } catch (error) {
              if (error.message != '不符合') throw error;
            }
            break;
        }
        return result;
      }

      /**
       * 处理出入后端的值 filterArray
       * @param chooseObj
       * @param itemValue
       * @param checkRes
       * @param filterArrayIndex
       */
      function searchFilter(
        chooseObj: any[],
        itemValue: string,
        checkRes: boolean,
        filterArrayIndex: number,
        isEmit: boolean,
      ) {
        // debugger;
        //校验结果
        let item = {
          name: chooseObj[0].key,
        };
        itemValue.indexOf('&empty') != -1
          ? (item[itemValue.split('&')[0]] = true)
          : (item.value = itemValue.split('|'));
        if (typeof item.value != 'undefined') {
          //数据转换
          let dataFormat =
            typeof chooseObj[0].componentProps.dataFormat != 'undefined'
              ? chooseObj[0].componentProps.dataFormat
              : 'any';
          item.value.forEach((elem: any, index: string | number) => {
            item.value[index] = dataFormatFun(elem, dataFormat);
          });
        }
        typeof filterArrayIndex != 'undefined'
          ? (filterArray.value[filterArrayIndex].value = item.value)
          : filterArray.value.push(item);
        if (typeof filterArrayIndex != 'undefined') {
          if (itemValue.indexOf('&empty') == -1) {
            if (typeof filterArray.value[filterArrayIndex]['notEmpty'] != 'undefined')
              delete filterArray.value[filterArrayIndex].notEmpty;
            if (typeof filterArray.value[filterArrayIndex]['empty'] != 'undefined')
              delete filterArray.value[filterArrayIndex].empty;
          }
        }
        if (checkRes) {
          if (typeof filterArrayIndex != 'undefined') {
            typeof filterArray.value[filterArrayIndex].rule != 'undefined'
              ? delete filterArray.value[filterArrayIndex].rule
              : '';
          }
        } else {
          let length = filterArray.value.length;
          typeof filterArrayIndex != 'undefined'
            ? (filterArray.value[filterArrayIndex].rule = chooseObj[0].componentProps.rule)
            : (filterArray.value[length - 1].rule = chooseObj[0].componentProps.rule);
        }
        if (typeof isEmit == 'undefined' || isEmit) {
          emitData();
        }
      }

      /**
       * 处理filterArrayShow（span展示）
       * 页面展示的选中值
       * @param chooseObj
       * @param itemValue
       */
      function processSelected(chooseObj: any[], itemValue: string) {
        // debugger;
        //处理选中后的过滤标签及新的输入框
        processFilterLabel(chooseObj);
        setTimeout(() => {
          let filterArrayShowItem;
          if (itemValue.indexOf('&empty') != -1) {
            filterArrayShowItem = {
              label: chooseObj[0].label,
              value: '',
            };
            switch (itemValue.split('&')[0]) {
              case 'empty':
                filterArrayShowItem.value = '空';
                break;
              case 'notEmpty':
                filterArrayShowItem.value = '不为空';
                break;
              default:
                break;
            }
          } else {
            filterArrayShowItem = {
              label: chooseObj[0].label,
              value: itemValue,
            };
          }
          if (chooseItem.value.componentType == '') {
            pushChooseItem(chooseObj[0], false);
          }
          Object.assign(filterArrayShowItem, filterArrayShowItem, chooseItem.value);
          filterArrayShow.value.push(filterArrayShowItem);
          //   nextTick(() => {
          //   inputShowSpan.value != null ? inputShowSpan.value.setFilterArrayShow([]) : '';
          // });
          reductionChooseItem();
        }, 100);
      }

      /**
       * 处理选中后的过滤标签及新的输入框
       * 新的输入框，绑定的filterValue要清空
       * @param chooseObj
       */
      function processFilterLabel(chooseObj: any[]) {
        // debugger
        filterListOperation.value.forEach((elem, index) => {
          if (elem.label == chooseObj[0].label) {
            selectedFilter.value.push(elem);
          }
        });
        nextTick(() => {
          inputShowSpan.value != null
            ? inputShowSpan.value.setFilterArrayShow(selectedFilter.value, 'selectedFilter')
            : '';
        });
        setTimeout(() => {
          filterValue.value = '';
          focusObj.value.divFocus = true;
        }, 100);
      }

      /**
       * 全部删除
       */
      function delAll() {
        filterArray.value = [];
        filterArrayShow.value = [];
        nextTick(() => {
          inputShowSpan.value != null ? inputShowSpan.value.setFilterArrayShow([]) : '';
        });
        filterValue.value = '';
        selectedFilter.value = [];
        reductionChooseItem();
        emitData();
      }

      /**
       * 还原chooseItem
       */
      function reductionChooseItem() {
        chooseItem.value = {
          isChoose: false,
          isEdit: false,
          componentType: '',
          item: {},
          empty: false,
          notEmpty: false,
          isShowEmptyDiv: false,
          showEmptyOption: [],
        };
      }

      /**
       * inputWidth 计算字符长度
       * @param fData
       */
      const DataLength = (fData: string) => {
        return utils.DataLength(fData);
      };

      // watch(
      //   () => chooseItem.value,
      //   (newValue, oldValue) => {}
      // );

      /**
       * 各个组件形态
       * nsInputChange input的值变化
       */
      function nsInputChange(value: string | string[]) {
        //删除了标签
        if (value.indexOf('：') == -1) {
          setTimeout(() => {
            aInputFilter.value != null
              ? aInputFilter.value.input.focus({
                  cursor: 'start', // 聚焦在文本的开始位置
                })
              : '';
          }, 100);
          reductionChooseItem();
        }
        filterValue.value = value;
      }

      /**
       * 组件选中某个空值
       * @param item
       */
      function chooseIsEmptyLabel(item: { label?: string; value: any }, isEmptyValue: any) {
        chooseItem.value.isShowEmptyDiv = false;
        focusObj.value.filterLabelFocus = false;
        // filterValue.value = '';
        //空值和不为空值
        filterformatconvert(item.value, isEmptyValue);
      }

      /**
       * 单选组件 选中
       */
      function chooseSingleOptions(
        value: string,
        option: { value: string; label: any },
        spanIndex: number,
      ) {
        // debugger;
        let selected = filterListOperation.value.filter(function (elem) {
          return elem.label == value.split('：')[0];
        });
        let item = {
          name: selected[0].key,
        };
        if (option.value != 'notEmpty' && option.value != 'empty') {
          item.value = [option.value];
        } else {
          item[option.value] = true;
        }
        let show = {
          label: value.split('：')[0],
          value: option.label,
          optionsValue: option.value,
        };
        if (spanIndex == -1) {
          selectedFilter.value.push(selected[0]);
          filterArray.value.push(item);
          Object.assign(show, show, chooseItem.value);
          filterArrayShow.value.push(show);
        } else {
          filterArray.value[spanIndex] = item;
          Object.assign(filterArrayShow.value[spanIndex], filterArrayShow.value[spanIndex], show);
          filterArrayShow.value[spanIndex].isEdit = false;
        }
        emitData();
        filterValue.value = '';
        focusObj.value.filterLabelFocus = false;
        reductionChooseItem();
      }

      /**
       * chooseMultiOptions 多选组件
       */
      function chooseMultiOptions(
        value: string,
        showValue: any,
        arrayValue: { value: any },
        spanIndex: number,
      ) {
        let selected = filterListOperation.value.filter(function (elem) {
          return elem.label == value.split('：')[0];
        });
        let arrayItem = {
          name: selected[0].key,
        };
        let show = {
          label: value.split('：')[0],
          value: showValue,
          optionsValue: arrayValue.value,
        };
        // debugger;
        Object.assign(arrayItem, arrayItem, arrayValue);
        if (spanIndex == -1) {
          selectedFilter.value.push(selected[0]);
          Object.assign(show, show, chooseItem.value);
          filterArray.value.push(arrayItem);
          filterArrayShow.value.push(show);
        } else {
          filterArray.value[spanIndex] = arrayItem;
          Object.assign(filterArrayShow.value[spanIndex], filterArrayShow.value[spanIndex], show);
          filterArrayShow.value[spanIndex].isEdit = false;
        }
        emitData();
        filterValue.value = '';
        focusObj.value.filterLabelFocus = false;
        reductionChooseItem();
      }

      /**
       * 多选组件取消
       */
      function canel(index: number) {
        filterValue.value = '';
        focusObj.value.filterLabelFocus = false;
        if (index != -1) {
          filterArrayShow.value[index].isEdit = false;
        }
        reductionChooseItem();
      }

      /**
       * table发送数据
       */
      function emitData(type: string | undefined) {
        // console.log('发送数据！！！');
        // nextTick(() => {
        //   inputShowSpan.value != null
        //     ? inputShowSpan.value.setFilterArrayShow(filterArrayShow.value)
        //     : '';
        // });
        if (type != 'notChange') {
          nextTick(() => {
            inputShowSpan.value != null
              ? inputShowSpan.value.setFilterArrayList(filterArray.value)
              : '';
          });
        }
        let sendArray: never[] = [];
        for (let i = 0; i < filterArray.value.length; i++) {
          for (let j = i + 1; j < filterArray.value.length; j++) {
            if (filterArray.value[i].name == filterArray.value[j].name) {
              filterArray.value.splice(i, 1);
              filterArrayShow.value.splice(i, 1);
            }
          }
        }
        nextTick(() => {
          inputShowSpan.value != null
            ? inputShowSpan.value.setFilterArrayShow(filterArrayShow.value)
            : '';
        });
        filterArray.value.forEach((elem: any) => {
          if (typeof elem.rule == 'undefined') {
            let item = elem;
            if (typeof item.value != 'undefined' && item.value[0] == '空') {
              item.value.splice(0, 1);
              item.empty = true;
            } else if (typeof item.value != 'undefined' && item.value[0] == '不为空') {
              item.value = [];
              item.notEmpty = true;
            }
            sendArray.push(item);
          } else {
            NsMessage.error('请输入' + elem.rule.message);
          }
        });
        let routeInfo = {
          filterArrayShow: filterArrayShow.value,
          filterArray: filterArray.value,
        };
        sessionStorage.setItem(
          `${router.currentRoute.value.fullPath}/filterInfo`,
          JSON.stringify(routeInfo),
        );
        // sessionStorage.setItem('filterArrayShow', JSON.stringify(filterArrayShow.value));
        // sessionStorage.setItem('filterArray', JSON.stringify(filterArray.value));
        if (sendArray.length > 0) {
          ctx.emit('change', encodeURIComponent(JSON.stringify(sendArray)));
        } else {
          sessionStorage.removeItem(`${router.currentRoute.value.fullPath}/filterInfo`);
          ctx.emit('change', null);
        }
        ctx.emit('search');
      }

      function showSpanChage() {
        emitData('notChange');
      }

      watch(
        () => router.currentRoute.value,
        (newValue: any) => {
          // console.log('thisRouter', thisRouter.value);
          // console.log('newValue', newValue);
          if (thisRouter.value != null && newValue.path != thisRouter.value.path) {
            if (newValue.path.indexOf(thisRouter.value.name) == -1) {
              // sessionStorage.removeItem('filterArrayShow');
              // sessionStorage.removeItem('filterArray');
              sessionStorage.removeItem(`${router.currentRoute.value.fullPath}/filterInfo`);
            }
          }
        },
        { immediate: true },
      );

      onBeforeRouteLeave((to, from, next) => {
        removeInfo();
        next();
      });

      function removeInfo() {
        ctx.emit('change', null);
        ctx.emit('search');
        // sessionStorage.removeItem('filterArrayShow');
        // sessionStorage.removeItem('filterArray');
        sessionStorage.removeItem(`${router.currentRoute.value.fullPath}/filterInfo`);
      }

      onMounted(() => {
        thisRouter.value = router.currentRoute.value;
      });

      return {
        selectedFilter,
        focus,
        inputFocus,
        defaultFilter,
        focusObj,
        chooseItem,
        filterArrayShow,
        inputShowSpan,
        realTimeFilterList,
        filterListOperation,
        nsInputFilter,
        inputAndPlaceholder,
        inputWidth,
        filterValue,
        aInputFilter,
        filterInput,
        filterSingSearch,
        filterMultiSearch,
        delAll,
        chooseLabel,
        pressEnter,
        valueChange,
        searchIcon,
        onKeyUpDelete,
        chooseIsEmptyLabel,
        nsInputChange,
        chooseSingleOptions,
        chooseMultiOptions,
        canel,
        showSpanChage,
        filterformatconvert,
        searchFilter,
        processSelected,
        singlePressEnter,
        filterArray,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-btn) {
    padding: 0 !important;
  }
  :deep(.ns-form-item) {
    min-width: 600px !important;
  }
  .ns-input-filter {
    position: relative;
    width: 150%;
    height: 30px;
    border: 1px solid #dcdfe2;
    padding-left: 4px;
    padding-right: 28px;
    float: right;
  }
  .ns-input-filter-long-focus {
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 9;
    width: 200%;
    background: #fff;
    border: 1px solid;
    border-color: @primary-color;
    box-shadow: 0 0 0 2px rgb(44 104 255 / 20%);
  }
  .ns-input-filter-list {
    border-radius: 0;
    background-color: #fff;
    box-shadow: 0 0 16px 0 rgb(54 58 80 / 16%);
    min-width: 150px;
    color: rgba(0, 0, 0, 0.9);
    max-height: 240px;
    overflow-y: auto;
  }
  .ns-input-filter-content {
    position: absolute;
    z-index: 9;
  }
  .filter-list-text {
    overflow-y: auto;
    padding: 0;
    list-style: none;
    color: rgba(0, 0, 0, 0.9);
    margin: 0px;
  }
  .filter-list-text > li.is-disabled {
    background-color: transparent;
    color: rgba(0, 0, 0, 0.25);
    cursor: not-allowed;
  }
  .filter-list-text > li:first-child,
  .filter-list-text > li:last-child {
    border-radius: 0 0 0 0;
  }
  .filter-list-text > li:hover {
    background-color: #ebeef2;
  }
  .filter-list-text > li {
    margin-bottom: 0;
    font-size: 12px;
    padding: 6px 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #000;
    display: block;
    cursor: pointer;
  }
  .ns-input-filter-input-show {
    display: inline-block;
    vertical-align: middle;
    width: 100%;
    overflow: hidden;
    height: 100%;
    border-right: 1px solid #dcdfe2;
  }
  .ns-input-filter-input-show-focus {
    display: inline-block;
    vertical-align: middle;
    width: 100%;
    padding-right: 44px;
    padding-left: 4px;
  }

  :deep(.ant-input) {
    border: transparent !important;
  }
  .ant-input:focus {
    border: transparent !important;
    box-shadow: none !important;
  }
  .filter-array-group {
    margin-top: 0;
    vertical-align: top;
    white-space: normal;
    display: inline-block;
    font-size: 0;
    line-height: normal;
    cursor: pointer;
  }

  .search-icon {
    cursor: pointer;
    margin: auto;
    position: absolute;
    right: 6px;
    bottom: 7px;
    background: #fff;
    width: 16px;
    height: 14px;
    display: inline-block;
    vertical-align: middle;
    background-repeat: no-repeat;
    background-position: inherit;
    font-size: 0;
    background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTYgMkM4LjIgMiAxMCAzLjggMTAgNkMxMCA4LjIgOC4yIDEwIDYgMTBDMy44IDEwIDIgOC4yIDIgNkMyIDMuOCAzLjggMiA2IDJaTTYgMUMzLjIzNzUgMSAxIDMuMjM3NSAxIDZDMSA4Ljc2MjUgMy4yMzc1IDExIDYgMTFDOC43NjI1IDExIDExIDguNzYyNSAxMSA2QzExIDMuMjM3NSA4Ljc2MjUgMSA2IDFaTTkuODU2MjkgOS4xODM3TDkuMTQzNzkgOS44OTYyTDE0LjEzNzUgMTQuODYyNUwxNC44NSAxNC4xNUw5Ljg1NjI5IDkuMTgzN1oiIGZpbGw9ImJsYWNrIiBmaWxsLW9wYWNpdHk9IjAuNDUiLz4KPC9zdmc+);
  }
  .close-span {
    width: 16px;
    height: 16px;
    vertical-align: middle;
    background-repeat: no-repeat;
    background-position: inherit;
    font-size: 0;
  }
  .close-icon {
    position: absolute;
    right: 2px;
    bottom: 0;
    top: 0;
    margin: auto;
    background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTcuOTk3NCAxQzQuMTMyODQgMSAxIDQuMTMyODUgMSA3Ljk5NzRDMSAxMS44NjE5IDQuMTMyODUgMTQuOTk0OCA3Ljk5NzQgMTQuOTk0OEMxMS44NjE5IDE0Ljk5NDggMTQuOTk0OCAxMS44NjE5IDE0Ljk5NDggNy45OTc0QzE0Ljk5NDggNC4xMzI4NSAxMS44NjE5IDEgNy45OTc0IDFaTTUuNTYyNTQgMTEuNjM4OEw0LjQyMzU3IDEwLjUwNjdMNi45MTQyMSA4LjAwMDk3TDQuNDA4NDQgNS41MTAzMkw1LjU0MDU0IDQuMzcxMzVMOC4wNDYzMyA2Ljg2MTk5TDEwLjUzNyA0LjM1NjIyTDExLjY3NTkgNS40ODgzM0w5LjE4NTMgNy45OTQwOUwxMS42OTExIDEwLjQ4NDhMMTAuNTU5IDExLjYyMzdMOC4wNTMyIDkuMTMzMDlMNS41NjI1NCAxMS42Mzg4WiIgZmlsbD0iYmxhY2siIGZpbGwtb3BhY2l0eT0iMC40Ii8+Cjwvc3ZnPg==);
  }
  .all-close-span {
    width: 16px;
    height: 16px;
    vertical-align: middle;
    background-repeat: no-repeat;
    background-position: inherit;
    font-size: 0;
  }
  .all-close-icon {
    cursor: pointer;
    position: absolute;
    right: 24px;
    bottom: 5px;
    background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTcuOTk3NCAxQzQuMTMyODQgMSAxIDQuMTMyODUgMSA3Ljk5NzRDMSAxMS44NjE5IDQuMTMyODUgMTQuOTk0OCA3Ljk5NzQgMTQuOTk0OEMxMS44NjE5IDE0Ljk5NDggMTQuOTk0OCAxMS44NjE5IDE0Ljk5NDggNy45OTc0QzE0Ljk5NDggNC4xMzI4NSAxMS44NjE5IDEgNy45OTc0IDFaTTUuNTYyNTQgMTEuNjM4OEw0LjQyMzU3IDEwLjUwNjdMNi45MTQyMSA4LjAwMDk3TDQuNDA4NDQgNS41MTAzMkw1LjU0MDU0IDQuMzcxMzVMOC4wNDYzMyA2Ljg2MTk5TDEwLjUzNyA0LjM1NjIyTDExLjY3NTkgNS40ODgzM0w5LjE4NTMgNy45OTQwOUwxMS42OTExIDEwLjQ4NDhMMTAuNTU5IDExLjYyMzdMOC4wNTMyIDkuMTMzMDlMNS41NjI1NCAxMS42Mzg4WiIgZmlsbD0iYmxhY2siIGZpbGwtb3BhY2l0eT0iMC40Ii8+Cjwvc3ZnPg==);
  }
  .input-and-placeholder {
    margin-top: 0;
    vertical-align: top;
    display: inline-block;
    font-size: 0;
    line-height: normal;
    .ns-input-content {
      font-size: 0;
      line-height: normal;
      display: inline-block;
      vertical-align: top;
      position: relative;
      width: v-bind(inputWidth);
      max-width: 400px;
      cursor: text;

      :deep(.ant-input) {
        padding: 3px 0px !important;
        border: transparent !important;
        vertical-align: top;
        position: relative;
        width: v-bind(inputWidth);
        max-width: 400px;
        display: inline-block;
      }

      .ns-input-content-1 {
      }
    }
    .ns-input-content-no-focus {
      font-size: 0;
      line-height: normal;
      display: inline-block;
      vertical-align: top;
      position: relative;
      width: 8px;
      max-width: 400px;
      cursor: text;

      :deep(.ant-input) {
        padding: 3px 2px !important;
        border: transparent !important;
        vertical-align: top;
        position: relative;
        width: 10px;
        max-width: 400px;
      }
    }
    .placeholder {
      position: relative;
      user-select: none;
      line-height: 28px;
      font-size: 12px;
      display: inline-block;
      color: rgba(0, 0, 0, 0.25) !important;
      cursor: text;
      margin-left: 0px;
    }
  }
</style>
