import React, { useState, useEffect } from 'react';
import { FlowchartFormWrapper, MODELS, useXFlowApp } from '@antv/xflow';
import { Button, message, Select } from 'antd';
import LuckyExcel from 'luckyexcel';
import {
  Position,
  Size,
  ColorPicker,
  InputNumberFiled,
  InputFiled,
  UploadFiled,
  RadioField,
} from '../fields';
import { PREFIX } from '../constants';
import { UnityAction } from '@/utils/utils';
import { connect } from 'dva';
import { IProps } from '@/components/Flow/index';

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

export interface IConfig {
  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;
}

const defaultConfig: IConfig = {
  muti_version: 1,
  is_start_node: 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);
  };

  const beforeUpload = (file: any) => {
    try {
      LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
          message.error('读取xlsx文件失败!');
          return;
        }
        console.log(exportJson);
        // const sheet = exportJson.sheets[0];
        let cell = [];
        exportJson.sheets.forEach(sheet => {
          let titleCell = [];
          sheet.celldata.forEach(item => {
            if (item.r == 0) {
              // 标题头
              titleCell.push(item);
            }
            // 生成cid
            item.v.cid = `${item.r}-${item.c}`;
          });
          let tempCell = titleCell.map(item => {
            let value = '';
            if (item.v?.v) {
              value = item.v?.v;
            } else if (item.v.ct?.s && item.v.ct?.s instanceof Array) {
              value = item.v.ct.s.map(item => item?.v).join?.('');
            }
            return { sheet_name: sheet.name, col_idx: item.r, col_axis: item.c, col_value: value };
          });
          cell = [...cell, ...tempCell];
        });
        console.log(cell);
        onNodeConfigChange(null, {
          data: exportJson.sheets,
          excel_info: {
            file_name: file.name,
            excel_cols: cell,
          },
        });
      });
    } catch (error) {
      message.error('excel文件导入失败！请联系管理员。');
      return false;
    }
  };

  useEffect(() => {
    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>
        <InputFiled
          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 },
          ]}
        />
        {nodeConfig.is_start_node == 1 && (
          <>
            <InputFiled
              label="模板名称"
              value={nodeConfig.version_name}
              onChange={value => {
                onNodeConfigChange('version_name', value);
              }}
            />

            <UploadFiled
              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);
            }}
          />
          <InputNumberFiled
            label="消息数量"
            value={nodeConfig.count}
            onChange={value => {
              onNodeConfigChange('count', value);
            }}
          />
          <div style={{ display: 'flex' }}>
            <InputNumberFiled
              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);
