import { action, observable, toJS } from "mobx";
import * as API from "../apis/TodoClientService";
import { message, Modal, Button } from 'antd';
import { WeaForm, WeaLogView, WeaTableNew } from 'comsMobx';
import { WeaLocaleProvider, WeaTools, WeaHelpfulTip, WeaFormItem, WeaSelect } from 'ecCom';
import isFunction from 'lodash/isFunction';
import {
  getSearchFormHeight,
  checkNonstandard
} from '../util/IntegrationUtil';

const { TableStore } = WeaTableNew;
const { LogStore } = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;

export class TodoClientStore {
  @observable hasRight = true;
  @observable rightLoading = true;

  @observable tableStore = new TableStore();
  @observable tableStore_whitewf = new TableStore();
  @observable tableStore_whitehrm = new TableStore();

  @observable searchForm = new WeaForm();
  @observable newForm = new WeaForm();
  @observable workflowForm = new WeaForm();
  @observable workflowdataFrom = new WeaForm();


  @observable
  status = {
    content: null,
    wfdataDiaSpinflag: true,
    hasNonStandard: true,
    nonStandLoading: true,
    selectedKey: 0,
    newFormHiddenFields: [],
    workflowFormHiddenFields: [],
    showSearchAd: false,
    rightMenus: [],
    condition: [],
    rowSelectIds: [],
    rowSelectIds_wf: [],
    rowSelectIds_hrm: [],
    showNewFormDialog: false,
    WhiteWorkflowDialogVisible: false,
    WhiteHrmDialogVisible: false,
    WorkflowdataDialogVisible: false,
    advancedSearchHeight: 120,
    paramsColumnsSet: [],
    paramsData: [],
    whiteWorkflowIds: [],
    whiteWorkflowIdsspan: [],
    sysid: [],
    selectedindex: 1,
  };

  @action cleanStore = () => {
    this.searchForm = new WeaForm();
    this.setState({
      selectedKey: 0,
      advanceHeight: 0,
      newFormHiddenFields: [],
      showSearchAd: false,
      rightMenus: [],
      condition: [],
      rowSelectIds: [],
      rowSelectIds_wf: [],
      rowSelectIds_hrm: [],
      showNewFormDialog: false,
      WhiteWorkflowDialogVisible: false,
      WhiteHrmDialogVisible: false,
      advancedSearchHeight: 120,
      paramsColumnsSet: [],
      paramsData: [],
      whiteWorkflowIds: [],
      whiteWorkflowIdsspan: [],
      sysid: [],
    });
  }

  @action
  doInit = () => {
    this.setState({
      nonStandLoading: true
    })
    checkNonstandard({ num: "101" }, (result) => {
      this.setState({
        hasNonStandard: result.isOpen,
        nonStandLoading: false
      })
      if (result.isOpen) {
        this.cleanStore();
        this.getOfsSendList();
        this.getOfsSendCondition();
        this.getOfsSendRightMenu();
        this.getAuth();
      }
    })
  };

  @action setState = (params = {}) => {
    let status = { ...this.status };
    Object.keys(params).forEach(key => {
      status[key] = params[key];
    });
    this.status = status;
  };

  @action getAuth = () => {
    API.getAuth().then(result => {
      this.setState({ auth: result.msg });
    })
  }

  getOfsSendForm = (params) => {
    API.getOfsSendForm(params).then(result => {
      this.status = {
        ...this.status,
        newFormHiddenFields: result.hiddenFields,
        paramsColumnsSet: result.paramsColumnsSet,
        paramsData: result.paramsData,
      };
      this.newForm = new WeaForm();
      this.newForm.setCondition(result.condition);
    });
  };

