import React, { useState, useEffect } from 'react';
import { Form, Input, Row, Col, Descriptions, Select, AutoComplete, Button, Divider } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';

import { highlightSearchContentByTerms, generateUUID } from '../../../../util';
import { dispatch, dispatchLatest } from '../../../../model'; 

import DebounceInput from './DebounceInput';

import './ImportActionHeader.less';

const { TextArea } = Input;
const { Option } = Select;

const InputDebounce = DebounceInput(300)(Input);

const loadOptions = ['append', 'refresh', 'insert', 'update', 'full', 'chain', 'delete', '手工导入'];
const updateOptions = [
  '每个交易日早间交易前加载上一交易日数据,历史资料入历史表',
  '每个交易日早间交易前清空该表,交易期间实时加载,下午收市后入历史表',
  '每个交易日7:30加载',
  '每个交易日8:30加载',
  '每个交易日15:00加载',
  '每个交易日18:00加载',
  '每个交易日19:00加载',
  '每个交易日19:30加载',
  '每个交易日20:00加载',
  '每个交易日22:00加载',
  '每个交易日23:00加载',
  '每个交易日20:00加载T-2的数据',
  '每日中午12:00加载T-3日数据',
  '实时更新',
  '收盘后加载',
  '收市后加载',
  '下午收市后加载',
  '下午收市后入历史表',
  '下午收市后入实时和历史表',
  '晚间结算后加载',
  '实时从mysql同步',
  '手工维护',
  '用户提交',
  '作业提交',
  '脚本加载',
];

const ConstraintSelect = ({ value = {}, constraints = [], onChange, ...restProps }) => {

  return (
    <Select 
      onChange={onChange} 
      value={value?.name || ''} 
      placeholder='请选择规范'
      {...restProps}
    >
    {
      (constraints||[]) && constraints.map((constraint, index) => {
        return (
          <Option key={index} value={constraint.name||''} >{constraint.cnName||''}</Option>
        );
      })
    }
    </Select>
  )
}

// const TemplateSelect = ({ value = {}, templates = [], onChange, ...restProps }) => {

//   return (
//     <Select 
//       onChange={onChange} 
//       value={value?.name || ''} 
//       placeholder='请选择生成表类型'
//       allowClear
//       {...restProps}
//     >
//     {
//       (templates||[]) && templates.map((template, index) => {
//         return (
//           <Option key={index} value={template.name||''} >{template.cnName||''}</Option>
//         );
//       })
//     }
//     </Select>
//   )
// }

const AttributesSelect = ({ value = [], modelerData, onChange, mode = 'multiple', ...restProps }) => {

  const onAttributeChange = (value) => {
    let currentAttributes = [];
    if (mode === 'multiple') {
      currentAttributes = (modelerData?.easyDataModelerDataModelAttributes||[]).filter(attribute => (value||[]).indexOf(attribute.iid)!==-1);
    } else {
      (value||[]).forEach(item => {

        const filterAttributes = (newAttributes||[]).filter(attribute => item ===attribute.iid);

        if (filterAttributes.length !== 0) {
          currentAttributes = [...currentAttributes, ...filterAttributes];
        } else {
          currentAttributes = [...currentAttributes, { name: item, iid: generateUUID() }];
        }
      })
    }

    triggerChange(currentAttributes);
  }

  const triggerChange = (changedValue) => {
    onChange?.(changedValue);
  };

    //value有可能为空
    value = value ? value: [];
  
    let attributeIds = [];
    let newAttributes = [...(modelerData?.easyDataModelerDataModelAttributes||[])];
  
    value.forEach(attribute => {
      attributeIds.push(attribute.iid);
  
      if (mode === 'tags') {
        const filterAttributes = (modelerData?.easyDataModelerDataModelAttributes||[]).filter(_attribute => attribute.iid ===_attribute.iid);
  
        if (filterAttributes.length === 0) {
          newAttributes = [...newAttributes, attribute];
        } 
      }
    })

  return (
    <Select 
      onChange={(value) => { onAttributeChange && onAttributeChange(value) }} 
      value={attributeIds} 
      placeholder='请选择字段名称'
      mode={mode}
      allowClear={true}
    >
    {
      (newAttributes||[]).map((attribute, index) => {
        return (
          <Option key={index} value={attribute.iid?attribute.iid:(attribute.name||'')}>{attribute.name||''}</Option>
        );
      })
    }
    </Select>
  );
}

