import React, { useState, useEffect } from 'react';
import { FlowchartFormWrapper, MODELS, useXFlowApp } from '@antv/xflow';
import { Button, message, Select } from 'antd';
import {
  Position,
  Size,
  ColorPicker,
  InputNumberField,
  InputField,
  UploadField,
  RadioField,
} from '../fields';
import { PREFIX } from '../constants';
import { UnityAction } from '@/utils/utils';
import { connect } from "umi";
import { IProps } from '@/components/Flow/index';

interface ExcelInfo {
  file_name?: string;
  excel_cols?: any;
}

export interface IConfig {
  id?: string;
  label?: string;
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  fontSize?: number;
  count?: number;
  fontFill?: string;
  fill?: string;
  stroke?: string;
  muti_version?: string | number;
  is_start_node?: string | number;
  bom_template?: string;
  version_name?: string;
  data?: any;
  excel_info?: ExcelInfo;
  role_list?: string;
  is_seal?: string | number;
}

const defaultConfig: IConfig = {
  muti_version: 1,
  is_start_node: 0,
  is_seal: 0,
  excel_info: { file_name: '' },
};

const Component = (props: any) => {
  const { config, plugin = {}, roleList } = props;
  const { updateNode } = plugin;
  const [options, setOptions] = useState([]);
  const [fileName, setFileName] = useState('');
  const [nodeConfig, setNodeConfig] = useState<IConfig>({
    ...defaultConfig,
    ...config,
  });

  const app = useXFlowApp();
  const [meta, setMeta] = useState<IProps['meta']>(null);
  const onNodeConfigChange = (key: string, value: number | string | object) => {
    if (key) {
      setNodeConfig({
        ...nodeConfig,
        [key]: value,
      });
      updateNode({
        [key]: value,
      });
    } else if (value instanceof Object) {
      setNodeConfig({
        ...nodeConfig,
        ...value,
      });
      updateNode({
        ...value,
      });
    }
  };

  const onSave = () => {
    UnityAction.emit('NODE_SAVE', nodeConfig);
  };

  useEffect(() => {
    if(config.id != nodeConfig.id) {
      setNodeConfig({
        ...defaultConfig,
        ...config,
      });
    }
  }, [config]);

  useEffect(() => {
    MODELS.GRAPH_META.useValue(app.modelService).then((meta: IProps['meta']) => {
      setMeta(meta);
    });
  }, []);

  const updataFileName = (name: string) => {
    var idx = name?.lastIndexOf('/');
    let str = name.substring(idx + 1, name.length);
    setFileName(str);
    onNodeConfigChange('version_name', str);
  };

  useEffect(() => {
    if (config.bom_template) updataFileName(config.bom_template);
    if (nodeConfig.excel_info?.file_name) updataFileName(nodeConfig.excel_info.file_name);
  }, [nodeConfig.bom_template, nodeConfig.excel_info.file_name]);
  // console.log(nodeConfig, config)

  useEffect(() => {
    if (!roleList || roleList.length <= 0) return;
    let op = [];
    console.log(roleList);
    roleList
      .filter(cur => cur.RoleType == 4)
      .forEach(item => {
        op.push({ label: `${item.Name}(${item.ID})`, value: item.ID });
      });
    setOptions(op);
    console.log(op);
  }, [roleList]);

  // const handleFileNameClick = () => {
  //   if (nodeConfig.bom_template) window.open(nodeConfig.bom_template);
  // };

  return (
    <div className={`${PREFIX}-panel-body`}>
      <div className={`${PREFIX}-panel-group`}>
        <h5>内容</h5>
        <InputField
          label="标题"
          value={nodeConfig.label}
          disabled={meta?.editMode == 2}
          onChange={value => {
            onNodeConfigChange('label', value);
          }}
        />
      </div>
      <div className={`${PREFIX}-panel-group`}>
        <h5>数据</h5>
        <RadioField
          label="多个版本"
          value={nodeConfig.muti_version}
          onChange={value => {
            onNodeConfigChange('muti_version', value);
          }}
          options={[
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ]}
        />
        <RadioField
          label="起始起点"
          value={nodeConfig.is_start_node}
          onChange={value => {
            onNodeConfigChange('is_start_node', value);
          }}
          options={[
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ]}
        />
        <RadioField
          label="是否用印"
          value={nodeConfig.is_seal}
          onChange={value => {
            onNodeConfigChange('is_seal', value);
          }}
          options={[
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ]}
        />
        {nodeConfig.is_start_node == 1 && (
          <>
            <InputField
              label="模板名称"
              value={nodeConfig.version_name}
              onChange={value => {
                onNodeConfigChange('version_name', value);
              }}
            />

            {/* <UploadField
              label="模板"
              onChange={url => onNodeConfigChange('bom_template', url)}
              beforeUpload={beforeUpload}
            /> */}

            {/* <div onClick={handleFileNameClick}>{fileName}</div> */}
            <a href={nodeConfig.bom_template}>{fileName}</a>
          </>
        )}
        <div className="group">
          <label>权限</label>
          <Select
            value={
              nodeConfig.role_list ? nodeConfig.role_list.split(',').map(item => Number(item)) : []
            }
            mode="multiple"
            allowClear
            style={{ width: '100%' }}
            placeholder="选择权限"
            onChange={(v: number[]) => {
              onNodeConfigChange('role_list', v.join(','));
            }}
            disabled={meta?.editMode == 2}
            options={options}
          />
        </div>
      </div>
      {meta?.editMode != 2 && (
        <div className={`${PREFIX}-panel-group`}>
          <h5>样式</h5>
          <Position
            x={nodeConfig.x}
            y={nodeConfig.y}
            onChange={(key, value) => {
              onNodeConfigChange(key, value);
            }}
          />
          <Size
            width={nodeConfig.width}
            height={nodeConfig.height}
            onChange={(key, value) => {
              onNodeConfigChange(key, value);
            }}
          />
          <ColorPicker
            label="填充"
            value={nodeConfig.fill}
            onChange={(value: string) => {
              onNodeConfigChange('fill', value);
            }}
          />
          <ColorPicker
            label="边框"
            value={nodeConfig.stroke}
            onChange={(value: string) => {
              onNodeConfigChange('stroke', value);
            }}
          />
          <InputNumberField
            label="消息数量"
            value={nodeConfig.count}
            onChange={value => {
              onNodeConfigChange('count', value);
            }}
          />
          <div style={{ display: 'flex' }}>
            <InputNumberField
              label="字号"
              value={nodeConfig.fontSize}
              width={68}
              onChange={value => {
                onNodeConfigChange('fontSize', value);
              }}
              style={{ marginRight: 10 }}
            />
            <ColorPicker
              value={nodeConfig.fontFill}
              onChange={(value: string) => {
                onNodeConfigChange('fontFill', value);
              }}
            />
          </div>
        </div>
      )}
      <Button type="primary" onClick={onSave}>
        保存
      </Button>
    </div>
  );
};

function RecthServe(props: any) {
  return (
    <FlowchartFormWrapper {...props}>
      {(config, plugin) => <Component {...props} plugin={plugin} config={config} />}
    </FlowchartFormWrapper>
  );
}

export default connect(({ user }) => ({ roleList: user.roleList }))(RecthServe);
