import React from "react";
import {inject, observer} from "mobx-react";
import { Button} from "antd";
import {toJS} from "mobx";
import {WeaForm, WeaLogView, WeaSwitch, WeaTableNew} from "comsMobx";
import {WeaDialog, WeaLocaleProvider, WeaTools, WeaSearchGroup, WeaFormItem, WeaRightMenu,WeaTab,WeaNewScroll,WeaTop,WeaPopoverHrm} from "ecCom";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import AppDataMappingEditDialog from "./AppDataMappingEditDialog";
import AppDataMappingImportDialog from "./AppDataMappingImportDialog";
import AppDataMappingImportResultDialog from "./AppDataMappingImportResultDialog";
const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const { WeaTable } = WeaTableNew;
const store = ["oauth2Store"];

@inject(...store)
@observer
export default class AppEditDetailDialog extends React.Component {
  constructor (props) {
    super(props);
  }

  render() {
    const {oauth2Store} = this.props;
    const status = toJS(oauth2Store.status);
    const {showSearchAd2, selectedKey} = toJS(status);
    let topTab = [
      {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(81711, "基本信息")}`,
        viewcondition_dt: 0
      }
      ,{
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(131274, "运行日志")}`,
        viewcondition_dt: 2
      }
    ];
    let account_rules = oauth2Store.registerAppEditForm.getFormParams().account_rules;
    if(account_rules=="6"||account_rules=="7"){
      topTab = [
        {
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(81711, "基本信息")}`,
          viewcondition_dt: 0
        }
        ,{
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(381943, "数据映射")}`,
          viewcondition_dt: 1
        }
        ,{
          color: "#000000",
          groupid: "flowAll",
          showcount: true,
          title: `${getLabel(131274, "运行日志")}`,
          viewcondition_dt: 2
        }
      ];
    }

    return <WeaDialog
      title={getLabel('82178','编辑应用')}
      onCancel={()=> oauth2Store.setState({appEditFormDetailDialogVisible: false})}
      visible={status.appEditFormDetailDialogVisible}
      style={{width: 1000, height: 600}}
      hasScroll
      moduleName="integration"
      buttons={
        oauth2Store.editDetailDialogSelectedKey==0?
        [<Button type="primary" onClick={()=> this.onRightMenuClick('BTN_SAVE')}>{getLabel(86,'保存')}</Button>]:[]
      }
      // moreBtn={oauth2Store.editDetailDialogSelectedKey!=2?{datas : this.getRightMenu(), collectParams: []}: []}
      moreBtn={{datas : this.getRightMenu(), collectParams: []}}
    >
      <WeaPopoverHrm />
      <WeaRightMenu
        datas={this.getRightMenu()}
        collectParams={[]}
      >

        <WeaTab
          datas={topTab}
          keyParam="viewcondition_dt" //主键
          countParam="groupid" //数量
          selectedKey={oauth2Store.editDetailDialogSelectedKey}
          searchType={oauth2Store.editDetailDialogSelectedKey==1?['advanced']:[]}
          advanceHeight={80}
          buttons={oauth2Store.editDetailDialogSelectedKey==0?[]:oauth2Store.editDetailDialogSelectedKey==1?this.getTabButton():[]}
          searchsAd={this.getAdvancedSearch()}
          showSearchAd={showSearchAd2}
          buttonsAd={this.getTabButtonsAd()}
          setShowSearchAd={() => {oauth2Store.setState({ showSearchAd2: !showSearchAd2 })}}
          hideSearchAd={() => {oauth2Store.setState({ showSearchAd2: false })}}
          onChange={v => {
            oauth2Store.setEditDetailDialogSelectedKey(v);
          }}
          // onSearch={() => {
          //   let params={id:oauth2Store.registerAppId}
          //   oauth2Store.getRegisterAppDataMappingList(params)
          // }}
          // onSearchChange={value => {}}
        />
        <WeaNewScroll
          height={550}
          onScroll={(e)=>{
            this.setState({
              scrollTop:e.target.scrollTop,
            })
          }}>
          {
            oauth2Store.editDetailDialogSelectedKey==0? this.getSearch1() : (oauth2Store.editDetailDialogSelectedKey==1 
              // ? this.getSearch2():this.getSearch3())
              ?  (<WeaTable
                      comsWeaTableStore={oauth2Store.tableStore2}
                      hasOrder={true}
                      needScroll={true}
                      onOperatesClick={this.onOperatesClick.bind(this)}
                      // uniqueId={true}
                      rowSelection={{onChange: selectedRowKeys => (oauth2Store.setState({rowSelectIds2: selectedRowKeys}))}}
                      getColumns={[]}
              />):(<WeaTable
                      comsWeaTableStore={oauth2Store.tableStore3}
                      hasOrder={true}
                      needScroll={true}
                      onOperatesClick={this.onOperatesClick.bind(this)}
                      // uniqueId={true}
                      getColumns={[]}
                      rowSelection={{onChange: (selectedRowKeys) => {}}}
              />))
          }
        </WeaNewScroll>
        <AppDataMappingEditDialog/>
        <AppDataMappingImportDialog/>
        <AppDataMappingImportResultDialog/>
      </WeaRightMenu>

    </WeaDialog>
  }

  getAdvancedSearch = () => {
    const { oauth2Store } = this.props;
    const {searchForm2, status} = oauth2Store;
    const {showSearchAd, selectedKey, condition2} = toJS(status);
    let btns = [];
    btns = IntegrationUtil.getAdvancedSearchs(
      searchForm2,
      condition2,
      false,
      2
    );
    return btns;
  };

  getTabButtonsAd() {
    const { oauth2Store } = this.props;
    const { selectedKey } = toJS(oauth2Store.status);
    let btns = [
      <Button
        type="primary"
        onClick={() => {
          let params={id:oauth2Store.registerAppId}
          oauth2Store.getRegisterAppDataMappingList(params);
          oauth2Store.setState({ showSearchAd2: false });
        }}
      >
        {getLabel(197, "搜索")}
      </Button>,
      <Button type="ghost" onClick={() => oauth2Store.searchForm2.reset()}>
        {getLabel(2022, "重置")}
      </Button>,
      <Button type="ghost" onClick={() => oauth2Store.setState({ showSearchAd2: false })}>{getLabel(31129, "取消")}</Button>
    ];
    return btns;
  }

  getTabButton = () => {
    const {oauth2Store} = this.props;
    let {rightMenus2,rowSelectIds2} = toJS(oauth2Store.status);
    let btnArr = [];
    let rightDis = 0;
    if(!rightMenus2){return btnArr}
    for (let j = 0, len = rightMenus2.length; j < len; j++) {
      if (j == 4) {
        break
      }
      if(j == 2) {
        rightDis = 15;
      }
      let m = rightMenus2[j];
      let btn = <Button style={{marginRight:rightDis}} type="primary" disabled={m.menuIcon === 'icon-coms-delete' && rowSelectIds2.length === 0} onClick={() => {{this.onRightMenuClick(m.type);}}}>{`${m.menuName}`}</Button>;
      btnArr.push(btn);
    }
    // console.log("btnArr:",btnArr);
    return btnArr;
  };

  getColumnsInfo = (data) => {
    const that = this;
    if (!isEmpty(data)) {
      for (let index = 0; index < data.length; index++) {
        if (data[index].dbField == 'setname') {
          data[index].render = (text, record, index) => {
            return (<a onClick={that.doEditDetailById.bind(that, record)}>{record.setname}</a>);

          }
        }
      }
    }
  }

  getSearch3=()=>{
    const {oauth2Store} = this.props;

    return (
      <WeaTable
        comsWeaTableStore={oauth2Store.tableStore3}
        hasOrder={true}
        needScroll={true}
        onOperatesClick={this.onOperatesClick.bind(this)}
        uniqueId={true}
        getColumns={[]}
        rowSelection={{onChange: (selectedRowKeys) => {}}}
      />
    )
  }

  getSearch2=()=>{
    const {oauth2Store} = this.props;
  
    return (

      <WeaTable
        comsWeaTableStore={oauth2Store.tableStore2}
        hasOrder={true}
        needScroll={true}
        onOperatesClick={this.onOperatesClick.bind(this)}
        // uniqueId={true}
        rowSelection={{onChange: selectedRowKeys => (oauth2Store.setState({rowSelectIds2: selectedRowKeys}))}}
        getColumns={[]}
      />
      )
  }

  getSearch1=()=>{
    {
      const {oauth2Store} = this.props;
      const status = toJS(oauth2Store.status);
      let group = [];
      oauth2Store.registerAppEditForm.render({col: 1},{
        onChange: (v)=> {},
        isHide: (key, formParams) => {}

      },true,(c, idx)=>{
        if(idx==0){
          let items = [];
          let form = oauth2Store.registerAppEditForm;
          let formParams = form.getFormParams();
          c.items.map(fields => {
            items.push({
              com: (
                <WeaFormItem
                  label={`${fields.label}`}
                  labelCol={{span: `${fields.labelcol}`}}
                  wrapperCol={{span: `${fields.fieldcol}`}}
                  error={form.getError(fields)}
                  tipPosition="bottom"
                >
                  <nobr>
                    <WeaSwitch fieldConfig={fields} form={form} formParams={formParams} />
                  </nobr>

                </WeaFormItem>),
              colSpan: 1,
              hide: form.isHide(fields, (key, formParams) => {
                let hide = false;
                if ('definebroswerType' == key && formParams.account_rules !== '7') {
                  hide = true;
                }
                return hide;
              }),
              onChange: (v)=> {
                // console.log(v);
              }
            })
          });

          group.push(<WeaSearchGroup center={true}  col={1}  needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        }
      })
      return group;
    }
  }

  getRightMenu = () => {
    const {oauth2Store} = this.props;
    let {rightMenus2,rowSelectIds2} = toJS(oauth2Store.status);
    let btnArr = [];
    if(oauth2Store.editDetailDialogSelectedKey==0) {
      btnArr=[
        {
          key: 'BTN_SAVE',
          icon: <i className='icon-coms-Preservation'/>,
          content : `${getLabel(86,'保存')}`,
          onClick : () => {this.onRightMenuClick('BTN_SAVE')}
        }
      ];
    }else if(oauth2Store.editDetailDialogSelectedKey==1) {
      btnArr = [];
      rightMenus2&&rightMenus2.map(m => {
        var btn= {
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          onClick: () => this.onRightMenuClick(m.type),
          disabled: m.menuIcon==='icon-coms-delete' && rowSelectIds2.length === 0
        } ;
        btnArr.push(btn);
        // if(! (m.menuIcon==='icon-coms-delete' && rowSelectIds2.length === 0)){
        //   btnArr.push(btn);
        // }
      });
      btnArr.push({
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom" />,
        content: `${getLabel(32535, "显示列定制")}`,
        onClick: () => this.onRightMenuClick("BTN_COLUMN")
      });
    }

    return btnArr;
  }

  ipv6Test = (value) => {
    let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
    let regV4 = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/

    let datas = value.split(',');
    for(let i = 0; i < datas.length; i++) {
      if(!reg.test(datas[i].trim()) && (!regV4.test(datas[i].trim()))) {
        return false;
      }
    }
    return true;
  }

  onRightMenuClick = (type) => {
    const {oauth2Store} = this.props;
    const {registerAppEditForm, status} = oauth2Store;
    const {rowSelectIds2} = toJS(oauth2Store.status);
    if(type == 'BTN_SAVE'){
      let value = registerAppEditForm.getFormParams().allow_ip;
      let ipv6 = this.ipv6Test(value.trim());

      IntegrationUtil.onCheck(registerAppEditForm,function () {           
        if(value.trim() == '' || (value.trim() && ipv6)) {
          //合并hiddenfield参数
          let id=oauth2Store.registerAppId;
          let params = Object.assign({id:id,operation:"edit"}, registerAppEditForm.getFormParams());
          oauth2Store.getRegisterAppOperation(params);
        }else {
          registerAppEditForm.showError('allow_ip',getLabel('382232','应用服务器地址非法'));
        }
      });

    }

    if(type == 'rb_1'){
      //注册数据映射
      this.doDataMappingEditById({randomField0: '',appid:registerAppEditForm.getFormParams().appid});
    }

    if(type == 'rb_2'){
      //导入
      oauth2Store.registerAppDataMappingImportForm.reset();
      let id=oauth2Store.registerAppId;
      let params = Object.assign({id:id,operation:"import"}, registerAppEditForm.getFormParams());
      oauth2Store.getRegisterAppDataMappingImportForm(params);
      oauth2Store.setState({ appEditFormDetailDataMappingImportDialogVisible: true });

    }
    if(type == 'rb_3'){
      //删除
      if(rowSelectIds2.length>0) {
        oauth2Store.confirmModal(`${getLabel(385625, '确定要删除选择的记录吗？')}`, oauth2Store.getRegisterAppDataMappingOperation, {operation:'delete',id: rowSelectIds2});
      }
    }

  }

  onOperatesClick = (record, index, operate) => {
    const { oauth2Store } = this.props;
    const { selectedKey } = toJS(oauth2Store.status);
    if (operate.index == "0") {
      this.doDataMappingEditById(record);
    }
    if (operate.index == "1") {
      //删除
      oauth2Store.confirmModal(`${getLabel(15097, '确定要删除吗？')}`, oauth2Store.getRegisterAppDataMappingOperation, {operation:'delete',id: record.randomField0});
    }
  };

  doDataMappingEditById(record) {
    const { oauth2Store } = this.props;
    const { registerAppEditForm } = oauth2Store;
    oauth2Store.registerAppDataMappingEditForm.reset();
    oauth2Store.setOperateDataMappingIndex(record.randomField0);
    oauth2Store.getRegisterAppDataMappingEditForm({ id: record.randomField0,appid:record.appid ,account_rules:registerAppEditForm.getFormParams().account_rules});
    oauth2Store.setState({ appEditFormDetailDataMappingDialogVisible: true });
  }

}