const PartitionSelect = ({ value = {}, modelerData, partitionTypes = [], onChange, ...restProps }) => {

  const onPartitionTypeChange = (value) => {

    let currentPartitionType = {}; 
    (partitionTypes||[]).forEach((partitionType, index) => {
      if (value === partitionType.name) {
        currentPartitionType = partitionType;
      }
    })

    triggerChange({ partitionType: currentPartitionType });
  }

  const onAttributeChange = (value) => {
    const currentAttributes = (modelerData?.easyDataModelerDataModelAttributes||[]).filter(attribute => (value||[]).indexOf(attribute.iid)!==-1);

    triggerChange({ keys: currentAttributes });
  }

  const triggerChange = (changedValue) => {
    onChange?.({
      ...value,
      ...changedValue,
    });
  };

  //value有可能为空
  value = value ? value: {};
  
  let attributeIds = [];
  (value?.keys||[]).forEach(attribute => {
    attributeIds.push(attribute.iid);
  })

  return (
    <Row gutter={10}>
      <Col span={8}>
      <Select 
        onChange={onPartitionTypeChange} 
        value={value?.partitionType?.name || ''} 
        placeholder='请选择分区类型'
        allowClear={true}
      >
      {
        (partitionTypes||[]).map((partitionType, index) => {
          return (
            <Option key={partitionType.name||''}>{partitionType.cnName||''}</Option>
          );
        })
      }
      </Select>
      </Col>
      <Col span={16}>
        <Select 
          onChange={(value) => { onAttributeChange && onAttributeChange(value) }} 
          value={attributeIds} 
          placeholder='请选择字段名称'
          mode='multiple'
          allowClear={true}
        >
        {
          (modelerData?.easyDataModelerDataModelAttributes||[]).map((attribute, index) => {
            return (
              <Option key={index} value={attribute.iid||''}>{attribute.name||''}</Option>
            );
          })
        }
        </Select>
      </Col>
    </Row>
  );
}

const LoadSelect = ({ value = '', onChange, ...restProps }) => {

  const onLoadChange = (value) => {

    triggerChange(value.join('/'));
  }

  const triggerChange = (changedValue) => {
    onChange?.(changedValue);
  };

  //value有可能为空
  value = value ? value: '';
  
  let loadNames = [];

  if (value !== '') {
    value.split('/').forEach(item => {
      loadNames.push(item);
    })
  }

  return (
    <Select 
      mode="tags" 
      tokenSeparators={['/', ' ']}
      onChange={(value) => { onLoadChange && onLoadChange(value) }} 
      value={loadNames} 
      placeholder='请选择选择或者手动输入加载方式'
      allowClear={true}
    >
    {
      loadOptions.map((item, index) => {
        return (
          <Option key={index} value={item}>{item}</Option>
        );
      })
    }
    </Select>
  );
}

const UpdateSelect = ({ value = '', onChange, ...restProps }) => {

  const onUpdateChange = (value) => {

    triggerChange(value.join('/'));
  }

  const triggerChange = (changedValue) => {
    onChange?.(changedValue);
  };

  //value有可能为空
  value = value ? value: '';
  
  let updateNames = [];
  if (value !== '') {
    value.split('/').forEach(item => {
      updateNames.push(item);
    })
  }

  return (
    <Select 
      mode="tags" 
      tokenSeparators={['/', ' ']}
      onChange={(value) => { onUpdateChange && onUpdateChange(value) }} 
      value={updateNames} 
      placeholder='请选择选择或者手动输入更新时间'
      allowClear={true}
    >
    {
      updateOptions.map((item, index) => {
        return (
          <Option key={index} value={item}>{item}</Option>
        );
      })
    }
    </Select>
  );
}

