/**
 * @description 21.04.25 重构数据源功能
 * @author fyj
 */

import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Spin, Button } from "antd";
import { WeaSwitch } from "comsMobx";
import { WeaLocaleProvider, WeaSearchGroup, WeaRightMenu, WeaCheckbox, WeaDialog, WeaFormItem, WeaTools, WeaUpload } from "ecCom";
import { GeneralTitleColor, checkFormValidator, checkFieldValueUnique } from "../../util/IntegrationUtil.js";
import { checkTableFieldValueUnique }  from "../../apis/CommonService";

const getLabel = WeaLocaleProvider.getLabel;
const { getKey } = WeaTools;

@inject("dataSource")
@observer
export default class CreateOrEditTask extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      src: '/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4',
      num: 0,
      collectParams: {
        favname: getLabel("28051", "新建模板"),
        favouritetype: 1,
        objid: 0,
        link: "wui/engine.html#/blogengine/templateSetCreate",
        importantlevel: 1
      }
    }
  }

  /**
   * 获取弹窗的标题
   * @returns title
   */
  getDialogTitle = () => {
    const {
      tab,
      dataSourceType={},
      dataSourceCreateAndEdit={}
    } = this.props.dataSource;

    if(0 === Number(tab.selectedKey)) {
      return (dataSourceCreateAndEdit.isEdit ? getLabel(26473, "编辑") : getLabel(365, "新建")) + getLabel(385388, "数据源");
    } else if(1 === Number(tab.selectedKey)) {
      return (dataSourceType.isEdit ? getLabel(26473, "编辑") : getLabel(365, "新建")) + getLabel(15025, "数据库类型");
    }
  };

  /**
   * 获取弹窗内的按钮
   * @returns buttons
   */
  getDialogBtns = () => {
    const { tab, rightmenus } = this.props.dataSource;
    const whichRightMenu = [rightmenus.dataSource, rightmenus.dataSourceType][Number(tab.selectedKey)] || [];

    return whichRightMenu.map(m => (
      <Button 
        ecId={`${this && this.props && this.props.ecId || ''}_Button@integrationDataSourceEditDialogButton${m.type}`}
        type="primary"
        onClick={() => this.onRightMenuClick(m.type)}
      >{`${m.menuName}`}</Button>
    ));
  };

  /**
   * 获取右键的操作菜单
   * @returns buttons
   */
  getDialogBtnsRightMenu = () => {
    const { tab, rightmenus } = this.props.dataSource;
    const whichRightMenu = [rightmenus.dataSource, rightmenus.dataSourceType][Number(tab.selectedKey)] || [];

    return whichRightMenu.map(item => (
      {
        key: item.type,
        icon: <i className={item.menuIcon} />,
        content: item.menuName,
        onClick: () => this.onRightMenuClick(item.type)
      }
    ));
  }

  onRightMenuClick = (type) => {
    switch (type) {
      case "BTN_Save":
        this.saveBaseInfo();
        break;
      case "BTN_Test":
        this.saveBaseInfo(this.testSaveCallBack);
        break;
    }
  }

  /**
   * 表单保存之前的必填项处理
   */
  hideFormRequiredFieldKey = () => {
    const { dataSourceCreateAndEdit } = this.props.dataSource;
    const { form } = dataSourceCreateAndEdit;
    const params = form.getFormParams();

    if (params.iscluster == '1') {
      window.e9HideFormFieldKeys = ["host", "port", "dbname", "sortid"];
    } else if(["gs", "dm"].includes(params.type)) {
      window.e9HideFormFieldKeys = ["url", "dbname", "sortid"];
    } else {
      window.e9HideFormFieldKeys = ["url", "sortid"];
    } 
  }

  /**
   * 处理保存时传递给后端的数据
   * @returns params
   */
  handleFormParams = () => {
    const { dataSourceCreateAndEdit, source } = this.props.dataSource;
    const { form } = dataSourceCreateAndEdit;
    const params = form.getFormParams();

    if(source) {
      // 新建保存时添加 typename 分类
      params.typename = source;
    }
    params.id = dataSourceCreateAndEdit.editId || '';
    params.iscluster = (params.iscluster === "0" ? "1" : "2");
    params.sortid = (typeof(params.sortid) === "object" 
      ? params.sortid.join && params.sortid.join(",")
        ? params.sortid 
        : "0"
      : params.sortid);

    return params;
  }
  
  /**
   * 保存
   * @param {function} testSaveCallBack 测试函数
   * @returns 
   */
  saveBaseInfo = (testSaveCallBack=null) => {
    const { tab, dataSourceType, datasourceAPI, dataSourceCreateAndEdit } = this.props.dataSource;
    const { form } = dataSourceCreateAndEdit;
    // 获取 form 表单提交时传递给接口的数据
    const params = this.handleFormParams();
    
    if (Number(tab.selectedKey) === 0) {
      if(/^(ecology)$/gi.test(params.pointid)) {
        form.showError('pointid', getLabel('519109','ecology不允许作为数据源名称'));
        return;
      }
      
      // 隐藏必填项的校验
      this.hideFormRequiredFieldKey();

      checkFormValidator(form)
        .then(() => {
          let checkParams = {
            tableName: 'datasourcesetting',
            fieldName: 'pointid',
            fieldValue: form.getFormParams().pointid.replace(/^(\s*)|(\s*)$/g, ''),
            idName: 'id',
            idValue: dataSourceCreateAndEdit.editId
          };
          return checkFieldValueUnique(checkParams, 1);
        })
        .then(title => {
          if(title) {
            form.showError('pointid', title);
          } else {
            if(dataSourceCreateAndEdit.isEdit || dataSourceType.isEdit) {
              if(testSaveCallBack && typeof(testSaveCallBack) === "function") {
                params.operate = 'test';
              }
              datasourceAPI().update(params, (result) => {
                if(result.status != "false") {
                  typeof(this.props.saveCallBack) === "function" && this.props.saveCallBack(result);
                }
              }, typeof(testSaveCallBack) != "function");
            } else {
              datasourceAPI().insert(params, (result) => {
                if(result.status != "false") {
                  typeof(this.props.saveCallBack) === "function" && this.props.saveCallBack(result);
                  typeof(testSaveCallBack) === "function" && testSaveCallBack(result.datasourcesettingid);
                }
              }, typeof(testSaveCallBack) != "function");
            }
          }
        })
        .catch(reason => {
          console.error(reason.message);
        });
    }
  }

  testSaveCallBack = (datasourcesettingid) => {
    const {
      dataSourceCreateAndEdit,
      datasourceAPI,
      getForm
    } = this.props.dataSource;
    
    datasourceAPI().test({datasourcesettingid}, () => {
      getForm({ id: datasourcesettingid });
      dataSourceCreateAndEdit.isEdit = true;
      dataSourceCreateAndEdit.editId = datasourcesettingid;
    });
  }

  getSearchs = (form, datas, hide) => {
    const { isFormInit } = form;
    const { isclusterAttr, dataSourceCreateAndEdit } = this.props.dataSource;
    const group = [];
    const formParams = form.getFormParams();

    isFormInit && datas && datas.forEach((c, index) => {
      const items = [];
      c && c.items && c.items.forEach(fields => {
        const key = fields.domkey[0];

        if('driverfilename' !== key) {
            items.push({
              com: (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@kv402k@integrationDataSourceEditForm${key}`}
                  label={`${fields.label}`}
                  labelCol={{ span: fields.labelcol }}
                  wrapperCol={{ span: fields.fieldcol }}
                  fieldType={fields.conditionType.toUpperCase()}
                  error={form.getError(fields)}
                  tipPosition="bottom"
                >
                  {"iscluster" === key ?  
                    <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@nqhnaf@integrationDataSourceEditForm${key}`} 
                      viewAttr={isclusterAttr == 0 ? 1 : 2} 
                      value={formParams.iscluster} 
                      helpfulTip={<div dangerouslySetInnerHTML={{__html: `SqlServer:<br/>jdbc:sqlserver://${getLabel('83578', '地址')}:${getLabel('84629', '端口')};DatabaseName=${getLabel('504419','数据库名')}<br/>Oracle:<br/>jdbc:oracle:thin:@${getLabel('83578', '地址')}:${getLabel('84629','端口')}:${getLabel('504419','数据库名')}<br/>MySQL:<br/>jdbc:mysql://${getLabel('83578', '地址')}:${getLabel('84629','端口')}/${getLabel('504419','数据库名')}?useUnicode=true&characterEncoding=utf8<br/>DB2:<br/>jdbc:db2://${getLabel('83578', '地址')}:${getLabel('84629','端口')}/${getLabel('504419','数据库名')}<br/>Sybase:<br/>jdbc:sybase:Tds:${getLabel('83578', '地址')}:${getLabel('84629','端口')}/${getLabel('504419','数据库名')}?charset=cp936<br/>Informix:<br/>jdbc:informix-sqli://${getLabel('83578', '地址')}:${getLabel('84629','端口')}/${getLabel('504419','数据库名')}:INFORMIXSERVER=myserver<br/>Hana:<br/>jdbc:sap://${getLabel('83578', '地址')}:${getLabel('84629','端口')}?reconnect=true`}} />} onChange={v => form.updateFields({iscluster: v})} 
                      onChange={v => form.updateFields({iscluster: v})}
                    /> 
                    : <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@nwa05l@integrationDataSourceEditForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams}
                        onChange={v => {
                          if(getKey(fields) === 'pointid') {
                            if(v.pointid && v.pointid.value) {
                              if(/^(ecology)$/gi.test(v.pointid.value)) {
                                form.showError('pointid', getLabel('519109','ecology不允许作为数据源名称') );
                              }else {
                                let checkParams = {
                                    tableName: 'datasourcesetting',
                                    fieldName: 'pointid',
                                    fieldValue: form.getFormParams().pointid.replace(/^(\s*)|(\s*)$/g, ''),
                                    idName: 'id',
                                    idValue: dataSourceCreateAndEdit.editId
                                };
                                checkFieldValueUnique(checkParams, 1)
                                  .then(title => {
                                    if(title) {
                                      form.showError('pointid', title);
                                    }
                                  });
                              }
                            }
                          }else if(getKey(fields) === 'dbtype') {
                            let checkParams = {
                                tableName: 'datasource_type',
                                fieldName: 'dbtype',
                                fieldValue: form.getFormParams().dbtype.replace(/^(\s*)|(\s*)$/g, ''),
                                idName: 'id',
                                idValue: ''
                            };
                            checkTableFieldValueUnique(checkParams).then(result => {
                                if(result&&result.isNotUnique) {
                                  form.showError('dbtype',getLabel('129943','名称已存在'));
                                }
                            });
                          }
                        }}
                      />
                  }
                </WeaFormItem>),
              colSpan: 1,
              hide: form.isHide(fields, (keys, allParams) => {
                if (hide) {
                  return hide(getKey(fields), keys, allParams)
                }
              })
            })
          }else if(getKey(fields) === 'driverfilename') {
            if(fields.datas[0]) {
              let params = fields.datas[0];
              Object.assign(params, {imgSrc : ''})
            }
            items.push({
              com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@jus5vs@integrationDataSourceEditForm${fields.domkey[0]}`}
                    label={`${fields.label}`}
                    labelCol={{ span: fields.labelcol }}
                    wrapperCol={{ span: fields.fieldcol }}
                    fieldType={fields.conditionType.toUpperCase()}
                    error={form.getError(fields)}
                    tipPosition="bottom"
                  >
                      <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@hyuz5q@integrationDataSourceEditForm${fields.domkey[0]}`}
                        uploadUrl={fields.uploadUrl}
                        category='string'
                        maxFilesNumber={1}
                        showClearAll={false}
                        datas={fields.datas}
                        getShowListDatas={(...arr) => {
                          if(arr[0].length === 0) {
                            document.querySelector('.wea-upload-container').style.display='block';
                            form.updateFields({
                              driverfilename:''
                            })
                          }else {
                            document.querySelector('.wea-upload-container').style.display='none';
                            form.updateFields({
                              driverfilename: `${arr[0][0].fileid}`
                            })
                          }
                        }}
                      />
                  </WeaFormItem>)
            })
          }
      });
    
      group.push(
        <WeaSearchGroup 
          ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@x7p43b@integrationDataSourceEditForm${index}`} 
          center={index === 0 ? true : false} 
          col={1} 
          needTigger={true} 
          title={c.title}
          showGroup={c.defaultshow} 
          items={items} 
        />
      )
    });
    return group;
  }

  closeDialog = () => {
    const { dataSourceCreateAndEdit, dataSourceType } = this.props.dataSource;

    dataSourceCreateAndEdit.show = false;
    dataSourceType.show = false;
    this.setState({num: 0});
  }

  render() {
    const { loading, dataSourceCreateAndEdit, tab, dataSourceType} = this.props.dataSource;
    const {collectParams} = this.state;

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@huvj7p`}
        icon={GeneralTitleColor.icon}
        iconBgcolor={GeneralTitleColor.iconBgcolor}
        style={{ width: 700, height: 600 }}
        hasScroll={true}
        title={this.getDialogTitle()}
        visible={
          Number(tab.selectedKey) === 0
            ? dataSourceCreateAndEdit.show
            : dataSourceType.show
        }
        onCancel={this.closeDialog}
        buttons={this.getDialogBtns()}
        moreBtn={{
          datas: this.getDialogBtnsRightMenu(),
          collectParams,
        }}
      >
        <WeaRightMenu 
          ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@gdwiwj`} 
          datas={this.getDialogBtnsRightMenu()} 
          collectParams={collectParams}
        >
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@3c5f03`} spinning={loading}>
            {
              Number(tab.selectedKey) === 0 
                ? this.getSearchs(
                    dataSourceCreateAndEdit.form, 
                    toJS(dataSourceCreateAndEdit.conditions), 
                    (key, b, c) => {
                      switch (key) {
                        case "host":
                        case "port":
                          return c.iscluster == 1;
                        case "url":
                          return c.iscluster == 0 || c.iscluster == 2;
                        case "dbname":
                          return c.iscluster == 1 || ["gs", "dm"].includes(c.type);
                      }
                      return false;
                    }
                  )
                : this.getSearchs(dataSourceType.form, toJS(dataSourceType.conditions))
            }
          </Spin>
        </WeaRightMenu>
      </WeaDialog>
    );
  }
}
