import type { PropType } from 'vue';
import { defineComponent, ref, reactive, toRaw } from 'vue';
import { TagValue, IType, ValueItem } from './type';
import type { ChangeEvent } from 'ant-design-vue/lib/_util/EventInterface';
import { Popover, Input } from 'ant-design-vue';
import { uniqBy } from 'lodash';
import { EditorInterface } from '@aomao/engine';

type TagVauleItem = ValueItem & { isCustom: boolean };

export const defaultValue: ValueItem[] = [
  {
    type: 'abandon',
    background: '#FFE8E6',
    color: '#820014',
    text: '废弃',
  },
  {
    type: 'must',
    background: '#ebf3ff',
    color: '#338aff',
    text: '必填',
  },
  {
    type: 'add',
    background: '#d8eecd',
    color: '#5ca537',
    text: '新增',
  },
  {
    type: 'delete',
    background: '#ffe9bc',
    color: '#dc9300',
    text: '删除',
  },
];

const getInitData = (list: ValueItem[], value: TagValue, local: Record<string, any>) => {
  const { tagType, tagValue, isCustom } = value;
  const data = list.find(item => item.type === tagType) || list[0];

  if (isCustom) {
    return {
      ...data,
      text: tagValue || local['addTag'],
      isCustom: true,
    };
  }

  return {
    ...data,
    text: tagType ? data.type : local['addTag'],
    isCustom: false,
  };
};

export default defineComponent({
  name: 'tag-comp',
  props: {
    value: { type: Object as PropType<TagValue>, required: true },
    editor: { type: Object as PropType<EditorInterface>, required: true },
    defaultVisible: { type: Boolean, required: false },
    change: { type: Function as PropType<(item: any) => void> },
  },
  setup(props) {
    const { value, editor, defaultVisible, change } = toRaw(props);
    const { tagType, tagValue, isCustom } = value;
    const local: any = editor.language.get('tag');
    const initData: ValueItem[] = defaultValue.map(item => ({
      ...item,
      text: local[item.type],
    }));
    const data = getInitData(initData, value, local);
    const description = isCustom ? tagValue : '';

    const type = ref(tagType);
    let activeValue = reactive(data);
    const customText = ref(description);
    const visible = ref(defaultVisible);

    const hide = () => {
      visible.value = false;
    };

    const handleVisibleChange = (newVisible: boolean) => {
      visible.value = newVisible;
    };

    const onClick = (item: ValueItem) => {
      type.value = item.type;
      customText.value = '';
      activeValue = reactive({ ...item, isCustom: false });
      if (change) {
        change(activeValue);
        hide();
      }
    };

    const onCustomClick = (item: ValueItem) => {
      type.value = item.type;
      activeValue = reactive({
        ...item,
        text: customText.value,
        isCustom: true,
      });

      if (change) {
        change(activeValue);
      }
    };

    const onInputChange = (e: ChangeEvent) => {
      customText.value = e.target.value || '';
      activeValue.isCustom = true;
    };

    const onPressEnter = () => {
      type.value = activeValue.type || 'abandon';
      activeValue = reactive({ ...activeValue, text: customText.value });
      if (change) {
        change(activeValue);
        hide();
      }
    };

    return () => {
      return (
        <Popover
          visible={visible.value}
          trigger={'click'}
          placement="bottomLeft"
          overlayClassName="tag-plugin-tooltip"
          onVisibleChange={handleVisibleChange}
          overlayStyle={{
            padding: 0,
            boxShadow: '0px 2px 4px 0px rgba(225 225 225, .5)',
          }}
          content={
            <div class="tag-plugin-tooltip-contain">
              <div class="tag-plugin-tooltip-default">
                <div class="tag-plugin-tooltip-title">{local['defaultTag']}</div>
                {initData.map(item => (
                  <span
                    key={item.type}
                    style={{
                      minWidth: 22,
                      color: item.color,
                      background: item.background,
                    }}
                    onClick={() => onClick(item)}
                  >
                    {type.value === item.type && !activeValue.isCustom && (
                      <svg width={12} height={12} fill={item.color} viewBox="0 0 18 18" style={{ marginRight: 2 }}>
                        <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />
                      </svg>
                    )}
                    {item.text}
                  </span>
                ))}
              </div>
              <div class="tag-plugin-tooltip-custom">
                <div class="tag-plugin-tooltip-title">{local['customTag']}</div>
                <div class="tag-plugin-tooltip-custom-theme">
                  {initData.map(item => (
                    <span
                      key={item.type}
                      style={{
                        color: item.color,
                        background: item.background,
                      }}
                      onClick={() => {
                        onCustomClick(item);
                      }}
                    >
                      {type.value === item.type && activeValue.isCustom && (
                        <svg width={12} height={12} fill={item.color} viewBox="0 0 18 18" style={{ marginRight: 2 }}>
                          <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />
                        </svg>
                      )}
                    </span>
                  ))}
                </div>
                <Input size="small" value={customText.value} placeholder={local['placeholder']} onChange={onInputChange} onPressEnter={onPressEnter} />
              </div>
            </div>
          }
        >
          <div
            class="tag-plugin-contain"
            style={{
              color: activeValue.color,
              background: activeValue.background,
            }}
          >
            {activeValue.text || local['addTag']}
          </div>
        </Popover>
      );
    };
  },
});
