import React from "react";
import { 
  inject, 
  observer, 
} from "mobx-react";
import { 
  toJS, 
} from "mobx";
import { 
  Button, 
  message, 
} from "antd";
import {
  WeaLocaleProvider,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaFormItem,
  WeaSearchGroup,
  WeaHelpfulTip,
  WeaLeftRightLayout,
} from "ecCom";
import { 
  WeaTableNew, 
  WeaSwitch, 
} from "comsMobx";
import {
  onCheck,
  getAdvancedItem,
  getSearchBtns,
  doConfirm,
} from "../../util/IntegrationUtil";
import NewForm from "./NewForm";
import NewDetailForm from "./NewDetailForm";
import NoRight from "../../public/NoRight";
import NonStand from "../../public/NonStand";
import OrganizationTree from '../../public/OrganizationTree';

const {WeaTable} = WeaTableNew;
const {getLabel} = WeaLocaleProvider;

@inject("triggerStore")
@observer
export default class Trigger extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      marginLeftDis: -390,
      bottomDis: 7,
      styleSheet: 'labeldeyangshi',
    };
    //来自其他入口
    let queryString = toJS(this.props.location.query);
    if(queryString && queryString.from){
      this.state = {
        from: queryString.from,
      }
    }else {
      this.from = '';
    }
  }

  componentWillMount() {
    const {triggerStore} = this.props;
    let paramsIndex = location.href.trim() && location.href.trim().indexOf('?');
    if((paramsIndex != -1) && (location.href.trim().indexOf('typename') > paramsIndex) && (location.href.trim().indexOf('from=productEntrance') > paramsIndex)) {
      let url = location.href.split('?')[1];
      if(url) {
        let params = url.split('&');
        let query = {};
        for(let i = 0; i < params.length; i++) {
          query[params[i].split('=')[0]] = params[i].split('=')[1];
        }
        triggerStore.source = (query.typename ? query.typename : "");
      }else {
        triggerStore.source = "";
      }
    }else {
      triggerStore.source = "";
    }
  }

  componentDidMount() {
    this.props.triggerStore.doInit();
  }

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

  getBtns = () => {
    const { 
      triggerStore 
    } = this.props, {
      status,
      tableStore,
      tableStoreLog,
    } = triggerStore, { 
      selectedKey,
      rightMenus,
      rightMenusLog, 
    } = toJS(status);
    if (selectedKey == 0) {
      return rightMenus && rightMenus.map(m => 
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@j81to1@integrationWorkflowTriggerButton${m.type}`} type="primary" disabled={m.menuIcon==='icon-coms-delete' && toJS(tableStore.selectedRowKeys).length === 0} onClick={() => this.onRightMenuClick(m.type)}>{m.menuName}</Button>
      );
    }else if (selectedKey == 1) {
      return [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@dseizd@integrationWorkflowTriggerButtonSave`} type="primary" onClick={() => this.onRightMenuClick('BTN_INTERVAL_SAVE')}>{getLabel(30986, "保存")}</Button>];
    }else if (selectedKey == 2) {
      return rightMenusLog && rightMenusLog.map(m => 
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fcyv88@integrationWorkflowTriggerButton${m.type}`} type="primary" disabled={m.menuIcon==='icon-coms-delete' && toJS(tableStoreLog.selectedRowKeys).length === 0} onClick={() => this.onRightMenuClick(m.type)}>{m.menuName}</Button>
      );
    }
  };

  getRightMenu = () => {
    const { 
      triggerStore, 
    } = this.props, {
      status,
      tableStore,
      tableStoreLog,
    } = triggerStore, { 
      selectedKey,
      rightMenus,
      rightMenusLog,
    } = toJS(status);
    let btnArr = [];
    if(selectedKey == 0) {
      btnArr = rightMenus && rightMenus.map(m => {
        return {
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          onClick: () => this.onRightMenuClick(m.type),
          disabled: m.menuIcon === 'icon-coms-delete' && toJS(tableStore.selectedRowKeys).length === 0,
        };
      });
    }else if(selectedKey == 1) {
      btnArr.push({
        key: "BTN_INTERVAL_SAVE",
        icon: <i className="icon-coms-Preservation" />,
        content: getLabel(30986, "保存"),
        onClick: () => this.onRightMenuClick("BTN_INTERVAL_SAVE")
      });
    }else {
      btnArr = rightMenusLog && rightMenusLog.map(m => {
        return {
          key: m.type,
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
          onClick: () => this.onRightMenuClick(m.type),
          disabled: m.menuIcon === 'icon-coms-delete' && toJS(tableStoreLog.selectedRowKeys).length === 0
        };
      });
    }
    if(selectedKey != 1) {
        //显示列定制
      btnArr.push({
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom" />,
        content: getLabel(32535, "显示列定制"),
        onClick: () => this.onRightMenuClick("BTN_COLUMN")
      });
    }
    return btnArr;
  }

  onRightMenuClick = (type, record) => {
    const { 
      triggerStore 
    } = this.props, {
      triggerIntervalForm, 
      status,
      tableStore,
      tableStoreLog,
    } = triggerStore, {
      selectedKey, 
    } = toJS(status);
    if (type == "BTN_NEW" || type=="rb_1") {
      triggerStore.getTriggerAddForm({viewid: ""});
      triggerStore.setState({ showNewFormDialog: true });
    }else if (type == "rb_2" || (selectedKey == 0 && type == "2")) {
      let title = "", ids = "";
      if(type == "rb_2") {
        title = getLabel(385625, '确定要删除选择的记录吗？');
        ids = toJS(tableStore.selectedRowKeys);
      } else {
        title = getLabel(15097, '确定要删除吗？');
        ids = record.randomFieldId;
      }
      doConfirm(
        title, 
        triggerStore.getTriggerOperation, 
        {operate:'delete', deteteviewid: ids}
      );
    }else if (type == "rb_delLog" || (selectedKey == 2 && type == "0")) {
      let title = "", ids = "";
      if(type == "rb_delLog") {
        title = getLabel(385625, '确定要删除选择的记录吗？');
        ids = toJS(tableStoreLog.selectedRowKeys);
      } else {
        title = getLabel(15097, '确定要删除吗？');
        ids = record.randomFieldId;
      }
      doConfirm(
        title, 
        triggerStore.getTriggerOperation, 
        {operate:'deleteLog', deteteviewid: ids}
      );
    }else if (type == "BTN_INTERVAL_SAVE") {
        //触发周期设置保存
        onCheck(triggerIntervalForm, () => {
            let p = triggerIntervalForm.getFormParams().periodvalue;
            if(p[0] && p[0] != '') {
                switch(p[0]) {
                    case '1': 
                    let minutes = p[1] || '';
                    if(!(/^[1-5]\d{0,1}$/.test(Number(minutes)) || /^[1-9]$/.test(Number(minutes)) )) {
                        triggerIntervalForm.showError('periodvalue', getLabel('390590',"有效范围为1-59的整数 "));
                        return;
                    };
                    break;
                    case '2':
                    let hours = p[1] || '';
                    if(!(/^(1\d?)$/.test(Number(hours)) || /^(2[0-3])$/.test(Number(hours)) || /^[1-9]$/.test(Number(hours)))) {
                        triggerIntervalForm.showError('periodvalue', getLabel('390591',"有效范围为1-23的整数 "));
                        return;
                    }
                    break;
                    case '3':
                    let periodvalue = p[1];
                    if(!periodvalue) {
                        triggerIntervalForm.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                        return;
                    }
                    break;
                    case '4':
                    if(!p[2]) {
                        triggerIntervalForm.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                        return;
                    }
                    break;
                    case '5':
                    let days = p[2] || '';
                    if(!(/^(1\d?)$/.test(Number(days)) || /^2[0-7]$/.test(Number(days)) || /^[1-9]$/.test(Number(days)))) {
                        triggerIntervalForm.showError('periodvalue', getLabel('390592',"有效范围为1-27的整数 "));
                        return;
                    }
                    if(!p[3]) {
                        triggerIntervalForm.showError('periodvalue', getLabel('391056','"请选择时间"未填写'));
                        return;
                    }
                }
            }
            triggerStore.getTriggerOperation({operate:'INTERVAL_SAVE',scope:-1,periodvalue:p[1]||"",type:p[0]||"",value2:p[2]||"",value3:p[3]||""})
        })
    }else if (type == "BTN_COLUMN") {
      if(selectedKey == 0) {
        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
      }else if(selectedKey == 2){
        tableStoreLog.setColSetVisible(true);
        tableStoreLog.tableColSet(true);
      }
    }else if (selectedKey == 0 && type == "0") {
      triggerStore.getTriggerOperation({operate: 'test',viewid: record.randomFieldId}, (result)=>{
        if(result.errmsgTip) {
          if(result.isError) {
            message.error(result.errmsgTip);
          } else {
            message.success(result.errmsgTip);
          }
        }
      });
    }else if (selectedKey == 0 && type == "1") {
      triggerStore.setSetRettingRegisterID(record.randomFieldId);
      if(record.randomFieldId != '') {
        // triggerStore.getTriggerOperation({operate: "getDatasource"});
        triggerStore.getTriggerCheckWorkflowForm({viewid: record.randomFieldId});
      }
      triggerStore.getTriggerAddForm({viewid: record.randomFieldId});
      triggerStore.setState({showNewDetailFormDialog: true, newDetailFormSelectedKey: 0});
    }
  };

  getAdvancedSearch = () => {
    const { 
      triggerStore,
    } = this.props, {
      searchForm,
      searchFormLog,
      status,
    } = triggerStore, {
      selectedKey,
      TriggerConditionInfo,
      TriggerConditionInfoLog,
    } = toJS(status);
    if(selectedKey == 0) {
      return getAdvancedItem(
        searchForm, 
        TriggerConditionInfo, 
        this.handleSearchFun,
        false,
        this && this.props && this.props.ecId || '', 
        "integrationWorkflowTrigger",
      );
    }else if(selectedKey==2) {
      return getAdvancedItem(
        searchFormLog, 
        TriggerConditionInfoLog, 
        this.handleSearchFun,
        false,
        this && this.props && this.props.ecId || '', 
        "integrationWorkflowTrigger",
      );
    }
    return null;
  };

  handleSearchFun = () => {
    const { triggerStore } = this.props;
    const { selectedKey } = toJS(triggerStore.status);
    if(selectedKey == 0) {
      triggerStore.setState({ 
        showSearchAd: false,
        subcompanyid: triggerStore.searchForm.getFormParams().subcompanyid1,
      });
      triggerStore.getTriggerListInfo();
    }else if(selectedKey == 2) {
      triggerStore.setState({ 
        showSearchAd: false,
        subcompanyid: triggerStore.searchFormLog.getFormParams().subcompanyid1,
       });
      triggerStore.getTriggerLogListInfo();
    }
  }

  getTabButtonsAd = () => {
    const { 
      triggerStore,
    } = this.props, { 
      selectedKey, 
    } = toJS(triggerStore.status);
    return getSearchBtns(
      this.handleSearchFun,
      () => selectedKey==0 ? triggerStore.searchForm.reset() : triggerStore.searchFormLog.reset(),
      () => triggerStore.setState({showSearchAd: false}),
      this && this.props && this.props.ecId || '', 
      "integrationWorkflowTrigger",
    );
  }

  onOperatesClick = (record, index, operate, flag) => {
    this.onRightMenuClick(operate.index, record);
  };

  getColumnsInfo = (data) => {
    const {
      triggerStore,
    } = this.props, {
      selectedKey,
    } = toJS(triggerStore.status);
   
    return data && data.map(item => {
      if(item.dbField === "setname" && selectedKey == 0) {
        item.render = (text, record) => <a onClick={() => this.onRightMenuClick("1", record)}>{record.setname}</a>;
      } else if(item.dbField == 'subcompanyid') {
        item.render = (text, record) => <a href={`${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${record.subcompanyid}`} target="_blank">{record.subcompanyidspan}</a>;
      }
      return item;
    });
  }

  getTab2Form = () => {
    const {triggerStore} = this.props;
    const {triggerIntervalForm, status} = triggerStore;
    const {TriggerIntervalFormFields} = toJS(status);
    const {isFormInit} = triggerIntervalForm;
    let group = [];
    const formParams = triggerIntervalForm.getFormParams();
    isFormInit && TriggerIntervalFormFields && TriggerIntervalFormFields.map((c, index) =>{
        let items = [];
        c.items.map(fields => {
            items.push({
                com:(
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@d60ifw@integrationWorkflowTriggerForm${fields.domkey[0]}`}
                        label={`${fields.label}`}
                        labelCol={{span: `${fields.labelcol}`}}
                        wrapperCol={{span: `${fields.fieldcol}`}}
                        error={triggerIntervalForm.getError(fields)}
                        tipPosition="bottom"
                    >
                        <nobr>
                            <div className={this.state.styleSheet}>
                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@zq9jsq@integrationWorkflowTriggerForm${fields.domkey[0]}`} fieldConfig={fields} form={triggerIntervalForm} formParams={formParams}  onChange={v=> {
                                if(fields.domkey[0] == 'periodvalue') {
                                    let timer = triggerIntervalForm.getFormParams().periodvalue;
                                    if(timer[0] == '1' || timer[0] == '2') {
                                        this.setState({marginLeftDis: -350, bottomDis: 7, styleSheet: 'labeldeyangshi'});
                                    }else if(timer[0] == '3') {
                                        this.setState({marginLeftDis: -290, bottomDis: 10, styleSheet: 'meitiandeyangshi'})
                                    }else if(timer[0] == '4') {
                                        this.setState({marginLeftDis: -210, bottomDis: 7, styleSheet: 'meizhoudeyangshi'})
                                    }else if(timer[0] == '5') {
                                        this.setState({marginLeftDis: 0, bottomDis: 8, styleSheet: 'meiyuedeyangshi'})
                                    }else if(timer[0] == '0') {
                                        this.setState({marginLeftDis: -500, bottomDis: 8, styleSheet: 'buchufayangshi'})
                                    }
                                }
                            }} />
                            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@h2b5kl@integrationWorkflowTriggerForm${fields.domkey[0]}`} style={{marginLeft:this.state.marginLeftDis, position: 'absolute', bottom: this.state.bottomDis}}
                                            width={170}
                                            title={getLabel('519107','更改后立即生效；为空，意为不设置。')}
                            /></div>
                        </nobr>
                    </WeaFormItem>),
                colSpan: 1,
            });

        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ba8818@integrationWorkflowTriggerForm${index}`} center  col={1}  needTigger={true} title={c.title}  showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  }

  handleSearchChange = (value) => {
    const {
      triggerStore,
    } = this.props, {
      searchForm,
      searchFormLog,
      status,
    } = triggerStore, {
      selectedKey,
    } = toJS(status);
    if(0 == selectedKey) {
      searchForm.updateFields({setname: value});
    } else if(2 == selectedKey) {
      searchFormLog.updateFields({requestname: value});
    }
  }

  handleChangeTab = (v) => {
    const {
      triggerStore,
    } = this.props;
    triggerStore.setState({
      subcompanyid: "",
      selectedKey: v,
    });
    if(v == 0) {
      triggerStore.getTriggerCondition({}, triggerStore.getTriggerListInfo); 
    } else if(v == 1) {
      triggerStore.getTriggerIntervalSetForm();
    } else if(v == 2) {
      triggerStore.getTriggerLogCondition({}, triggerStore.getTriggerLogListInfo);
    }
  }

  // 分权刷新
  refreshData = (id, type) => {
    const {
      triggerStore
    } = this.props, {
      selectedKey,
    } = toJS(triggerStore.status);
    // 如果点击的是分部
    if("1" === type) {
      triggerStore.setState({
        subcompanyid: id  
      })
    } else{
      triggerStore.setState({
        subcompanyid: ""  
      })
    }
    if(selectedKey == 0) {
      triggerStore.getTriggerCondition({}, triggerStore.getTriggerListInfo);
    } else if(selectedKey == 2) {
      triggerStore.getTriggerLogCondition({}, triggerStore.getTriggerLogListInfo);
    }
  }

  getTitle = () => {
    if(this.state.from == "productEntrance") {
      return getLabel(31698, "流程创建");
    }else{
      return getLabel(33720, "流程触发集成");
    } 
  }

  render() {
    const { 
      triggerStore 
    } = this.props, {
      searchForm,
      searchFormLog,
      tableStore,
      tableStoreLog,
      status,
      hasRight,
      rightLoading,
      hasManageDetachableRight,
    } = triggerStore, {
      showSearchAd,
      selectedKey,
      hasNonStandard,
      nonStandLoading,
      collectParams,
      tabDatas,
      advanceHeight,
      hasOrganization,
      subcompanyid,
    } = toJS(status);

    return (nonStandLoading
      ? null
      : hasNonStandard
        ? rightLoading 
          ? null
          : hasRight
            ? <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@5zjo1r`}
                datas={((selectedKey == 0 || selectedKey == 2) && (!hasManageDetachableRight)) ? [] : this.getRightMenu()}
                collectParams={collectParams}
              >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@t5f9rg`}
                  title={this.getTitle()}
                  icon={<i className="icon-coms-integration" />}
                  iconBgcolor="#1a57a0"
                  buttons={((selectedKey == 0 || selectedKey == 2) && (!hasManageDetachableRight)) ? [] : this.getBtns()}
                  showDropIcon={true}
                  dropMenuDatas={((selectedKey == 0 || selectedKey == 2) && (!hasManageDetachableRight)) ? [] : this.getRightMenu()}
                  dropMenuProps={{collectParams}}
                />
                <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@v28ibb`}
                    showLeft={selectedKey != 1 && hasOrganization && hasManageDetachableRight}
                    showBtn={selectedKey != 1 && hasOrganization && hasManageDetachableRight}
                    leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@lqj336`} 
                      ref="workflowtrigger"
                      selectedKeys={[subcompanyid]}
                      refreshData={this.refreshData}
                      rightStr={"intergration:automaticsetting"}
                      {...(this.props.orgTreeParams || {})} 
                    />}
                >
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@dljm3v`}
                    datas={tabDatas}
                    keyParam="viewcondition" 
                    selectedKey={selectedKey}
                    searchType={(selectedKey != 1 && hasManageDetachableRight) ? ['base','advanced'] : []}
                    searchsBaseValue={selectedKey == 0 ? searchForm.getFormParams().setname : selectedKey == 2 ? searchFormLog.getFormParams().requestname : ""}
                    advanceHeight={advanceHeight}
                    searchsAd={this.getAdvancedSearch()}
                    showSearchAd={showSearchAd}
                    buttonsAd={this.getTabButtonsAd()}
                    setShowSearchAd={() => triggerStore.setState({showSearchAd: !showSearchAd})}
                    hideSearchAd={() => triggerStore.setState({showSearchAd: false})}
                    onChange={this.handleChangeTab}
                    onSearch={this.handleSearchFun}
                    onSearchChange={this.handleSearchChange}
                  />
                  {
                    selectedKey == 1
                        ? this.getTab2Form()
                        : hasManageDetachableRight
                          ? <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@iyx6aj`}
                              key={selectedKey}
                              getColumns={this.getColumnsInfo}
                              comsWeaTableStore={selectedKey == 0 ? tableStore : tableStoreLog}
                              hasOrder={true}
                              needScroll={true}
                              onOperatesClick={this.onOperatesClick}
                            />
                          : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@x7ksup`} />
                  }
                </WeaLeftRightLayout>
                <NewForm ecId={`${this && this.props && this.props.ecId || ''}_NewForm@vuvp4e`}/> 
                <NewDetailForm ecId={`${this && this.props && this.props.ecId || ''}_NewDetailForm@20qvd4`}/>
              </WeaRightMenu>
            : <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@qki39b`} />
        : <NonStand ecId={`${this && this.props && this.props.ecId || ''}_NonStand@sbl2jh`} />                    
    );
  }
}