import { Input, message } from 'antd';
import _ from 'lodash';
import { useCallback, useState } from 'react';
import { useIntl } from 'umi';
import DynamicForm from '../DynamicForm';
import AddSelect from './select';
import { useControllableValue } from 'ahooks';

const messageLocaleKey = {
  addTagValTips: '请选择标签名称',
  tagName: '标签名称',
  tagNameAddName: '添加标签名称',
  tagVal: '标签值',
  tagValAddName: '添加标签值',
};

export interface TagRuleValue {
  tag_id?: number;
  tag_name?: string;
  tag_value?: string;
}

export interface TagRuleOptions {
  label: string;
  value: string | number;
  disabled?: boolean;
  children?: TagRuleOptions[];
}

export interface TagRuleSelectProps {
  options: TagRuleOptions[];
  value?: TagRuleValue[];
  onChange?: (val: TagRuleValue[]) => void;
}

const TagRuleSelect = (props: TagRuleSelectProps) => {
  const { options: parentOps } = props;
  const [options, setOptions] = useState<TagRuleOptions[]>(parentOps || []);
  const [value, onChange] = useControllableValue(props);
  const { formatMessage } = useIntl();

  const addTagNameHandler = useCallback(
    (inputVal: string): boolean => {
      setOptions([
        ...options,
        {
          label: inputVal,
          value: inputVal,
          children: [],
        },
      ]);
      return true;
    },
    [options],
  );

  const addTagValHandler = useCallback(
    (inputVal: string, item: TagRuleValue): boolean => {
      const o = options.find((v) => v.value === item?.tag_name);
      if (!o) {
        message.warn(formatMessage({ id: messageLocaleKey.addTagValTips }));
        return false;
      }
      const newOp = { label: inputVal, value: -Number(_.uniqueId()) };
      o.children = [...(o.children || []), newOp];
      setOptions([...options]);
      return true;
    },
    [formatMessage, options],
  );

  return (
    <DynamicForm
      value={value}
      onChange={onChange}
      format={(vals: TagRuleValue[]) => {
        const res = vals.map((item) => {
          if (item?.tag_id && item?.tag_name) {
            const tagValOptions = options?.find((v) => v.value === item?.tag_name)?.children || [];
            item.tag_value = tagValOptions.find((v) => v.value === item?.tag_id)?.label;
          }
          return item;
        });
        return res;
      }}
    >
      <AddSelect
        options={options}
        addName={formatMessage({ id: messageLocaleKey.tagNameAddName })}
        onOptionAdd={addTagNameHandler}
        name={'tag_name'}
        changeCleans={['tag_id', 'tag_value']}
        rules={[{ required: true }]}
      />

      {(item: TagRuleValue) => {
        const tagValOptions = options?.find((v) => v.value === item?.tag_name)?.children || [];
        return (
          <AddSelect
            disabled={!item?.tag_name}
            options={tagValOptions}
            addName={formatMessage({ id: messageLocaleKey.tagValAddName })}
            onOptionAdd={(v) => addTagValHandler(v, item)}
            name={'tag_id'}
            rules={[{ required: true }]}
          />
        );
      }}

      <Input name={'tag_value'} hidden />
    </DynamicForm>
  );
};

export default TagRuleSelect;
