import { ref, watch, Ref, defineComponent } from 'vue';
import {
  getDataPickerProps,
  getEditorEmits,
  useNamespace,
} from '@ibiz-template/vue-util';
import { isEmpty } from 'ramda';
import '@ibiz-template/theme/style/components/editor/ibiz-picker/ibiz-picker.scss';

export const IBizPicker = defineComponent({
  name: 'IBizPicker',
  props: getDataPickerProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('picker');

    const c = props.controller!;

    // 当前值
    const curValue: Ref<Array<string> | string | null> = ref('');

    // 实体数据集
    const items: Ref<IData[]> = ref([]);

    // 是否显示所有数据
    const isShowAll = ref(true);

    watch(
      () => props.value,
      newVal => {
        if (newVal || newVal === null) {
          curValue.value = newVal;
          if (newVal === null) {
            curValue.value = '';
          }
          const value = props.data[c.valueItem];
          const index = items.value.findIndex((item: IData) =>
            Object.is(item[c.keyName], value),
          );
          if (index !== -1) {
            return;
          }
          // items里匹配不到当前值项值时，生成自身的选项
          items.value = [];
          if (!isEmpty(newVal) && !isEmpty(value)) {
            items.value.push({ [c.textName]: newVal, [c.keyName]: value });
          }
        }
      },
      { immediate: true },
    );

    // 处理选中数据后的处理逻辑
    const handleDataSelect = async (data: IData) => {
      // 处理回填数据
      const dataItems = await c.calcFillDataItems(data);
      if (dataItems.length) {
        dataItems.forEach(dataItem => {
          emit('change', dataItem.value, dataItem.name);
        });
      }

      // 处理值项和本身的值
      if (c.valueItem) {
        emit('change', data[c.keyName], c.valueItem);
      }
      emit('change', data[c.textName]);
    };

    // 打开数据选择视图
    const openPickUpView = async () => {
      const res = await c.openPickUpView(props.data);
      if (res && res[0]) {
        await handleDataSelect(res[0]);
      }
    };

    // 打开数据链接视图
    const openLinkView = async () => {
      await c.openLinkView(props.data);
    };

    // 往外抛值
    const onACSelect = async (item: IData) => {
      await handleDataSelect(item);
      isShowAll.value = true;
      emit('operate', false);
    };

    // 搜索
    const onSearch = async (query: string) => {
      if (c.model.appDataEntity) {
        const res = await c.getServiceData(query, props.data);
        if (res) {
          items.value = res.data as IData[];
        }
      }
    };

    // 清除
    const onClear = () => {
      // 清空回填数据
      const dataItems = c.model.deACMode?.dataItems;
      if (dataItems?.length) {
        dataItems.forEach(dataItem => {
          emit('change', null, dataItem.name);
        });
      }
      if (c.valueItem) {
        emit('change', null, c.valueItem);
      }
      emit('change', null);
    };

    // 聚焦
    const onFocus = (e: IData) => {
      emit('operate', true);
      const query = isShowAll.value ? '' : e.target.value;
      onSearch(query);
    };

    // 失焦
    const onBlur = () => {
      emit('operate', false);
    };

    const closeCircle = (c.linkView ? 1 : 0) + (c.pickupView ? 1 : 0);

    return {
      ns,
      c,
      curValue,
      items,
      openPickUpView,
      openLinkView,
      onACSelect,
      onSearch,
      onClear,
      onFocus,
      closeCircle,
      onBlur,
    };
  },
  render() {
    if (this.readonly) {
      return (
        <div class={(this.ns.b(), this.ns.m('readonly'))}>{this.value}</div>
      );
    }
    return (
      <div class={[this.ns.b(), this.disabled ? this.ns.m('disabled') : '']}>
        {this.c.noAC ? (
          <i-input
            value={this.curValue}
            clearable
            placeholder={this.c.placeHolder}
            on-on-clear={this.onClear}
            disabled={this.disabled}
          >
            {this.$slots.append}
            {!this.$slots.append && this.c.pickupView ? (
              <i-button
                key='ios-search'
                icon='ios-search'
                on-click={this.openPickUpView}
              ></i-button>
            ) : null}
            {!this.$slots.append && this.c.linkView ? (
              <i-button
                key='ios-search-outline'
                icon='ios-search-outline'
                on-click='openLinkView'
              ></i-button>
            ) : null}
          </i-input>
        ) : (
          <div
            class={[
              this.ns.e('autocomplete'),
              this.ns.m(this.closeCircle.toString()),
            ]}
          >
            <i-auto-complete
              value={this.curValue}
              placeholder={this.c.placeHolder}
              placement='bottom'
              clearable
              transfer-class-name={this.ns.e('transfer')}
              on-on-focus={this.onFocus}
              on-on-search={this.onSearch}
              on-on-clear={this.onClear}
              on-on-blur={this.onBlur}
              disabled={this.disabled}
            >
              {this.items.map(item => {
                return (
                  <div
                    class={this.ns.e('transfer-item')}
                    on-click={() => {
                      this.onACSelect(item);
                    }}
                  >
                    {item[this.c.textName]}
                  </div>
                );
              })}
            </i-auto-complete>
            <div class={this.ns.e('buns-position')}>
              <div class={this.ns.e('btns')}>
                {this.c.pickupView ? (
                  <i-button
                    icon='ios-search'
                    on-click={this.openPickUpView}
                    type={'text'}
                  ></i-button>
                ) : null}
                {this.c.linkView ? (
                  <i-button
                    on-click={this.openLinkView}
                    type={'text'}
                    class={this.ns.e('link')}
                  >
                    <ion-icon src={'./assets/img/link.svg'}></ion-icon>
                  </i-button>
                ) : null}
              </div>
            </div>
          </div>
        )}
      </div>
    );
  },
});