const ImportActionHeader = (props) => {
  const { editable, form, modelerData, constraints, templates, onConstraintChange, onTemplateChange, validateReports, onChange, terms, supportedPartitionTypes } = props;

  const [ causes, setCauses ] = useState([]);
  const [ options, setOptions ] = useState([]);

  const [ autoTranslate, setAutoTranslate ] = useState(false);
  const [ onlyShowRequireChange, setOnlyShowRequireChange ] = useState(true);
  const [ maintenanceRecords, setMaintenanceRecords ] = useState(null);

  useEffect(() => {

    const causes = [];
    (validateReports||[]).forEach(report => {
    
      if (report.type === 'DataModel') {
        (report.reportItems||[]).forEach((item) => {
          causes.push(item.cause||'');
        })
      }
    });

    if (editable) {
      form?.setFields([{ name: 'name', errors: causes }]);
    } else {
      setCauses(causes);
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [validateReports])

  useEffect(() => {

    setAutoTranslate((modelerData.name||'')==='');
    if (modelerData) {
      form?.setFieldsValue(modelerData);

      if ((modelerData.id||'')!=='' && maintenanceRecords===null) {
        getMaintenanceRecords();
      }
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [modelerData])

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };

  const getMaintenanceRecords = () => {
    dispatch({
      type: 'datamodel.getMaintenanceRecords',
      payload: {
        params: {
          id: modelerData.id
        }
      },
      callback: data => {
        setMaintenanceRecords(data);
      }
    })
  }

  const onSearch = (searchText) => {

    const _searchText = searchText.replace(/ /g,'');
    if (_searchText !== '') {
      dispatchLatest({
        type: 'datamodel.autocomplete',
        payload: {
          params: {
            word: _searchText,
            isEasyDataModelerDataModelAttribute: false,
          }
        },
        callback: data => {
          const _options = [];
          (data||[]).forEach(item => {
            _options.push({ value: item });
          })

          setOptions(_options);
        }
      })
    } else {
      dispatchLatest({
        type: 'datamodel.recommandEnglishWords',
        payload: {
          params: {
            chineseWord: modelerData.cnName,
          }
        },
        callback: data => {
          const _options = [];
          (data||[]).forEach(item => {
            _options.push({ value: item });
          })

          setOptions(_options);
        }
      })
    }
  }

  const onValuesChange = (changedValues, allValues) => {

    onChange && onChange(changedValues, allValues);

    //有手动编辑过英文名称并且有内容的情况下, 不能通过编辑中文名称自动翻译
    if (changedValues.hasOwnProperty('name')) {
      setAutoTranslate(changedValues.name==='');
    } else if (changedValues.hasOwnProperty('cnName')) {
      if (autoTranslate) {
        dispatchLatest({
          type: 'datamodel.translatePhase',
          payload: {
            params: {
              phaseInChinese: changedValues.cnName,
            }
          },
          callback: data => {
            if ((data?.translated||'') !== '') {
              form?.setFieldsValue({ name: data?.translated||'' });
              onChange && onChange({...changedValues, ...{name: data?.translated||''}}, {...allValues, ...{name: data?.translated||''}});
            }
          }
        })
      }
    } 
  }

  const onOnlyShowRequireChange = () => {
    setOnlyShowRequireChange(!onlyShowRequireChange);
  }

  let distributionDescription = '', primaryDescription = '', partitionsDescription = '', semiPrimaryDescription = '', maintenanceDescription = '';

  if (!editable && modelerData) {
    //分布
    if (modelerData?.easyDataModelerDistributionKey) {
      (modelerData?.easyDataModelerDistributionKey||[]).forEach((item, index) => {
        if (index > 0) {
          distributionDescription += ',';
        }

        distributionDescription += item.name||'';
      });
    }

    //主键
    if (modelerData?.easyDataModelerPrimaryKey) {
      (modelerData?.easyDataModelerPrimaryKey||[]).forEach((item, index) => {
        if (index > 0) {
          primaryDescription += ',';
        }

        primaryDescription += item.name||'';
      })
    }

    //分区
    if (modelerData?.partition?.keys) {
      (modelerData?.partition?.keys||[]).forEach((item, index) => {
        if (index > 0) {
          partitionsDescription += ',';
        }

        partitionsDescription += item.name||'';
      })
    }

    if (modelerData?.partition?.partitionType?.cnName) {
      partitionsDescription += '/' + modelerData?.partition?.partitionType?.cnName||'';
    }

     //类主键
     if (modelerData?.easyDataModelerSemiPrimaryKey) {
      (modelerData?.easyDataModelerSemiPrimaryKey||[]).forEach((item, index) => {
        if (index > 0) {
          semiPrimaryDescription += ',';
        }

        semiPrimaryDescription += item.name||'';
      })
    }
  }

  if ((maintenanceRecords||[]).length>0) {
    maintenanceRecords.forEach((record, index) => {
      if (index !== 0) {
        maintenanceDescription += '/';
      }
      
      maintenanceDescription += record;
    })

    form?.setFieldsValue({ maintenanceRecords: maintenanceDescription });
  }

  return (
    <div className='model-import-action-header'>
    <div 
      className='mb-3'
      style={{ 
      display: 'flex',
      alignItems: 'center',
      }}
    >
      <h2 className='mr-3' style={{ marginBottom: 0 }}>基本信息</h2>
      {
        onlyShowRequireChange ? <Button type='text' style={{ padding: 0, color: '#0069AC' }} onClick={onOnlyShowRequireChange}>展开<DownOutlined /></Button> : <Button type='text' style={{ padding: 0, color: '#0069AC' }} onClick={onOnlyShowRequireChange}>收起<UpOutlined /></Button>
      }
    </div>
    {
      editable ? (
        <Form
          form={form}
          {...formItemLayout}
          onValuesChange={onValuesChange}
        >
          <Row gutter={10}>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="中文名称"
                name="cnName"
                rules={[{ required: true, message: '请输入中文名称!' }]}
              >
                <InputDebounce />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="英文名称"
                name="name"
                rules={[{ required: true, message: '请输入英文名称!' }]}
              >
                <AutoComplete options={options} onSearch={onSearch} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="规范"
                name="easyDataModelerModelingConstraint"
                rules={[{ required: true, message: '请选择规范!' }]}
              >
                <ConstraintSelect 
                  constraints={constraints} 
                  onChange={onConstraintChange} 
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="数据内容"
                name="remark"
                rules={[{ required: true, message: '请输入数据内容!' }]}
                style={{ marginBottom: 15 }}
              >
                <TextArea row={4} />
              </Form.Item>
            </Col>
          </Row>
          {
            !onlyShowRequireChange && <Divider style={{ margin: '0 0 15px' }} />
          }
          {
            !onlyShowRequireChange && <Row gutter={10}>  
            {/* <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="生成表类型"
                name="easyDataModelerModelingTemplate"
                rules={[{ required: false, message: '请选择生成表类型!' }]}
              >
                <TemplateSelect 
                  templates={templates} 
                  onChange={onTemplateChange} 
                />
              </Form.Item>
            </Col> */}
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="数据表类型"
                name="tableType"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="数据平台"
                name="dataResidence"
              >
                <Input disabled={true} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="数据情况"
                name="dataCircumstances"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>     
              <Form.Item
                label="分布键"
                name="easyDataModelerDistributionKey"
              >
                <AttributesSelect modelerData={modelerData} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>  
              <Form.Item
                label="分区键"
                name="partition"
              >
                <PartitionSelect modelerData={modelerData} partitionTypes={supportedPartitionTypes} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="主键"
                name="easyDataModelerPrimaryKey"
              >
                <AttributesSelect modelerData={modelerData} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>  
              <Form.Item
                label="类主键"
                name="easyDataModelerSemiPrimaryKey"
              >
                <AttributesSelect modelerData={modelerData} mode='tags' />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="加载方式"
                name="dataLoadingStrategy"
              >
                <LoadSelect />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="更新时间"
                name="dataUpdatingTiming"
              >
                <UpdateSelect />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} lg={12} xl={8}>
              <Form.Item
                label="维护历史"
                name="maintenanceRecords"
              >
                <TextArea rows={3} disabled={true} />
              </Form.Item>
            </Col>
          </Row>
          }  
        </Form> 
      ) : (
        <React.Fragment>
          <Descriptions column={3}>
            <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>中文名称</div>} >{highlightSearchContentByTerms(modelerData.cnName||'', terms)}</Descriptions.Item>
            <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>英文名称</div>}>
            {
              <div>
                <div>{highlightSearchContentByTerms(modelerData.name||'', terms)}</div>
                {
                  (causes||[]).map((cause, index) => {
                    return (
                      <div key={index} style={{ color: '#ff4d4f' }}>
                      {cause||''}
                      </div>
                    )
                  })
                }
              </div>
            }
            </Descriptions.Item>
            <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>规范</div>} >{modelerData.easyDataModelerModelingConstraint?(modelerData.easyDataModelerModelingConstraint.cnName||''):''}</Descriptions.Item>
            <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>数据内容</div>}>{highlightSearchContentByTerms(modelerData.remark||'', terms)}</Descriptions.Item>
          </Descriptions>  
          {
            !onlyShowRequireChange && <Divider style={{ margin: '0 0 15px' }} />
          }
          {
            !onlyShowRequireChange && <Descriptions column={3}>
              {/* <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>生成表类型</div>} >{modelerData.easyDataModelerModelingTemplate?(modelerData.easyDataModelerModelingTemplate.cnName||''):''}</Descriptions.Item> */}
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>数据表类型</div>} >{highlightSearchContentByTerms(modelerData.tableType||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>数据平台</div>} >{highlightSearchContentByTerms(modelerData.dataResidence||'', terms)}</Descriptions.Item>   
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>数据情况</div>} >{highlightSearchContentByTerms(modelerData.dataCircumstances||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>分布键</div>} >{highlightSearchContentByTerms(distributionDescription||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>分区键</div>} >{highlightSearchContentByTerms(partitionsDescription||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>主键</div>} >{highlightSearchContentByTerms(primaryDescription||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>类主键</div>} >{highlightSearchContentByTerms(semiPrimaryDescription||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>加载方式</div>} >{highlightSearchContentByTerms(modelerData.dataLoadingStrategy||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>更新时间</div>} >{highlightSearchContentByTerms(modelerData.dataUpdatingTiming||'', terms)}</Descriptions.Item>
              <Descriptions.Item label={<div style={{ textAlign: 'right', width: 85 }}>维护历史</div>} >
                <div>
                {
                  (maintenanceRecords||[]).map((record, index) => {
                    return <div key={index}>{record||''}</div>;
                  })
                }
                </div>
              </Descriptions.Item> 
            </Descriptions>
          }         
        </React.Fragment>
      ) 
    }
    </div>
  )
}

export default ImportActionHeader;