import type { ReactNode } from 'react';
import { memo } from 'react';
import { EditableProTable } from '@ant-design/pro-components';
import { useProTableList } from './hook';
import { Tooltip, Popconfirm, Input, Space, Select, Button, Switch } from 'antd';
import { defaultTableRow } from './const';
import style from './index.less';
import { find } from 'lodash';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { FormattedMessage } from 'umi';
interface recordProps {
  /**
   * @description 其他属性
   */
  recordCreatorProps?: any;
  /**
   * @description 需要的options
   */
  tableRow?: any;
  /**
   * @description datasource
   */
  value?: API.DataSourceType[];
  /**
   * @description onChange
   */
  onChange?: (value?: API.DataSourceType[]) => void;
  /**
   * @description operate是否存在 true(默认值)  false
   */
  inOperate?: boolean;
  /**
   *  @description 新增一行是否需要校验 true(默认值)  false
   */
  isRequire?: boolean;
  /**
   * @description key 是否唯一
   */
  isUniqueKey?: boolean;
  /**
   * hiddenOrNotOperate 是否隐藏操作列 【异或，not】选项 默认隐藏
   */
  hiddenOrNotOperate?: boolean;
}
const options = [
  { value: 'and', label: '与' },
  { value: 'xor', label: '异或' },
  { value: 'or', label: '或' },
];
const OperateRender = ({ dataSource, row, onChange }) => {
  // debugger;
  const target = find(dataSource, (item) => {
    return item.id === row.id;
  });

  return (
    <>
      <Select
        defaultValue={target?.relation}
        style={{ minWidth: 100 }}
        dropdownRender={(originNode: ReactNode, props) => {
          return <div className={style.select}>{originNode} </div>;
        }}
        options={options}
        onChange={(val) => {
          dataSource.map((item) => {
            if (item.id === row.id) {
              item.relation = val;
            }
          });
          onChange?.(dataSource);
        }}
      />
      <Switch
        checkedChildren="not"
        defaultChecked={target?.not}
        onChange={(val) => {
          dataSource.map((item) => {
            if (item.id === row.id) {
              item.not = val;
            }
          });
          onChange?.(dataSource);
        }}
      />
    </>
  );
};
const ConditionSelect = ({
  value,
  onChange,
  tableRow = defaultTableRow,
  recordCreatorProps,
  inOperate = true,
  isRequire = true,
  isUniqueKey = false,
  hiddenOrNotOperate = true,
}: recordProps) => {
  const dataSource = value || ([{ id: Date.now() }] as API.DataSourceType[]);
  const { columns } = useProTableList({
    valueEnum: tableRow,
    operatorHidden: inOperate,
    isUniqueKey,
    dataSource,
    hiddenOrNotOperate,
  });
  const handleAdd = () => {
    const newData = {
      id: Date.now(),
    };
    onChange?.([newData, ...dataSource]);
  };
  const isNoEmpty = (val: any) => {
    return val != null && val != undefined && val != ''; //TODO: 不为空
  };
  return (
    <>
      {dataSource?.length > 0 ? (
        <EditableProTable
          controlled
          className={style.table}
          columns={columns}
          rowKey="id"
          value={dataSource}
          onChange={(val: any) => {
            onChange?.(val);
          }}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: Date.now(),
            }),
            style: {
              // width: '50%',
              display: 'none',
            },
            ...recordCreatorProps,
          }}
          editable={{
            type: 'multiple',
            editableKeys: dataSource?.map?.((item) => item.id ?? ''),
            actionRender: (row, config, defaultDoms) => {
              return [
                !hiddenOrNotOperate && (
                  <OperateRender
                    key="OperateRender"
                    dataSource={dataSource}
                    row={row}
                    onChange={onChange}
                  />
                ),
                dataSource?.length <= 1 ? null : (
                  <Popconfirm
                    key={config.index}
                    title={<FormattedMessage id="base.common.delete.confirm" />}
                    onConfirm={() => {
                      onChange?.(dataSource?.filter((item) => item?.id !== row?.id));
                    }}
                  >
                    <MinusCircleOutlined style={{ color: '#F16622' }} />
                  </Popconfirm>
                ),
                config.index == 0 ? (
                  isRequire ? (
                    <Tooltip title={<FormattedMessage id="component.conditionSelect.add.tips" />}>
                      <PlusCircleOutlined
                        style={{ color: '#F16622' }}
                        key={`add${config.index}`}
                        onClick={async (e) => {
                          const operator = inOperate
                            ? isNoEmpty(row.content) &&
                              isNoEmpty(row.key) &&
                              isNoEmpty(row.operator)
                            : isNoEmpty(row.key) && isNoEmpty(row.content);
                          if (operator) {
                            handleAdd();
                            return;
                          }
                        }}
                      />
                    </Tooltip>
                  ) : (
                    <PlusCircleOutlined
                      style={{ color: '#F16622' }}
                      key={`add${config.index}`}
                      onClick={async (e) => {
                        handleAdd();
                        return;
                      }}
                    />
                  )
                ) : null,
              ];
            },
          }}
        />
      ) : null}
    </>
  );
};

export default memo(ConditionSelect);