  getOfsSendOperation = (params, callback) => {
    API.getOfsSendOperation(params).then(result => {
      if (!callback) {
        if (result.errmsgTip) {
          message.success(result.errmsgTip);
        }
      }
      if (params && (params.operate == "dowfdel" || params.operate == "dowf")) {
        params.operate == "dowfdel" && this.setState({ rowSelectIds_wf: [] });
        this.getOfsSendWhiteWorkflowList(params);
      } else if (params && (params.operate == "douserdel" || params.operate == "douser")) {
        params.operate == "douserdel" && this.setState({ rowSelectIds_hrm: [] });
        this.getOfsSendWhiteHrmList(params);
      } else {
        this.getOfsSendList();
      }
      this.status.showNewFormDialog = false;
      isFunction(callback) && callback(result);
    });

  };

  getOfsSendList = (p) => {
    let params = (this.searchForm && this.searchForm.getFormParams()) || {};
    API.getOfsSendList(params).then(result => {
      if (result.ret && result.ret == "noright") {
        this.hasRight = false;
      } else {
        this.hasRight = true;
      }
      this.rightLoading = false;
      if (result.sessionkey) {
        this.tableStore = new TableStore();
        this.tableStore.getDatas(result.sessionkey, 1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };

  getOfsSendRightMenu = (params) => {
    API.getOfsSendRightMenu(params).then(result => {
      this.status = { ...this.status, rightMenus: result.rightMenus };
    });
  };

  getOfsSendCondition = (params) => {
    API.getOfsSendCondition(params).then(result => {
      this.status.condition = result.condition;
      if (result.condition) {
        this.searchForm = new WeaForm();
        this.searchForm.initFormFields(result.condition);
        let advanceHeight = getSearchFormHeight(result.condition);
        this.setState({ advanceHeight });
      }
    });
  };

  getOfsSendWhiteWorkflowList = (params) => {
    API.getOfsSendWhiteWorkflowList(params).then(result => {
      if (result.sessionkey) {
        this.tableStore_whitewf = new TableStore();
        this.tableStore_whitewf.getDatas(result.sessionkey, 1);
        this.status = { ...this.status, isAlertPage: true, sysid: params.sysid };
      }
    });
  };

  getOfsSendWhiteHrmList = (params) => {
    API.getOfsSendWhiteHrmList(params).then(result => {
      if (result.sessionkey) {
        this.tableStore_whitehrm = new TableStore();
        this.tableStore_whitehrm.getDatas(result.sessionkey, 1);
        this.status = { ...this.status, isAlertPage: true, sysid: params.sysid };
      }
    });
  };


  confirmModal = (content, func, val) => {
    //确认信息， 方法， 方法参数
    Modal.confirm({
      title: `${getLabel(131329, '信息确认')}`,
      content: content,
      okText: `${getLabel(16631, '确定')}`,
      cancelText: `${getLabel(201, '取消')}`,
      onOk: () => func(val),
    })
  };

  getOfsSendWhiteWorkflowForm = (params) => {
    params = params || {};
    API.getOfsSendWhiteWorkflowForm(params).then(result => {
      if (result.status) {
        this.workflowForm = new WeaForm();
        this.workflowForm.setCondition(result.condition);
        this.status = {
          ...this.status,
          workflowFormHiddenFields: result.hiddenFields,
        };
      }
    });
  }
  /** **********************下面为流程数据分类控制弹窗页面的操作*************************** */
  // 表单的列数据和行数据
  @observable columns = [];
  @observable datas = [];
  // Form的数据存储
  @observable condtionField = [];
  // 接口请求
  @action getOfsSendWorkflowdataFrom = () => {
    this.setState({ selectedindex: 0, content: null })
    // 初始化Form
    this.workflowdataFrom = new WeaForm();
    API.getOfsSendMessageTypeForm({ sysId: this.status.sysid }).then(action((data) => {

      // 通过后端数据判断初始化时当前要展示预设还是自定义
      this.status.selectedindex = data.fieldValues.sendTypeSetting;
      // table表单数据处理
      this.columns = data.systemMessageTypeTable.columns;
      this.datas = data.systemMessageTypeTable.data;
      this.columns.forEach((item) => {
        if (item.dataIndex == "requestType") {
          this.columns[2].render = text => <span style={{ color: '#4D7AD8' }}>{text}</span>;
        }
      })
      // this.columns[2].render = text => <span style={{ color: '#0000EE' }}>{text}</span>;
      // Form数据处理
      this.condtionField = [data.condition];
      this.workflowdataFrom.initFormFields(this.condtionField);
      if (data.status == '1') {
        this.setState({ wfdataDiaSpinflag: false })
        this.setState({
          content: (<div div style={{ width: '800px' }} >
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@l2asd8`}
              label={`${getLabel('532286', '流程数据推送选择')}`}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 16 }}
              style={{ margin: '20px 20px	 20px 150px' }}
            >
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@bkrr2a`}
                options={[{
                  key: '1',
                  selected: true,
                  showname: <span >
                    {getLabel('532287', '使用预设推送数据分类')}
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@65f2aj@prePushData`} style={{ marginLeft: '10px' }} placement={'right'} title={`${getLabel('532288', '按照系统设置的默认分类方式向异构系统进行流程数据推送。')}`} width={200} />
                  </span>,
                }, {
                  key: '2',
                  selected: false,
                  showname: <span style={{ display: 'block', margin: '10px 0 10px  0' }}>
                    {getLabel('525438', '手动设置推送数据分类')}
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ttwlym@handPushData`} style={{ marginLeft: '10px' }} placement={'right'} title={`${getLabel('532289', '可以自定义设置向异构系统推送的待办、已办、办结和删除流程数据。')}`} width={200} />
                  </span>
                }]}
                detailtype={3}
                onChange={this.onChangeHandle}
                fieldshowtypes={2}
                value={`${this.status.selectedindex}`}
              />
            </WeaFormItem>
          </div >)
        })

      }
    }));
  }
  // 单选框选中的时候返回单选下标值
  @action onChangeHandle = (value) => {
    this.status.selectedindex = value;
  }

  // 保存按钮操作
  savedata = () => {
    let params = {};
    if (this.status.selectedindex == 1) {
      params = {
        sysId: this.status.sysid,
        sendTypeSetting: this.status.selectedindex,
        todoData: '',
        doneData: '',
        overData: '',
        deleteData: '',
      };
    } else {
      // workflowdataFrom.getFormParams()可以获取浏览按钮当前选中的值的id
      const FormFielddata = this.workflowdataFrom.getFormParams();
      params = {
        sysId: this.status.sysid,
        sendTypeSetting: this.status.selectedindex,
        todoData: `${FormFielddata.todoData}`,
        doneData: `${FormFielddata.doneData}`,
        overData: `${FormFielddata.overData}`,
        deleteData: `${FormFielddata.deleteData}`,
      };
    }
    // 触发保存接口
    API.getOfsSendMessageTypeOperationCmd(params).then((result) => {
      if (result && result.status && result.status == '1') {
        this.setState({ WorkflowdataDialogVisible: false });
        this.setState({ sysid: '' });
      }
    });
  }
  // dialog按钮
  buttons = [
    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yzb93i@button`} type="primary" onClick={this.savedata}>{`${getLabel('30986', '保存')}`}</Button>,
  ]
  moreBtn = {
    datas: [
      {
        key: '1',
        disabled: false,
        icon: <i className="icon-coms-Save-as" />,
        content: `${getLabel('30986', '保存')}`,
        onClick: this.savedata,
      },
    ],
  }

  // 右键菜单
  @observable rightButton = [
    {
      key: '1',
      icon: <i className="icon-coms-Save-as" />,
      content: `${getLabel('30986', '保存')}`,
      onClick: this.savedata,
    }]
  // table每行都有自己的sysid
  @action setsysId = (sysId) => {
    this.setState({ sysid: sysId });
  }
}
