import React, { useEffect, useMemo, useState } from 'react';
import { Checkbox, Select, TreeSelect } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { ComponentName, FormItem } from '../../node/judgeNode/mapServe';
import { InputNumberField } from '../../node/fields';
import { connect } from 'umi';

const { Option } = Select;

interface Condition {
  smallValue?: number;
  smallSign?: number;
  bigValue?: number;
  bigSign?: number;
}

export interface JudgeType {
  type: string;
  id: string;
  condition?: Condition;
  values?: any[];
}

export const JudgeOptions = [
  { label: '小于', value: 1 },
  { label: '大于', value: 2 },
  { label: '小于等于', value: 3 },
  { label: '等于', value: 4 },
  { label: '大于等于', value: 5 },
  { label: '介于(两个数之间)', value: 6 },
];
export const SiginOptions = [
  { label: '<', value: 1 },
  { label: '≤', value: 3 },
];
export const SiginSmallOptions = [
  { label: '<', value: 2 },
  { label: '≤', value: 5 },
];

const RenderJudge = (props: any) => {
  const { formItems = '', onChange, depUserTree } = props;
  let formData: FormItem[] = formItems ? JSON.parse(formItems) : [];
  console.log('==========formData================', formData);

  const handleChange = (
    values: any[],
    item: FormItem,
    condition?: Condition,
  ) => {
    const itemCur = formData.find((cur) => cur.props.id == item.props.id);
    let judge: JudgeType = {
      id: item.props.id,
      values:
        values.length == 0 && itemCur && itemCur.judge?.values
          ? itemCur.judge.values
          : values,
      type: item.componentName,
      condition:
        !condition && itemCur && itemCur.judge?.condition
          ? itemCur.judge.condition
          : condition,
    };
    const newItem: FormItem = {
      ...item,
      judge,
    };
    const index = formData.findIndex((cur) => cur.props.id == item.props.id);
    if (index != -1) {
      formData[index] = newItem;
    } else {
      formData.push(newItem);
    }
    onChange(formData);
  };

  const getTreeNode = (pid, dep) => {
    return {
      id: dep.ID,
      pId: pid,
      value: dep.ID,
      title: dep.Name,
      isLeaf: false,
    };
  };
  const getResult = (pid, items) => {
    let result = [];
    items.forEach((item) => {
      let node = getTreeNode(pid, item);
      result.push(node);
      if (item.children) {
        let node = getResult(item.ID, item.children);
        result = [...result, ...node];
      }
    });
    return result;
  };

  const handleDelete = (item: FormItem) => {
    const index = formData.findIndex((cur) => cur.props.id == item.props.id);
    if (index != -1) {
      formData.splice(index, 1);
      onChange(formData);
    }
  };

  const handleTreeChange = (values: (string | number)[], item: FormItem) => {
    const newValues = values.map((cur) => {
      if (typeof cur == 'string' && cur.includes('||')) {
        return { type: 'user', value: Number(cur.split('||')[0]), origin: cur };
      } else {
        return { type: 'dep', value: cur, origin: cur };
      }
    });
    handleChange(newValues, item);
  };

  const RenderComp = (item: FormItem) => {
    let component;
    switch (item.componentName) {
      case ComponentName.Inner:
        component = (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>发起人</div>
              <DeleteOutlined onClick={() => handleDelete(item)} />
            </div>
            <TreeSelect
              showSearch
              multiple
              allowClear
              defaultValue={item.judge?.values?.map((item) => item.origin)}
              style={{ width: '100%' }}
              placeholder="请选择部门"
              treeData={depUserTree}
              onChange={(values) => {
                handleTreeChange(values, item);
                // handleChange(values, item)
              }}
            />
          </>
        );
        break;
      case ComponentName.Depart:
        component = (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>{item.props.label}</div>
              <DeleteOutlined onClick={() => handleDelete(item)} />
            </div>
            {/* <Checkbox.Group
              defaultValue={item.judge?.values}
              onChange={(values: any) => handleChange(values, item)}
            >
              {options.map((cur: any, idx: number) => {
                return (
                  <Checkbox key={`${cur}_${idx}`} value={cur}>
                    {cur}
                  </Checkbox>
                );
              })}
            </Checkbox.Group> */}
          </>
        );
        break;
      case ComponentName.Money:
      case ComponentName.Number:
        const { judge, props } = item;
        component = (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>{props.label}</div>
              <DeleteOutlined onClick={() => handleDelete(item)} />
            </div>
            <Select
              options={JudgeOptions}
              defaultValue={judge?.values[0]}
              onChange={(value: number) => {
                let newCondition: Condition = null;
                if (judge && judge.values && judge.values.length > 0) {
                  if (judge?.values[0] == 6 && value != 6) newCondition = {};
                  else if (judge.values[0] != 6 && value == 6)
                    newCondition = {};
                }
                handleChange([value], item, newCondition);
              }}
            />
            {judge?.values[0] == 6 ? (
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <InputNumberField
                  value={judge?.condition?.smallValue}
                  onChange={(value) => {
                    handleChange([], item, {
                      ...judge?.condition,
                      smallValue: value,
                    });
                  }}
                />
                <Select
                  value={judge?.condition?.smallSign == 2 ? 1 : 3}
                  onChange={(value: number) => {
                    const newValue = Number(value) == 1 ? 2 : 5;
                    handleChange([], item, {
                      ...judge?.condition,
                      smallSign: newValue,
                    });
                  }}
                >
                  {SiginOptions.map((item) => (
                    <Option key={item.value}>{item.label}</Option>
                  ))}
                </Select>
                <span>N</span>
                <Select
                  value={judge?.condition?.bigSign}
                  onChange={(value: number) => {
                    handleChange([], item, {
                      ...judge?.condition,
                      bigSign: Number(value),
                    });
                  }}
                >
                  {SiginOptions.map((item) => (
                    <Option key={item.value}>{item.label}</Option>
                  ))}
                </Select>
                <InputNumberField
                  value={judge?.condition?.bigValue}
                  onChange={(value) => {
                    handleChange([], item, {
                      ...judge?.condition,
                      bigValue: value,
                    });
                  }}
                />
              </div>
            ) : (
              <InputNumberField
                value={judge?.condition?.smallValue}
                onChange={(value) => {
                  handleChange([], item, { smallValue: value });
                }}
              />
            )}
          </>
        );
        break;

      case ComponentName.MultiSelect:
      case ComponentName.Select:
        const options = item.props.options;
        component = (
          <>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <div>{item.props.label}</div>
              <DeleteOutlined onClick={() => handleDelete(item)} />
            </div>
            <Checkbox.Group
              defaultValue={item.judge?.values}
              onChange={(values: any) => handleChange(values, item)}
            >
              {options.map((cur: any, idx: number) => {
                return (
                  <Checkbox key={`${cur}_${idx}`} value={cur}>
                    {cur}
                  </Checkbox>
                );
              })}
            </Checkbox.Group>
          </>
        );
        break;
    }
    return component;
  };

  return <>{formData.map((item) => RenderComp(item))}</>;
};

export default connect(({ user }) => ({ depUserTree: user.depUserTree }))(
  RenderJudge,
);
