import React from 'react';
import {inject, observer} from "mobx-react";
import {toJS} from "mobx";
import {Button} from "antd";
import {WeaFormItem, WeaTableEditable, WeaLocaleProvider, WeaRightMenu, WeaSearchGroup, WeaNewScroll, WeaTop, WeaInput} from "ecCom";
import {WeaSwitch} from "comsMobx";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import {GeneralTitleColor, doConfirm} from "../../util/IntegrationUtil";
import TestMessage from './TestMessage';
import "../../style/webxml.less";

const {getLabel} = WeaLocaleProvider;

@inject("oauth2Store")
@observer
export default class OAuth2 extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      tableOps: {
        showTitle: true,
        showAdd: true,
        showDelete: true,
        showCopy: false,
        showMove: false,
        tableProps: {showEmptyText: false},
      }
    };
  }

  componentWillUnmount() {
    this.state={
      tableOps: {
        showTitle: true,
        showAdd: true,
        showDelete: true,
        showCopy: false,
        showMove: false,
        tableProps: {showEmptyText: false},
      }
    };
  }
  
  componentDidMount() {
    this.props.oauth2Store.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if(this.props.location.key !== nextProps.location.key) {
      this.props.oauth2Store.doInit();
    }
  }

  /**渲染列 */
  renderColumns = (columns, flag) => {
    columns && columns.forEach((item, index) => {
      if(["clazz"].includes(item.dataIndex) && flag === "header") {
        columns[index].com = [{
          type: "CUSTOM",
          key: item.dataIndex,
          render: (text, record, index, onEdit) => {
            if(item.dataIndex === "clazz" && record.headTag && record.headTag.trim().toLocaleLowerCase() === "authorization") {
              return <nobr>
                <label title={getLabel('513949','签名算法实现类')} style={{
                  display: "inline-block",
                  width: 110,
                  whiteSpace: "nowrap",
                  textOverflow: "ellipsis",
                  overflow: "hidden"
                }}>{getLabel('513949','签名算法实现类')}:</label>
                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@j01070@integrationAouth2Column${item.dataIndex}`} style={{width: 120}} value={record[item.dataIndex]} onChange={value => onEdit({value, index, key: item.dataIndex, record})} />
              </nobr>
            }
          }
        }]
      }
    })
    return columns;
  }

  willDelete = (datas, key, name) => {
    const {oauth2Store} = this.props;
    doConfirm(getLabel(385625, '确定要删除选择的记录吗？'), () => {
      if(oauth2Store[name]) {
        oauth2Store[name].state.selectedRowKeys = [];
        oauth2Store[name].state.selectedRows = [];
      }
      oauth2Store.setState({[name]: datas})
    });
  }

  willEdit = (datas, editData) => {
    const {value, index, key} = editData;
    datas[index] = {
      ...datas[index],
      [key]: value ? value.trim() : ""
    }
    return datas;
  }

  /**获取table数据 */
  getTableDatas = (index, form) => {
    const {oauth2Store} = this.props;
    const {status} = oauth2Store;
    const {paramsColumns, headerColumns} = toJS(status);
    const allParams = form.getFormParams();
    let isShow = true;

    if("baseInfo" === index) {
      index = "other";
    }

    if(("profile" == index && allParams.profile_use != '1') || ("logout" === index && allParams.logout_use != '1') || ("refresh_token" === index && allParams.refresh_token_use != '1') || ("heart_beat" === index && allParams.heart_beat_use != '1')) {
      isShow = false;  
    }
    if(isShow) {
      let dom = null,
        tableStateProps = {
          ...this.state.tableOps,
          title: "other" === index ? <span style={{float: "left", marginLeft: -10}}>{getLabel('20967','其他参数')}</span>: "",
        };
          
      if("other" != index) {
        dom = <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@ci8oio`}
          key={`${index}_header`}
          ref={el => oauth2Store[`${index}_header`] = el}
          {...this.state.tableOps}
          validator={{
            rules: {
              headTag: 'required|uniqueAttrName',
            },
            customRegister: [{
              name: "uniqueAttrName",
              rules: (value, requirement, attribute) => {
                return toJS(status)[`${index}_header`].filter(v => v.headTag === value).length < 2;
              },
              errorMessage: getLabel('514688','头部标签重复')
            }]
          }}
          title={<span style={{float: "left", marginLeft: -10}}>{getLabel('128539','请求头')}</span>}
          columns={this.renderColumns(headerColumns, "header")}
          datas={toJS(status)[`${index}_header`] || []}
          willDelete={(datas, key) => this.willDelete(datas, key, `${index}_header`)}
          willEdit={this.willEdit}
          onChange={datas => oauth2Store.setState({[`${index}_header`]: datas})}
        />;
        tableStateProps = {
          ...this.state.tableOps,
          title: <span style={{float: "left", marginLeft: -10}}>{getLabel('128540','请求参数')}</span>,
        }
      };
        
      return <div>
        {dom}
        <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@zwzxg7`}
          style={{marginTop: 10}}
          key={`${index}_params`}
          ref={el => oauth2Store[`${index}_params`] = el}
          {...tableStateProps}
          validator={{
            rules: {
              paramKey: 'required|uniqueAttrName',
            },
            customRegister: [
              {
                name: "uniqueAttrName",
                rules: (value, requirement, attribute) => {
                  return toJS(status)[`${index}_params`].filter(v => v.paramKey === value).length < 2;
                },
                errorMessage: getLabel('388334','参数名重复')
              }
            ]
          }}
          columns={paramsColumns}
          willDelete={(datas, key) => this.willDelete(datas, key, `${index}_params`)}
          datas={toJS(status)[`${index}_params`] || []}
          willEdit={this.willEdit}
          onChange={datas => oauth2Store.setState({[`${index}_params`]: datas})}
        />
      </div>
    }else {
      return null;
    }
  }

  /**form表单的联动 */
  hideFormField = (key, allParams) => {
    let bool = false;

    ["isuse", "summary"].indexOf(key) == -1 && allParams.isuse != '1' && (bool = true);
    ["profile_url", "profile_method", "profile_class", "profile_account_type", "profile_account_key"].includes(key) && allParams.profile_use != '1' && (bool = true);
    ["logout_url", "logout_method", "logout_class"].includes(key) && allParams.logout_use != '1' && (bool = true);
    ["refresh_token_url", "refresh_token_method", "refresh_token_class"].includes(key) && allParams.refresh_token_use != '1' && (bool = true);
    ["heart_beat_url", "heart_beat_method", "heart_beat_class", "heart_beat_ok_flag"].includes(key) && allParams.heart_beat_use != '1' && (bool = true);
    ["profile_account_key"].includes(key) && allParams.profile_account_type == "7" && (bool = true);
    ["profile_account_customsql"].includes(key) && allParams.profile_account_type != "7" && (bool = true);

    return bool;
  }

  /**测试事件 */
  handleTest = (type) => {
    const {oauth2Store} = this.props;

    oauth2Store.doTest({type});
    if("authorize" != type) {
      oauth2Store.setState({testDialogVisible: true});
    }
  }

  /**获取form中的测试按钮 */
  getFormDom = (allParams, key, index) => {
    let dom = null;
    if(['authorize_url', 'access_token_url', 'refresh_token_url', 'logout_url', 'heart_beat_url', 'profile_url'].includes(key)) {
      dom = <Button 
        ecId={`${this && this.props && this.props.ecId || ''}_Button@d3zcd7`} 
        style={{marginLeft: 20}} 
        size="small" 
        disabled={allParams[key].trim() == ""} 
        onClick={() => this.handleTest(index)}
      >{getLabel('25496', '测试')}</Button>;
    }
    return dom;
  }

  getBaseInfoForm = (form, datas=[]) => {
    const {isFormInit} = form;
    const formParams = form.getFormParams();
    let group = [];
    isFormInit && datas && datas.forEach((c, index) => {
      if(c.key != "other" && (formParams.isuse == '1' || (formParams.isuse != '1' && ["baseInfo", "description"].includes(c.key)))) {
        let items = [];
        c.items && c.items.forEach(fields => {
          const key = fields.domkey[0];
          const dom = this.getFormDom(formParams, key, c.key, form);
          
          if(key != "profile_use") {
            items.push({
              com:(<div style={"description" === c.key ? {marginLeft: -20} : null}>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@edlds3@integrationAouth2Form${key}`}
                  label={fields.label}
                  labelCol={{span: "description" === c.key ? 0 : fields.labelcol}}
                  wrapperCol={{span: "description" === c.key ? 24 : fields.fieldcol}}
                  error={form.getError(fields)}
                  tipPosition="bottom"
                >
                  {
                    dom
                      ? <nobr>
                          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@p67uye@integrationAouth2Form${key}`} fieldConfig={fields} form={form} onChange={v=> {
                            if(v[key]) {
                              form.updateFields({[key]: form.getFormParams()[key].trim()});
                            }
                          }} />
                          {dom}
                        </nobr>
                      : <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2p632x@integrationAouth2Form${key}`} fieldConfig={fields} form={form} onChange={v=> {
                          if(v[key]) {
                            form.updateFields({[key]: form.getFormParams()[key].trim()});
                          }
                        }} />
                  }
                </WeaFormItem>
              </div>),
              colSpan:1,
              hide: form.isHide(fields, (keys, allParams) => this.hideFormField(key, allParams))
            });
          }
        });
        if(formParams.isuse == '1' && c.key && ["auth_method", "description"].indexOf(c.key) === -1) {
          items.push({
            com: this.getTableDatas(c.key, form)
          })
        }
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@9pbsn4@integrationAouth2Form${index}`} center={index != datas.length - 1} col={1} needTigger={true} title={c.title} showGroup={this.props.oauth2Store.status[`searchGroup_${index}_visible`]} items={items} onVisibleChange={v => this.props.oauth2Store.setState({[`searchGroup_${index}_visible`]: v})}/>);
      }
    });

    return group;
  }

  render() {
    const {oauth2Store} = this.props;
    const {baseForm, status, menus} = oauth2Store;
    const {hasRight, rightLoading, formLoading, baseInfoFormFields, testDialogVisible, hasNonStandard, nonStandLoading} = toJS(status);

    return (
      nonStandLoading
        ? null
        : hasNonStandard
          ? rightLoading
            ? null
            : hasRight 
              ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@8c0ibn`}
                  className={"inte-webxml-rightmenu"}
                  datas={menus && menus.rightMenus}
                  collectParams={menus && menus.collectParams}
                >
                  <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@dyyyx6`}
                    title={menus && menus.title}
                    loading={formLoading}
                    icon={GeneralTitleColor && GeneralTitleColor.iconDom}
                    iconBgcolor={GeneralTitleColor && GeneralTitleColor.iconBgcolor}
                    buttons={menus && menus.buttons}
                    showDropIcon={true}
                    dropMenuDatas={menus && menus.rightMenus}
                    dropMenuProps={{
                      collectParams: menus && menus.collectParams
                    }}
                  />
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@rdd6nw`} height={"calc(100% - 60px)"}>
                    {this.getBaseInfoForm(baseForm, baseInfoFormFields)}
                  </WeaNewScroll>
                  {testDialogVisible && <TestMessage ecId={`${this && this.props && this.props.ecId || ''}_TestMessage@bqd1kl`}/>}
                </WeaRightMenu>
              : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@gg7um6`}/>
          : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@95gvlt`} />
    );
  }
}
