import React from "react";
import {inject, observer} from "mobx-react";
import {Button} from "antd";
import {toJS} from "mobx";
import {
  WeaSwitch
} from "comsMobx";
import {
  WeaDialog, 
  WeaLocaleProvider, 
  WeaHelpfulTip, 
  WeaTable, 
  WeaRightMenu,
  WeaFormItem,
  WeaSearchGroup,
} from "ecCom";
import {
  onCheck, 
  doConfirm
} from '../../util/IntegrationUtil';

const getLabel = WeaLocaleProvider.getLabel;

@inject("samlStore")
@observer
export default class AppEditDialog extends React.Component {

  // 检测的列重新渲染
  renderColumns = (columns=[]) => {
    return columns && columns.map(item => {
      if(item.dataIndex === "result") {
        item.render = (text, record) => (
          <div>
            {
              record.result
                ? <span style={{color: "green"}}>√</span> 
                : <span style={{color: "red"}}>×<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@qslzwx`} style={{marginLeft: "10px"}} title={record.helpTips} /></span>
            }
          </div>
        );
      }
      return item;
    })
  }

  /**
   * 获取右键菜单
   * @param {右键菜单} datas 
   */
  getRightMenu = (datas=[]) => {
    const {status: {isConfigured}} = this.props.samlStore;
    return datas && datas.map(item => {
      return {
        ...item,
        disabled: (!isConfigured) && item.key === "BTN_TEST",
        onClick: () => this.onRightMenuClick(item.key)
      }
    })
  }

  getBtns = (datas=[]) => {
    const {status: {isConfigured}} = this.props.samlStore;
    return datas && datas.map(item => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8kikd7@integrationSamlAppAddButton${item.key}`} disabled={item.key === "BTN_TEST" && (!isConfigured)} type={item.type} key={item.key} onClick={() => this.onRightMenuClick(item.key)}>{item.content}</Button>);
  }

  onRightMenuClick = (type) => {
    const {
      samlStore
    } = this.props, {
      status,
      configForm, 
      getDetailInfoForm,
      getConfigurationResult,
      getDetailInfoFormOperation,
    } = samlStore, {
      hiddenFields
    } = toJS(status);
    let params = Object.assign({}, configForm.getFormParams(), hiddenFields);
    if(type == 'BTN_SAVE'){
      onCheck(configForm, () => getDetailInfoFormOperation(params, () => {
        samlStore.cleanDialog();
      }));
    }else if(type == 'BTN_TEST'){
      getConfigurationResult();
      samlStore.setState({
        editTab: "test"
      });
    }else if(type === "BTN_EDIT") {
      getDetailInfoForm();
      samlStore.setState({
        editTab: "edit"
      });
    }else if(type === "BTN_SAVE_CONFIG") {
      onCheck(configForm, () => doConfirm(
        getLabel('517864','点此配置前请手动清空配置目录下已生成的配置'),
        () => getDetailInfoFormOperation({...params, generateCfg: '1'}, () => {
          samlStore.cleanDialog();
          samlStore.setState({isConfigured: true});
        })
      ));
    }
  }

  // form表单的渲染
  getForm = (form, datas=[]) => {
    const {
      samlStore
    } = this.props, {
      status
    } = samlStore, {
      sp_urls,
      sp_urls_columns
    } = toJS(status);

    const {isFormInit} = form;
    const formParams = form.getFormParams();
    let group = [];
    isFormInit && datas && datas.forEach((c, index) => {
      let items = [], left = (datas.length - 1 === index) ? "-20px" : 0;
      if(index == 1) {
        items.push({
          com: (<div style={{margin: "-8px -10px -10px -30px"}}>
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@4gfc2q@integrationSamlAppAdd${index}`} 
              dataSource={sp_urls} 
              columns={sp_urls_columns} 
              scroll={{x: true}}
              pagination={false}
            />
          </div>),
          colSpan: 1,
        })
      }else {
        c && c.items && c.items.forEach(fields => {
          items.push({
            com: (<div style={{marginLeft: left}}>
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9jdunj@integrationSamlAppAdd${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{span: `${datas.length - 1 === index ? 0 : fields.labelcol}`}}
                wrapperCol={{span: `${datas.length - 1 === index ? 24 : fields.fieldcol}`}}
                error={form.getError(fields)}
                tipPosition="bottom"
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@k8hapx@integrationSamlAppAdd${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} />
              </WeaFormItem>
            </div>),
            colSpan: 1,
            hide: form.isHide(fields, (keys, allParams) => {
              let bool = false, key = fields.domkey[0];
              key === "keystore_file" && allParams.create_new_self_sign == '1' && (bool = true);
              fields && fields.showWhere && fields.showWhere.length > 0 && fields.showWhere.map(w => {
                if(!bool){
                  let show = false;
                  for(let val of w.value){
                    if(allParams[w.domkey] == val){
                        show = true;
                        break;
                    }
                  }
                  bool = !show;
                }
              })
              return bool;
            })
          });
        })
      }
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@v9nwbm@integrationSamlAppAdd${index}`} col={1} center={!(datas.length - 1 === index || index == 1)} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  render() {
    const {
      samlStore
    } = this.props, {
      status,
      configForm
    } = samlStore, {
      editTab,
      testMenus,
      dialogMenus,
      configCondition=[],
      testResultDatas=[],
      testResultColumns=[],
      appEditDialogVisible,
    } = toJS(status);
    
    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@8t6qtq`}
      title={editTab === "edit" ? getLabel('516657','OIOSAML配置') : editTab === "test" ? getLabel('516677','OIOSAML配置检查') : ""}
      onCancel={()=> samlStore.cleanDialog()}
      visible={appEditDialogVisible}
      style={{width: 800, height: 600}}
      hasScroll
      moduleName="integration"
      buttons={this.getBtns(editTab === "edit" ? dialogMenus : testMenus)}
      moreBtn={{
        datas : this.getRightMenu(editTab === "edit" ? dialogMenus : testMenus),
        collectParams: []
      }}
    >
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@vn1zhg`}
        datas={this.getRightMenu(editTab === "edit" ? dialogMenus : testMenus)}
        collectParams={[]}
      >
        {
          editTab === "test"
            ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@smy4zh`} 
                dataSource={testResultDatas} 
                columns={this.renderColumns(testResultColumns)} 
                scroll={{x: true}}
                pagination={false}
              />
            : editTab === "edit"
              ? this.getForm(configForm, configCondition)
              : null
        }
      </WeaRightMenu>
    </WeaDialog>
  }
}
