import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Modal, Spin } from "antd";
import {
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaTableEditable,
  WeaTools,
  WeaCron,
  WeaFormItem,
  WeaInput,
  WeaDialog,
  WeaRightMenu
} from "ecCom";
import {WeaSwitch} from 'comsMobx'
import { onCheck } from "../../util/index.js";
import "../../util/croneLang.js";
import {checkTableFieldValueUnique}  from "../../apis/CommonService";
import * as IntegrationUtil from "../../util/IntegrationUtil.js";

require("../../public/jquery-ui.js");
require("../../public/jquery.croneditor.js");

const {getLabel} = WeaLocaleProvider;
const { getKey } = WeaTools;

@inject("schedule")
@observer
export default class AddOrEditTask extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editTableSelected: [],
    };
  }

  getBtns = () => {
    const { 
      createTask, 
      loading 
    } = this.props.schedule, { 
      menus=[] 
    } = createTask;

    return menus && menus.map(item => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@627f1b@integrationScheduleButton${item.key}`} type="primary" disabled={loading} onClick={() => this.onMenuClick(item.key)}>{item.content}</Button>);
  };

  getRightMenu = () => {
    const { 
      createTask, 
      loading 
    } = this.props.schedule, { 
      menus=[] 
    } = createTask;

    return menus && menus.map(item => {
      return {
        disabled: loading,
        key: item.key,
        icon: <i className="icon-coms-Preservation" />,
        content: item.content,
        onClick: () => this.onMenuClick(item.key)
      }
    });
  };

  onMenuClick = (type) => {
    const {schedule} = this.props;
    const {createTask, tableEditDatas, insert, update} = schedule;
    const {form, editData, isEdit} = createTask;
    const formParams = form.getFormParams();
    let datas = toJS(tableEditDatas);
    let checkParams = {
      tableName: 'schedulesetting',
      fieldName: 'pointid',
      fieldValue: formParams.pointid.replace(/^(\s*)|(\s*)$/g, ''),
      idName: 'id',
      idValue: ''
    };

    onCheck(form, () => {
      if(this.table.doValidate().pass) {
        checkTableFieldValueUnique(checkParams).then(result => {
          if(result && result.isNotUnique && (!isEdit)) {
            form.showError('pointid',getLabel('387654','标识已存在'));
          }else {
            if(type === "BTN_ADD") {
              insert({params: formParams, WeaTableEdit: JSON.stringify(datas)});
            }else if(type === "BTN_EDIT") {
              update({...formParams, id: editData.id, runstatus: editData.runstatus, WeaTableEdit: JSON.stringify(datas)});
            }
          }
      });
      }
    })
  }

  willDelete = (datas, keys) => {
    const { schedule } = this.props;
    Modal.confirm({
      content: `${getLabel(385625, '确定要删除选择的记录吗？')}`,
      onOk: () => {
        this.setState({
          editTableSelected: []
        });
        schedule.tableEditDatas = datas;
      },
      onCancel: () => {}
    }) 
  }

  getSearchs = (form, datas, needTigger = true, centerFlag=true) => {
    const {flag} = this.props.schedule;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && datas && datas.map((c, index) => {
      let items = [];
      c && c.items && c.items.map(fields => {
        items.push({
          com: (<div style={{marginLeft: centerFlag ? 0 : -20, marginRight: centerFlag ? 0 : -20}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@zj99vs@integrationScheduleAddForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: fields.labelcol }}
              wrapperCol={{ span: fields.fieldcol }}
              fieldType={fields.conditionType.toUpperCase()}
              error={form.getError(fields)}
              tipPosition="bottom"
            >
              {
                getKey(fields) != 'cronexpr' 
                  ? <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3l23lt@integrationScheduleAddForm${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onChange={v => {
                      if(getKey(fields) === 'pointid') {
                        let checkParams = {
                            tableName: 'schedulesetting',
                            fieldName: 'pointid',
                            fieldValue: form.getFormParams().pointid.replace(/^(\s*)|(\s*)$/g, ''),
                            idName: 'id',
                            idValue: ''
                        };
                        checkTableFieldValueUnique(checkParams).then(result => {
                            if(result&&result.isNotUnique) {
                              form.showError('pointid',getLabel('387654','标识已存在'));
                            }
                        });
                      }
                    }}/>
                  : <div>
                  <nobr>
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@dppjf3@integrationScheduleAddForm${fields.domkey[0]}`} {...fields} value={formParams.cronexpr.trim()} onChange={v => form.updateFields({cronexpr: v.trim() || '0 0 * * * ?'})} />
                    <div style={{display: 'inline-block'}}>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ncdgh4@integrationScheduleAddFormset${fields.domkey[0]}`} onClick={() => $("#scheduleCronexpr").toggle()}>{getLabel('30747','设置')}</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qvnqrc@integrationScheduleAddFormreset${fields.domkey[0]}`} onClick={() => form.updateFields({cronexpr: '0 0 * * * ?'})} style={{marginLeft: 10}}>{getLabel('2022','重置')}</Button>
                    </div>
                  </nobr>
                  <div id="scheduleCronexpr" style={{position: 'absolute', border: '1px solid #d9d9d9', marginTop: 10, zIndex: 1, backgroundColor: 'white', padding: '20px 25px 0', display: 'none'}}>
                    <div>{getLabel('508909','Cron表达式生成器')}</div>
                    <div style={{ width: 450, height: 350}}>
                      {flag && <WeaCron ecId={`${this && this.props && this.props.ecId || ''}_WeaCron@hyp0x6`}
                        cronExpression={form.getFormParams().cronexpr}
                        onChange={v => form.updateFields({cronexpr: v})}
                      />}
                    </div>
                  </div>
                </div>
              }
            </WeaFormItem>
          </div>),
          colSpan: 1,
        });
      });
      if (needTigger) {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@f04k6r@integrationScheduleAddForm${index}`} center={centerFlag} col={1} needTigger={needTigger} title={c.title} showGroup={c.defaultshow} items={items} />)
      }else {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@gwavo4@integrationScheduleAddForm${index}`} center={centerFlag} col={1} needTigger={needTigger} showGroup={c.defaultshow} items={items} />)
      }
    });
    return group;
  }

  render() {
    const { schedule } = this.props;
    const { createTask, tableEdit, tableEditDatas, loading, flag } = schedule;
    const { form, conditions, show, isEdit } = createTask;
    const resConditions = toJS(conditions);

    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@mh4puk`}
        style={{ width: 900, height: 700 }}
        hasScroll={true}
        title={`${isEdit ? getLabel(26473, "编辑") : getLabel(365, "新建")}${getLabel(16539, "计划任务")}`}
        visible={show}
        icon={IntegrationUtil.GeneralTitleColor.icon}
        iconBgcolor={IntegrationUtil.GeneralTitleColor.iconBgcolor}
        onCancel={() => createTask.show = false}
        buttons={this.getBtns()}
        moreBtn={{
          datas: this.getRightMenu(),
          collectParams: {
            favname: `${getLabel(20873, "新建模板")}`,
            favouritetype: 1,
            objid: 0,
            link: "wui/engine.html#/blogengine/templateSetCreate",
            importantlevel: 1
          }
        }}
      >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@vchs23`} datas={this.getRightMenu()}>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@5idyct`} spinning={loading}>
            {/* 基本信息 */}
            {flag && resConditions && resConditions[0] && this.getSearchs(form, [resConditions[0]], true)}
            {/* 参数设置 */}
            <div style={{paddingLeft:25, paddingRight:25}}>
              <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@ig7rup`}
                ref={el => this.table = el}
                title={getLabel(17632, "参数设置")}
                validator={{
                  rules: {
                    attrname: 'required|uniqueAttrName',
                    attrvalue: 'required',
                  },
                  customRegister: [
                    {
                      name: "uniqueAttrName",
                      rules: (value, requirement, attribute) => {
                        return toJS(tableEditDatas).filter(v => v.attrname === value).length < 2;
                      },
                      errorMessage: getLabel('509498','参数名称重复')
                    }
                  ]
                }}
                tableProps={{
                  showEmptyText: false
                }}
                columns={toJS(tableEdit)}
                datas={toJS(tableEditDatas)}
                selectedRowKeys={this.state.editTableSelected}
                onRowSelect={(selectedRowKeys, record) => {
                  this.setState({
                    editTableSelected: selectedRowKeys
                  });
                }}
                showCopy={false}
                showCollapse={true}
                willAdd={(allDatas, addData) => schedule.tableEditDatas = allDatas}
                willEdit={(allDatas, editData) => schedule.tableEditDatas = allDatas}
                willDelete={this.willDelete}
              />
            </div>
            
            {/* 状态说明 */}
            <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@bj6331`} title={getLabel('506723','状态详解:')} needTigger={true} showGroup={true}>
              <div style={{marginLeft: 10, color: 'rgb(50, 50, 50, 0.9)'}}>
                <p>1、{getLabel('506724','启用: 计划任务将根据Cron表达式执行;')}</p>
                <p>2、{getLabel('506725','禁用: 计划任务将不再执行，重启服务也不会再次执行;')}</p>
                <p>3、{getLabel('506756','暂停: 针对计划任务进行停止，重启服务将恢复正常状态;')}</p>
                <p>4、{getLabel('506727','恢复: 针对暂停状态的计划任务进行恢复，恢复后计划任务将继续执行;')}</p>
                <p>5、{getLabel('506728','执行: 单次执行计划任务，不影响Cron表达式周期执行;')}</p>
                <p>6、{getLabel('506729','测试: 检查填写的计划任务类是否符合规范（继承weaver.interfaces.schedule.BaseCronJob类,重写方法public void execute() {}）。')}</p>
              </div>
            </WeaSearchGroup>
            {/* 说明 */}
            {resConditions && resConditions[2] && this.getSearchs(form, [resConditions[2]], true, false)}
          </Spin>
        </WeaRightMenu>
      </WeaDialog>       
    );
  }

}
