import { message, Form } from 'ant-design-vue/es';
import { reactive, toRaw, watch } from 'vue';
import { graphG6, selectSourceTargetOptions } from './useGraph';
import useI18n from '@/hooks/useI18n';

export default function useCombo() {
  const { t } = useI18n();

  /**图分组内置类型 */
  const comboTypeOptions = [
    {
      value: 'circle',
      label: t('views.monitor.topologyBuild.comboTypeCircle'),
    },
    {
      value: 'rect',
      label: t('views.monitor.topologyBuild.comboTypeRect'),
    },
  ];

  /**图分组标签文本位置 */
  const comboLabelPositionOptions = [
    {
      value: 'top',
      label: t('views.monitor.topologyBuild.comboLabelPositionTop'),
    },
    {
      value: 'left',
      label: t('views.monitor.topologyBuild.comboLabelPositionLeft'),
    },
    {
      value: 'right',
      label: t('views.monitor.topologyBuild.comboLabelPositionRight'),
    },
    {
      value: 'bottom',
      label: t('views.monitor.topologyBuild.comboLabelPositionBottom'),
    },
    {
      value: 'center',
      label: t('views.monitor.topologyBuild.comboLabelPositionCenter'),
    },
  ];

  /**图分组信息状态类型 */
  type ComboStateType = {
    /**图分组原始数据 */
    origin: Record<string, any>;
    /**图分组表单数据 */
    form: Record<string, any>;
  };

  /**图分组信息状态 */
  let comboState: ComboStateType = reactive({
    origin: {},
    form: {
      id: '',
      type: 'rect',
      parentId: '',
      size: [40, 40],
      padding: [30, 30, 30, 30],
      style: {
        radius: 2,
        fill: '#ffffff',
        stroke: '#ffffff',
        lineWidth: 1,
        cursor: 'grab',
        fillOpacity: 0.5,
      },
      label: '',
      labelCfg: {
        refX: 10,
        refY: 10,
        position: 'top',
        style: {
          fill: '#000000',
          fontSize: 12,
          fontWeight: 500,
        },
      },
      children: [], // 子元素
    },
  });

  /**图分组对话分组内表单属性和校验规则 */
  const comboStateForm = Form.useForm(
    comboState.form,
    reactive({
      id: [
        {
          required: true,
          message: t('views.monitor.topologyBuild.comboFormIdPlease'),
        },
      ],
    })
  );

  /**图分组编辑监听更新视图 */
  watch(comboState.form, combo => {
    const info = JSON.parse(JSON.stringify(combo));
    // 新增不监听变化
    const comboOriginId = comboState.origin.id;
    const comboId = info.id;
    if (comboId && comboId === comboOriginId) {
      graphG6.value.clearItemStates(comboId, 'selected');
      const data = graphG6.value.save();
      const item = data.combos.find((item: any) => item.id === comboId);
      Object.assign(item, combo);
      // 无父组id时不要设置，避免导致绘制失败
      if (!combo.parentId) {
        Reflect.deleteProperty(item, 'parentId');
      }
      graphG6.value.read(data);
    }
  });

  /**图分组类型输入限制 */
  function handleComboTypeChange(type: any) {
    // 类型尺寸和边距
    if (type === 'circle') {
      comboState.form.size = 30;
      comboState.form.padding = 30;
    }
    if (type === 'rect') {
      comboState.form.size = [30, 20];
      comboState.form.padding = [10, 20, 10, 20];
    }
  }

  /**图分组新增或更新 */
  function handleOkcombo() {
    return comboStateForm
      .validate()
      .then(e => {
        const combo = JSON.parse(JSON.stringify(comboState.form));
        if (!combo.id) {
          message.warn({
            content: t('views.monitor.topologyBuild.comboFormIdNot'),
            duration: 3,
          });
          return false;
        }

        const item = graphG6.value.findById(combo.id);
        if (item) {
          const data = graphG6.value.save();
          const item = data.combos.find((item: any) => item.id === combo.id);
          Object.assign(item, combo);
          // 无父组id时不要设置，避免导致绘制失败
          if (!combo.parentId) {
            Reflect.deleteProperty(item, 'parentId');
          }
          graphG6.value.read(data);
        } else {
          graphG6.value.createCombo(combo, combo.children);
        }

        comboStateForm.resetFields();
        comboState.origin = {};
        return true;
      })
      .catch(e => {
        message.error(
          t('common.errorFields', { num: e.errorFields.length }),
          3
        );
        return false;
      });
  }

  /**图分组取消还原 */
  function handleCancelcombo() {
    // 新增无原始数据
    const origin = JSON.parse(JSON.stringify(comboState.origin));
    if (origin.id) {
      const data = graphG6.value.save();
      const item = data.combos.find((combo: any) => combo.id === origin.id);
      Object.assign(item, origin);
      graphG6.value.read(data);
    }
    comboStateForm.resetFields();
    comboState.origin = {};
  }

  return {
    comboTypeOptions,
    comboLabelPositionOptions,
    comboState,
    comboStateForm,
    handleComboTypeChange,
    handleOkcombo,
    handleCancelcombo,
  };
}
