import React from 'react';
import { Input, Select, NumberPicker } from '@cainiaofe/cn-ui';
import './index.scss';
import {
  compileTextExpr2,
  __ds__,
  __record__,
  __urlParams__,
  getDataSourceList,
  handleI18nLabel,
} from '../../util/util';

const symbolList = ['>=', '<=', '>', '<', '!==', '!=', '===', '==', '='];
const symbolList2 = ['==', '!=', '>', '<', '>=', '<='];
const typeList = [
  {
    label: '文本',
    value: 'string',
  },
  {
    label: '数字',
    value: 'number',
  },
  {
    label: '布尔',
    value: 'boolean',
  },
];

export default class TextExprSetter extends React.Component {
  static displayName = 'TextExprSetter';
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      visible: false,
      type: 'string',
    };
  }

  componentDidMount() {
    const { field, dataKey, labelKey, valueKey, value, onChange } = this.props;
    let result = [];
    if (field && dataKey && labelKey && valueKey) {
      result = this.getList();
    }
    let state;
    if (result?.length > 0) {
      state = {
        list: result,
      };
    }

    const exprObj = compileTextExpr2(value, this.state.type) || {};
    const { type } = exprObj;
    if (type) {
      state.type = type;
    }

    if (!exprObj.attr) {
      onChange('');
    }
    this.setState(state);
  }

  getList = () => {
    const { field, dataKey, labelKey, valueKey, groupName, configList } =
      this.props;
    const originList = field?.getNode?.()?.getPropValue?.(dataKey);
    let result = [];
    const newList = [];

    if (Array.isArray(configList) && configList.length > 0) {
      configList.forEach((item) => {
        if (groupName) {
          if (item?.dataKey === 'arrayTable') {
            const path = field?.path;
            if (Array.isArray(path) && path.length > 3) {
              const arrayTableIndex = path[1];
              if (arrayTableIndex !== undefined) {
                const formConfig = field?.getNode?.()?.getPropValue?.('config');
                const arrayTableConfig = formConfig?.[arrayTableIndex] || {};
                if (
                  arrayTableConfig?.componentName === 'CnArrayTable' &&
                  arrayTableConfig?.options?.config?.length > 0
                ) {
                  const tempList = arrayTableConfig?.options?.config;
                  result.push({
                    label: item?.groupName,
                    children: tempList.map((item2) => {
                      return {
                        label: handleI18nLabel(item2[item?.labelKey]),
                        value: `${item2[item?.valueKey]}`,
                      };
                    }),
                  });
                }
              }
            }
          }
        }
      });
    }

    if (originList?.length > 0) {
      originList.forEach((item) => {
        const label = handleI18nLabel(item[labelKey]);
        const value = item[valueKey];
        if (label && value) {
          newList.push({
            label,
            value: `${__record__}.${value}`,
          });
        }
      });
    }
    if (newList?.length > 0) {
      if (groupName) {
        result.push({
          label: groupName,
          children: newList,
        });
      } else {
        result = [...newList];
      }
    }
    const extra = {
      label: '其他数据',
      children: [
        {
          label: 'url参数',
          value: __urlParams__,
        },
      ],
    };

    const dsList = getDataSourceList({ typeList: ['VALUE'] });
    if (dsList.length > 0) {
      dsList.forEach((item) => {
        if (item) {
          const { label, value } = item;
          extra.children.push({
            label,
            value: __ds__ + value + __ds__,
          });
        }
      });
    }
    result.push(extra);
    return result;
  };

  isDataSource = (str) => {
    if (str) {
      return str === __urlParams__ || str?.startsWith(__ds__);
    }
  };

  transTextExprToStr = (textExpr) => {
    let result = '';
    const { attr, value, type, symbol, urlParamsKey } = textExpr || {};
    if (attr) {
      result += attr;
      if (this.isDataSource(attr) && urlParamsKey) {
        result += `.${urlParamsKey}`;
      }
    }
    if (symbol) {
      result += symbol;
    }
    if (value || value === 0 || value === false) {
      // if(type === 'string') {
      //   result += `"${value}"`;
      // }else{
      result += value;
      // }
    }
    return result;
  };

  getValueEditor = (type, value, exprObj) => {
    const { size = 'small' } = this.props;
    const props = {
      size,
      className: 'ctes-input',
      value,
      onChange: this.changeValue.bind(this, exprObj, 'value'),
    };
    switch (type) {
      case 'number':
        return <NumberPicker {...props} />;
      case 'boolean':
        return (
          <Select
            hasClear
            dataSource={[
              { label: 'true', value: true },
              { label: 'false', value: false },
            ]}
            {...props}
          />
        );
      default:
        return <Input placeholder={'空'} {...props} />;
    }
  };

  changeValue = (exprObj = {}, key, value) => {
    const { type } = this.state;
    const { onChange } = this.props;
    const newExprObj = { ...exprObj };
    if (type === 'string' && key === 'value') {
      newExprObj[key] = `"${value}"`;
    } else {
      newExprObj[key] = value;
    }
    if (key === 'symbol') {
      // if(exprObj === undefined) {
      //   newExprObj.value = '';
      // }
    }
    if (key === 'attr') {
      newExprObj.urlParamsKey = undefined;
    }
    const str = this.transTextExprToStr(newExprObj);
    onChange && onChange(str);
  };

  render() {
    const { list, type } = this.state;
    let { value, onChange, size = 'small', groupName } = this.props;
    if (!value) {
      value = '';
    }
    const exprObj = compileTextExpr2(value, type) || {};
    const { attr, value: v, symbol, urlParamsKey } = exprObj;
    const symbolDom = (
      <Select
        value={symbol || ''}
        hasClear
        size={size}
        className={'ctes-input ctes-symbol-input'}
        dataSource={symbolList2}
        onChange={this.changeValue.bind(this, exprObj, 'symbol')}
      />
    );
    const isDs = this.isDataSource(attr);
    return (
      <div className='cn-text-expr-setter-wrap'>
        <div className='ctes-first-line'>
          <Select
            placeholder={groupName || '筛选项'}
            hasClear
            value={attr || ''}
            autoWidth={false}
            size={size}
            className={'ctes-input'}
            dataSource={list}
            onChange={this.changeValue.bind(this, exprObj, 'attr')}
          />
          {isDs && (
            <Input
              placeholder={'属性名'}
              value={urlParamsKey || ''}
              onChange={this.changeValue.bind(this, exprObj, 'urlParamsKey')}
              size={size}
              className={'ctes-input'}
            />
          )}
          {!isDs && (
            <Select
              placeholder={'满足'}
              hasClear
              value={symbol || ''}
              size={size}
              className={'ctes-input ctes-symbol-input'}
              dataSource={symbolList2}
              onChange={this.changeValue.bind(this, exprObj, 'symbol')}
            />
          )}
        </div>
        <div className='ctes-second-line'>
          {isDs && symbolDom}
          <Select
            value={type}
            size={size}
            className={'ctes-input'}
            dataSource={typeList}
            onChange={(v) => {
              this.setState(
                {
                  type: v,
                },
                () => {
                  this.changeValue(exprObj, 'value', true);
                },
              );
            }}
          />
          {this.getValueEditor(type, v, exprObj)}
        </div>
      </div>
    );
  }
}
