import React from 'react';
import {toJS} from 'mobx';
import {inject, observer} from "mobx-react";
import {Button, Spin} from 'antd';
import {WeaDialog, WeaRightMenu, WeaLocaleProvider, WeaSearchGroup, WeaTable, WeaLeftRightLayout, WeaFieldTemplateSelect, WeaTextarea} from 'ecCom';
import {GeneralTitleColor, menuIcon} from "../../util/IntegrationUtil";

const {getLabel} = WeaLocaleProvider;

@inject("todoCenterStore")
@observer
export default class SMSTemplate extends React.Component { 
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false,
      title: getLabel('514719','短信提醒模板')
    }
  }

  componentWillUnmount() {
    this.props.todoCenterStore.setState({
      selectedRowKeys: [],
      smsDatas: [],
      selectedRowKeysName: "",
      remindContentValue: ""
    })
  }

  /**
   * 右键菜单
   */
  getRightMenu = () => {
    return [{
      key: 'BTN_SAVE',
      icon: menuIcon.save,
      content: getLabel(86,'保存'),
      disabled: this.props.todoCenterStore.status.buttonLoading,
      onClick: () => this.onRightMenuClick('BTN_SAVE')
    }, {
      key: 'BTN_RESET',
      icon: menuIcon.save,
      content: getLabel('385270','恢复默认设置'),
      disabled: this.props.todoCenterStore.status.buttonLoading,
      onClick: () => this.onRightMenuClick('BTN_RESET')
    }]
  }

  getBtns = () => {
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@xvmxcm@integrationTodoCenterEditDetailButtonSave`} type="primary" disabled={this.props.todoCenterStore.status.buttonLoading} onClick={()=> this.onRightMenuClick('BTN_SAVE')}>{getLabel(86,'保存')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@te8lcv@integrationTodoCenterEditDetailButtonReset`} type="primary" disabled={this.props.todoCenterStore.status.buttonLoading} onClick={()=> this.onRightMenuClick('BTN_RESET')}>{getLabel('385270','恢复默认设置')}</Button>
    ];
  }

  /**
   * menuClick事件
   */
  onRightMenuClick = (type) => {
    const {todoCenterStore} = this.props;
    const {status: {
      selectedRowKeys, 
      remindContentValue, 
      remindTypeValue,
      ofsInfoEditDetailDialogVisible
    }, resetSmstemplate, saveSmstemplate, ofsInfoAddForm} = todoCenterStore;
    const id = toJS(selectedRowKeys);
    if(["BTN_SAVE"].includes(type)) {
      let params = {
        id,
        type: remindTypeValue,
        content: remindContentValue
      };
      if(ofsInfoEditDetailDialogVisible) {
        params = {...params, syscode: ofsInfoAddForm.getFormParams().syscode};
      }
      saveSmstemplate(params);
    }else if(type === "BTN_RESET") {
      let params = {
        id,
        type: remindTypeValue
      };
      if(ofsInfoEditDetailDialogVisible) {
        params = {...params, syscode: ofsInfoAddForm.getFormParams().syscode};
      }
      resetSmstemplate(params);
    }
  }

  onSelect = (record, selected) => {
    const {todoCenterStore} = this.props;
    if(selected) {
      todoCenterStore.setState({
        selectedRowKeys: [record.key],
        selectedRowKeysName: record.remindType,
        remindContentValue: record.remindContent,
        remindTypeValue: record.remindTypeValue
      });
    }
  }

  onFieldTemplateSelect = (key, showname) => {
    const {todoCenterStore} = this.props;
    let {remindContentValue} = toJS(todoCenterStore.status);
    const remindContent = this.refs.remindContent;
    if(remindContent){
      try{
        const dom = remindContent.refs.textareaNormal.refs.input.refs.input;
        const selectionStart = dom.selectionStart;
        const selectionEnd = dom.selectionEnd;
        showname = '$' + showname + '$';
        let value = dom.value.substring(0, selectionStart) + showname + dom.value.substring(selectionStart, dom.value.length);
        todoCenterStore.setState({remindContentValue: value});
        setTimeout(()=>{
          dom.focus();
          dom.setSelectionRange(selectionStart+showname.length, selectionEnd+showname.length);
        },0)
      }catch(err) {
        showname = '$' + showname + '$';
        showname = remindContentValue + showname;
        todoCenterStore.setState({remindContentValue: showname});
      }
    }
  }

  render () {
    const {todoCenterStore} = this.props;
    const {status} = todoCenterStore;
    const {smsTemplateVisible, dialogLoading, buttonLoading, smsColumns, smsDatas, smsFields, selectedRowKeys, selectedRowKeysName, remindContentValue} = toJS(status);
    const {title} = this.state;

    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@bqfilh`}
      visible={smsTemplateVisible}
      title={title}
      onCancel={()=> todoCenterStore.setState({smsTemplateVisible: false})}
      style={{width: 800, height: 600}}
      hasScroll
      moduleName={GeneralTitleColor.moduleName}
      buttons={this.getBtns()}
      moreBtn={{
        datas: this.getRightMenu(),
        collectParams: []
      }}
    >
      {
        dialogLoading 
          ? <div style={{position: "relative", top: "50%"}}>
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@6uns7n`} spinning={dialogLoading}> </Spin>
            </div>
          : <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@1qpl5j`}
              datas={this.getRightMenu()}
              collectParams={{}}
            >
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@brlkvv`} spinning={buttonLoading}>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@1jj2bg`} title={`${getLabel('19480','内容设置')}${selectedRowKeysName ? '-' : ''}${selectedRowKeysName ? selectedRowKeysName : ""}`} showGroup={true}>
                    <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@inh15v`}
                        leftCom={<WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@yzqkhr`}
                            id={'remindContent'}
                            ref={'remindContent'}
                            value={remindContentValue}
                            stringLength={200}
                            onChange={(v)=> todoCenterStore.setState({remindContentValue: v})}
                            minRows={17}
                            maxRows={17}
                        />}
                        showBtn={false}
                        leftWidth={570}
                    >
                        <WeaFieldTemplateSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaFieldTemplateSelect@wsurtu`}
                            options={selectedRowKeys && selectedRowKeys.length > 0 ? smsFields : []}
                            searchValue={''}
                            ifAllowOnlyOneClick={false}
                            scrolledHeight={292}
                            onClick={(key, showname) => this.onFieldTemplateSelect(key,showname)}
                        />
                    </WeaLeftRightLayout>
                </WeaSearchGroup>

                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@0sqtus`} title={`${getLabel('82212','提醒类型')}(${getLabel('514724','点击列表行可修改提醒内容')})`} showGroup = {true}>
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@rs2li0`}
                        pagination={false}
                        columns={smsColumns}
                        dataSource={smsDatas}
                        rowSelection={{
                          type: 'radio',
                          selectedRowKeys: selectedRowKeys,
                          onSelect: this.onSelect
                        }}
                    />
                </WeaSearchGroup>
              </Spin>
            </WeaRightMenu>
      }
    </WeaDialog>
  }
}