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

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

    const c = props.controller!;

    // 当前表单项绑定值key的集合
    const curValue: Ref<Array<string>> = ref([]);

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

    // 选中项key-value键值对
    const selectItems: Ref<IData[]> = ref([]);

    // 下拉是否打开
    const open = ref(false);

    // 加载中
    const loading: Ref<boolean> = ref(false);

    // 组件实例
    const selectRef: Ref<Vue | null> = ref(null);

    // 远程搜索默认值
    const defaultLabel: Ref<string[]> = ref([]);

    // 监听传入值
    watch(
      () => props.value,
      newVal => {
        curValue.value = [];
        selectItems.value = [];
        if (newVal) {
          selectItems.value = JSON.parse(newVal);
          if (selectItems.value.length > 0) {
            selectItems.value.forEach((item: IData) => {
              // 选项没有的时候补充选项
              const index = items.value.findIndex(i =>
                Object.is(i.srfkey, item.srfkey),
              );
              if (index < 0) {
                items.value.push(item);
                defaultLabel.value.push(item.srfmajortext);
              }
              // 赋值
              curValue.value.push(item.srfkey);
            });
          }
        }
      },
      { immediate: true, deep: true },
    );

    // 处理视图关闭，往外抛值
    const handleOpenViewClose = async (result: IData[]) => {
      // 抛出值集合
      const valArr: IData[] = [];
      if (result && Array.isArray(result)) {
        for (let i = 0; i < result.length; i++) {
          const select = result[i];
          // 回显并且回来的选中值只有srfkey和srfmajortext,所以||
          const formattedItem = {
            srfkey: select[c.keyName] || select.srfkey,
            srfmajortext: select[c.textName] || select.srfmajortext,
          };
          // 自填模式
          // eslint-disable-next-line no-await-in-loop
          const dataItems = await c.calcFillDataItems(select);
          if (dataItems.length > 0) {
            dataItems.forEach(dataItem => {
              Object.assign(formattedItem, {
                [dataItem.name]: dataItem.value,
              });
            });
          }
          valArr.push(formattedItem);

          // 选项不存在的补充到选项里
          const index = items.value.findIndex(item =>
            Object.is(item[c.keyName], select[c.keyName]),
          );
          if (index < 0) {
            items.value.push(formattedItem);
          }
        }
      }
      const value = valArr.length > 0 ? JSON.stringify(valArr) : '';
      emit('change', value);
    };

    // 打开数据选择视图
    const openPickUpView = async () => {
      let selectedData;
      if (selectItems.value.length) {
        selectedData = JSON.stringify(selectItems.value);
      }
      const res = await c.openPickUpView(props.data!, selectedData);
      if (res) {
        handleOpenViewClose(res);
      }
    };

    // 下拉选中回调
    const onSelect = (selects: string[]) => {
      const valArr: Array<IData> = [];
      if (selects.length > 0) {
        selects.forEach((select: string) => {
          let index = items.value.findIndex(item =>
            Object.is(item.srfkey, select),
          );
          let findItem: IData | null = null;
          if (index >= 0) {
            findItem = items.value[index];
          } else {
            index = selectItems.value.findIndex((item: IData) =>
              Object.is(item.srfkey, select),
            );
            if (index >= 0) {
              findItem = selectItems.value[index];
            }
          }
          if (findItem) {
            valArr.push(findItem);
          }
        });
        const value = valArr.length > 0 ? JSON.stringify(valArr) : '';
        emit('change', value);
      } else {
        emit('change', '');
      }
    };

    // 搜索
    const onSearch = async (query: string) => {
      if (c.model.appDataEntity) {
        loading.value = true;
        try {
          const res = await c.getServiceData(query, props.data!);
          loading.value = false;
          if (res.data.length > 0) {
            items.value = res.data.map(item => ({
              srfkey: item[c.keyName],
              srfmajortext: item[c.textName],
            }));
          }
        } catch (error) {
          loading.value = false;
        }
      }
    };

    // 下拉打开
    const onOpenChange = (flag: boolean) => {
      open.value = flag;
      emit('operate', flag);
      if (open.value) {
        onSearch('');
      }
    };

    // 信息展示，只显示名称。
    const valueText = computed(() => {
      return selectItems.value
        .map(item => {
          return item.srfmajortext;
        })
        .join('、');
    });

    const setDefaultOptions = (options: IData[]) => {
      items.value = options;
    };

    return {
      ns,
      c,
      selectRef,
      curValue,
      loading,
      items,
      defaultLabel,
      valueText,
      onSearch,
      onOpenChange,
      onSelect,
      openPickUpView,
      setDefaultOptions,
    };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.readonly && this.valueText}
        {!this.readonly && (
          <i-select
            ref='selectRef'
            value={this.curValue}
            filterable
            transfer
            multiple
            default-label={this.defaultLabel}
            loading={this.loading}
            placeholder={this.c.placeHolder}
            remote-method={this.onSearch}
            on-on-open-change={this.onOpenChange}
            on-on-change={this.onSelect}
            disabled={this.disabled}
          >
            {this.items.map(item => {
              return (
                <i-option
                  key={item.srfkey}
                  value={item.srfkey}
                  label={item.srfmajortext}
                >
                  {item.srfmajortext}
                </i-option>
              );
            })}
          </i-select>
        )}
        {!this.readonly && (
          <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}
            </div>
          </div>
        )}
      </div>
    );
  },
});
