import React from 'react';
import {
  inject,
  observer
} from "mobx-react";
import {
  toJS
} from 'mobx';
import {
  Button,
  message
} from 'antd';
import {
  WeaLocaleProvider,
  WeaTop,
  WeaRightMenu,
  WeaFormItem,
  WeaSearchGroup,
  WeaTools,
} from "ecCom";
import * as IntegrationUtil from "../util/IntegrationUtil";
import {
  WeaSwitch
} from "comsMobx";
import { checkValidateCode }  from "../apis/CommonService";
import NoRight from '../public/NoRight';

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

@inject("accountSettingStore")
@observer
class Main extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      src: (window.ecologyContentPath || "") + '/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4',
      num: 0
    }
  }

  componentDidMount() {
    const {
      accountSettingStore
    } = this.props;
    const {
      doInit,
      singleInit
    } = accountSettingStore;

    if (this.props.params.id !== undefined) {
      singleInit(this.props.params.id);
    } else {
      doInit();
    }
  }
  
  getDropMenuDatas = () => {
    const {
      accountSettingStore
    } = this.props;
    const {
      doInit,
      buttons
    } = accountSettingStore;
    const btnArr = [];
    toJS(buttons).forEach(item => {
      btnArr.push({
        key: item.type,
        icon: <i className={item.menuIcon} />,
        content: item.menuName,
        onClick: () => this.clickEvent(item.type)
      })
    })
    return btnArr;
  }

  getWeaTopBtns = () => {
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9n4g8y@integrationAccountSettingButtonSave`} type="primary" onClick={() => this.clickEvent("BTN_Save")}>{getLabel("30986", "保存")}</Button>
    ]
  }

  clickEvent = type => {
    const {
      accountSettingStore
    } = this.props;
    const {
      status,
      setStatus,
      form,
      singleForm,
      condition,
      doSave,
      doInit
    } = accountSettingStore;
    if("BTN_Save" == type) {
        const params = form.getFormParams() || {};
        const otherParams = singleForm.getFormParams();
            
        if(this.props.params.id == undefined){
          if(params.validatecode !== undefined) {
            if(!(params.validatecode && params.validatecode.trim())) {
              message.error(getLabel('390564','"验证码"未填写'));
              return;
            }
            checkValidateCode({validatecode: params.validatecode}).then(result => {
              if(result&&result.isValid) {
                doSave(this.props.params.id !== undefined ? { ...otherParams,
                  sysid: this.props.params.id
                } : params, doInit);
                this.setState({num: this.state.num + 1}, function() {
                  this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
                })        
              }else {
                form.showError('validatecode',getLabel('129308','无效的验证码！'));
                this.setState({num: this.state.num+1}, function() {
                  this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
                });
                return;
              }
            })
          }else {
            doSave(this.props.params.id !== undefined ? { ...otherParams,
              sysid: this.props.params.id
            } : params, doInit);
            this.setState({num: this.state.num + 1}, function() {
              this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
            })    
          }
        }else{
          if(otherParams.validatecode !== undefined) {
            if(!(otherParams.validatecode && otherParams.validatecode.trim())) {
              singleForm.showError('validatecode', getLabel('390564','"验证码"未填写'));
              return;
            }
            checkValidateCode({validatecode: otherParams.validatecode}).then(result => {
              if(result&&result.isValid) {
                doSave(this.props.params.id !== undefined ? { ...otherParams,
                  sysid: this.props.params.id
                } : params);
                this.setState({num: this.state.num + 1}, function() {
                  this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
                })        
              }else {
                singleForm.showError('validatecode',getLabel('129308','无效的验证码！'));
                this.setState({num: this.state.num+1}, function() {
                  this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
                });
                return;
              }
            })
          }else {
            doSave(this.props.params.id !== undefined ? { ...otherParams,
              sysid: this.props.params.id
            } : params);
            this.setState({num: this.state.num + 1}, function() {
              this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
            })    
          }
        }
      }
  }

  getFormSearchs = (form, datas=[]) => {
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.map((c, index) => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@hl8rpy@integrationAccountSettingForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                getKey(fields) == 'validatecode' 
                 ? <div>
                     <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@szznju@integrationAccountSettingForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />
                     <img style={{height:30, cursor: 'pointer'}} src={this.state.src} onClick={() => {
                       this.setState({num: this.state.num+1}, function() {
                         this.setState({src: `${window.ecologyContentPath || ""}/weaver/weaver.file.MakeValidateCode?notneedvalidate=1&isView=1&validatetype=0&validatenum=4&seriesnum_=${this.state.num}`})
                       })
                     }}></img>
                   </div>
                 : <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@veqm4l@integrationAccountSettingForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />
              }
            </WeaFormItem>),
          colSpan: 1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@2n4p94@integrationAccountSettingForm${index}`} center={true} col={1} needTigger={true} title={c.title} showGroup={true} items={items} />);
    });
    return group;
  }

  render() {
    const {
      accountSettingStore
    } = this.props;
    const {
      status,
      form,
      condition,
      singleForm,
      singleCondition,
      hasRight
    } = accountSettingStore;
    const {
      loading,
      formLoading
    } = toJS(status);

    return (
      formLoading
        ? null
        : hasRight
          ?
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@0o9cqs`} datas={this.getDropMenuDatas()}
              dropMenuProps={{
                collectParams: {
                  favname: `${getLabel("129787", "账号设置")}`,
                  favouritetype: 1,
                  objid: 0,
                  link: "wui/engine.html#/integration/coremail",
                  importantlevel: 1
                }
              }}
            >
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@fzx1jf`}
                loading={loading}
                buttons={this.getWeaTopBtns()}
                title={getLabel("19667", "账号设置")}
                icon={<i className={IntegrationUtil.GeneralTitleColor.icon} />}
                iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
                showDropIcon={true}
                dropMenuDatas={this.getDropMenuDatas()}
                dropMenuProps={{
                  collectParams: {
                    favname: `${getLabel("19667", "账号设置")}`,
                    favouritetype: 1,
                    objid: 0,
                    link: "wui/engine.html#/integration/129787",
                    importantlevel: 1
                  }
                }}
              >
                {this.props.params.id !== undefined ? (
                  <div>
                    {this.getFormSearchs(singleForm, toJS(singleCondition))}
                  </div>
                ) : (
                  <div>
                    {this.getFormSearchs(form, toJS(condition))}
                  </div>
                )}
              </WeaTop>
            </WeaRightMenu>
          : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@20kjyg`} />
    )
  }
}

export default Main;