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

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

    const c = props.controller!;

    const curValue: Ref<string> = ref('');

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal && newVal !== oldVal) {
          curValue.value = `${newVal}`;
        }
      },
      { immediate: true },
    );

    // 处理视图关闭，往外抛值
    const handleOpenViewClose = (result: IData[]) => {
      const item: IData = {};
      if (result && Array.isArray(result)) {
        Object.assign(item, result[0]);
      }
      if (c.valueItem) {
        emit('change', item[c.keyName], c.valueItem);
      }
      emit('change', item[c.textName]);
    };

    // 打开数据链接视图
    const openLinkView = async () => {
      const res = await c.openLinkView(props.data!);
      if (res) {
        handleOpenViewClose(res);
      }
    };
    return { ns, openLinkView, curValue };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.disabled ? (
          this.value
        ) : (
          <a on-click={this.openLinkView}>{this.curValue}</a>
        )}
      </div>
    );
  },
});
