import * as React from 'react';
import { useState, useEffect, ErrorInfo, useMemo, Component,Popconfirm } from 'react';
import { Radio, Select, Box, Input } from '@alifd/next';
import { SettingTarget, CustomView } from '@alilc/lowcode-types';
import { event, project } from '@alilc/lowcode-engine';
import './index.scss';

import { BehaviorAction } from './types';
import { linkBehaviorAction } from './actions/link-action';
import { dialogBehaviorAction } from './actions/dialog-action';
import { messageBehaviorAction } from './actions/message-action';
import { tooltipBehaviorAction } from './actions/tooltip-action';

interface BehaviorSetterProps {
  field?: SettingTarget;
  // 兼容 vision engine
  defaultValue: string;
  prop?: SettingTarget;
  onChange: Function;
  actions: string[];
  value: string;
  type: string;
  url?: 'string';
  responseFormatter?: Function;
  extraBehaviorActions?: BehaviorAction[];
  extendedOptions?: Record<string, any>;
  enableMessageAction?: boolean;
  enableTooltipAction?: boolean;
}

const defaultActionMap = {
  dialog: dialogBehaviorAction,
  link: linkBehaviorAction,
  tooltip: tooltipBehaviorAction,
  message: messageBehaviorAction,
};
/**
 * 获取数据源面板中的数据
 * @param  {String}
 * @return {Array}
 */
const getDataSource = (): any[] => {
  const schema = project.exportSchema();
  const stateMap = schema.componentsTree[0]?.dataSource;
  const list = stateMap?.list || [];
  const dataSource = [];

  for (const item of list) {
    if (item && item.id) {
      dataSource.push(`this.state.${item.id}`);
    }
  }

  return dataSource;
};
 
const getParms = (field) => {
  let propsFieldparent = field?.parent || {};
  let columns = propsFieldparent.parent.parent.getPropValue('columns');

  const parms = columns.map((v) => ({
    label: `${v.columnName}/${v.fieldName}`,
    value: v.columnName,
  }));

  return parms;
};
  /**
   * 获取AutoComplete数据源
   * @param  {String}
   * @return {Array}
   */
   const getVarableList = (): any[] =>{
    const schema = project.exportSchema();

    const stateMap = schema.componentsTree[0]?.state;
    const dataSource = [];
    for (const key in stateMap) {
      if (Object.prototype.hasOwnProperty.call(stateMap, key) && key) {
        dataSource.push(key);
      }
    }

    return dataSource;
  }
const getbtnType = (field) => {
  let propsFieldparent = field?.parent || {};
  let btnType = propsFieldparent.getPropValue('btnType');

  return btnType;
};

const getDialogList = (field: SettingTarget) => {
  const node = (field as any).getNode();
  const nodeDocument = node.document || node.page;
  let nodeList = nodeDocument?.modalNodesManager?.getModalNodes?.();
  if (!nodeList || !nodeList.length) {
    nodeDocument?.modalNodesManager?.setNodes?.();
    nodeList = nodeDocument?.modalNodesManager?.getModalNodes?.();
  }
  console.log('nodelist', nodeList);
  nodeList.map((v) => {
    console.log('nodelist--v', v.propsData);
  });
  return (nodeList || [])
    .filter((x: any) => x && x.propsData)
    .map((x: any) => ({
      label:
        x.propsData && x.propsData.title
          ? `${x.propsData.title}(${x.id})`
          : `${x.id}(${x.componentName})`,
      value: x.propsData.ref,
    }));
};

const BehaviorSetter = ({
  onChange,
  field: propsField,
  prop,
  actions,
  value,
  type,
  extraBehaviorActions: propsBehaviorActions = [],
  extendedOptions = {},
  url,
  responseFormatter,
  enableMessageAction,
  enableTooltipAction,
}: BehaviorSetterProps) => {
  const field = propsField || prop;
  const [actionType, setActionType] = useState(0);
  const [jumpType, setJumpType] = useState(0);
  const [jumpPageType, setJumpPageType] = useState(0);
  const [pageurl, setPageurl] = useState('');
  const pageList: Array = [];
  const [dialogId, setDialogId] = useState('');
  const [dialogList, setDialogList] = useState([]);
  const [firstLoad, setFirstLoad] = useState(true);
  const [dataSource, setDataSource] = useState('');
  const [parms, setParms] = useState([]);
  const [commitTxt, setCommitTxt] = useState('');
  const [pageData, setPageData] = useState([])
  let btnType = field?.parent.getPropValue('btnType');
  useEffect(() => {
    setDialogList(getDialogList(field));
  }, [field]);
  useEffect(() => {
    if (value) {
      setActionType(value.actionType);
      setJumpType(value.jumpType);
      setJumpPageType(value.jumpPageType);
      setPageurl(value.pageurl);
      setDialogId(value.dialogId);
      setDataSource(value.dataSource);
      setParms(value.parms);
      setCommitTxt(value.commitTxt);
      setPageData(value.pageData)
    }
  }, []);

  useEffect(() => {
    onChange({
      actionType,
      jumpType,
      jumpPageType,
      pageurl,
      dialogId,
      dataSource,
      parms,
      commitTxt,
      pageData
    });
  }, [actionType, jumpType, jumpPageType, pageurl, dialogId, dataSource, parms, commitTxt,pageData]);
  return (
    <div>
      {(btnType === 1 || btnType === 5 || btnType === 8) && (
        <div>
          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>展示样式</Box>
            <Box className="behavior-radio">
              <Radio.Group
                size="small"
                dataSource={[
                  {
                    label: '弹窗',
                    value: 0,
                  },
                  {
                    label: '链接',
                    value: 1,
                  },
                ]}
                value={actionType}
                shape="button"
                onChange={(value) => setActionType(value as any)}
              />
            </Box>
          </Box>
          {actionType === 1 && (
            <div>
              <Box direction="row" align="center" className="behavior-item">
                <Box style={{ width: 70 }}>跳转方式</Box>
                <Box className="behavior-radio">
                  <Radio.Group
                    size="small"
                    dataSource={[
                      {
                        label: '当前窗口打开',
                        value: 0,
                      },
                      {
                        label: '新窗口打开',
                        value: 1,
                      },
                    ]}
                    value={jumpType}
                    shape="button"
                    onChange={(value) => setJumpType(value as any)}
                  />
                </Box>
              </Box>{' '}
            </div>
          )}
          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>关联内容</Box>
            <Box className="behavior-radio">
              <Radio.Group
                size="small"
                dataSource={[
                  {
                    label: '关联页面',
                    value: 0,
                  },
                  {
                    label: '自定义页面',
                    value: 1,
                  },
                ]}
                value={jumpPageType}
                shape="button"
                onChange={(value) => setJumpPageType(value as any)}
              />
            </Box>
          </Box>
          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>{jumpPageType === 1 ? '自定义页面' : '关联页面'}</Box>
            <Box className="behavior-radio">
              {jumpPageType === 1 ? (
                <Input
                  size="small"
                  hasClear
                  placeholder="请输入链接"
                  value={pageurl}
                  onChange={(value) => setPageurl(value)}
                />
              ) : (
                <Select
                  size="small"
                  hasClear
                  showSearch
                  dataSource={pageList}
                  value={pageurl}
                  onChange={(value) => setPageurl(value)}
                />
              )}
            </Box>
          </Box>

          {actionType === 0 && (
            <Box direction="row" align="center" className="behavior-item">
              <Box style={{ width: 70 }}>绑定弹窗</Box>
              <Box className="behavior-radio">
                <Select
                  size="small"
                  hasClear
                  value={dialogId}
                  onChange={(val) => setDialogId(val)}
                  dataSource={dialogList}
                  style={{ width: '100%', marginRight: 8 }}
                />
              </Box>
            </Box>
          )}
        </div>
      )}

      {(btnType === 1 ||
        btnType === 2 ||
        btnType === 3 ||
        btnType === 4 ||
        btnType === 9 ||
        btnType === 10) && (
        <div>
          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>绑定数据源</Box>
            <Box className="behavior-radio">
              <Select
                size="small"
                hasClear
                value={dataSource}
                onChange={(val) => setDataSource(val)}
                dataSource={getDataSource()}
                style={{ width: '100%', marginRight: 8 }}
              />
            </Box>
          </Box>

          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>选择参数</Box>
            <Box className="behavior-radio">
              <Select
                size="small"
                mode="multiple"
                hasClear
                value={parms}
                onChange={(val) => setParms(val)}
                dataSource={getParms(field)}
                style={{ width: '100%', marginRight: 8 }}
              />
            </Box>
          </Box>
        </div>
      )}
      {(btnType === 2 || btnType === 3) && (
        <Box direction="row" align="center" className="behavior-item">
          <Box style={{ width: 70 }}>二次确认提示文案</Box>
          <Box className="behavior-radio">
            <Input
              size="small"
              hasClear
              placeholder="请输入"
              value={commitTxt}
              onChange={(value) => setCommitTxt(value)}
            />
          </Box>
        </Box>
      )}
          <Box direction="row" align="center" className="behavior-item">
            <Box style={{ width: 70 }}>page参数</Box>
            <Box className="behavior-radio">
              <Select
                size="small"
                multiple
                hasClear
                value={pageData}
                onChange={(val) => setPageData(val)}
                dataSource={getVarableList()}
                style={{ width: '100%', marginRight: 8 }}
              />
            </Box>
          </Box>
    </div>
  );
};

BehaviorSetter.defaultProps = {
  value: undefined,
  type: 'string',
  defaultValue: '',
  hasClear: false,
  placeholder: '请点击选择 Icon',
  onChange: () => undefined,
};

export default class extends Component<BehaviorSetterProps> {
  render() {
    return <BehaviorSetter {...this.props} />;
  }
}
