/**
 * 徐立
 * 2019年9月18日
 * 发起流程表单申请列表
 */
import React, { Component } from 'react';
import styles from './styles.less';
import { Form, Button, Spin } from 'antd';
import AddModal from './AddModal';
import openToast from '@/webPublic/one_stop_public/DetailForAudit/components/Notification';
import { connect } from 'dva';
import ZdyTable from '@/webPublic/one_stop_public/Table';
import { preHandle } from '@/webPublic/one_stop_public/utils/myutils';
import router from 'umi/router';
import { isEmpty } from 'lodash';
import { callbackApplyData } from '@/webPublic/one_stop_public/models/callbackExamineProcess';
import { isJSON } from '@/webPublic/one_stop_public/tableCompon/Split_Index/staticInfo';
import { getModal } from '@/webPublic/one_stop_public/utils/utils';
import beforeApplySubmit from '@/webPublic/one_stop_public/utils/beforeApplySubmit';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
import { deepCopy } from '@/webPublic/zyd_public/utils/utils';

const Modal = getModal();

class SponsorForm extends Component {
  constructor(props) {
    super(props);
    this.setEditor = editor => {
      this.editor = editor;
    };
    this.focusEditor = () => {
      if (this.editor) {
        this.editor.focus();
      }
    };
    const { propsState } = props;
    this.state = {
      visible: false, // 确认弹框状态
      img: '', // 上传图片路径
      items: [], // 动态列表数据
      left: 0,
      top: 0,
      max: 4,
      width: 100,
      init: {}, // 默认值
      disabled: false, // 按钮控制状态
      data: '', //当前用户数据
      appId: propsState.appId,
      postData: propsState.postData,
      isLoading: propsState.isLoading,
      draftId: propsState.draftId,
    };
  }

  countHeight = () => {
    let dom = document.getElementById('tabsTableFromIframe');
    let top = 0;
    if (dom && dom.offsetHeight) {
      let height = dom.offsetHeight;
      if (height > 700) {
        top = height - 700;
      }
    }
    return top;
  };

  /**
   * 提交完成后用户提示
   */
  info = (applySubmitModalProps = undefined) => {
    let method = applySubmitModalProps && applySubmitModalProps.method ? applySubmitModalProps.method : 'info'; // 从流程发起回调里面拿配置项
    let config = (applySubmitModalProps && applySubmitModalProps.config) || {};
    Modal[method]({
      title: '提交申请',
      centered: true,
      content: (
        <div>
          <p
            style={{
              width: '100%',
              textAlign: 'center',
              fontSize: 14,
              color: '#666666',
            }}
          >
            已提交申请！请耐心等待审核。
          </p>
        </div>
      ),
      okText: '确定',
      onOk: () => {
        if(this.props.returnList){
          this.props.returnList(true);
        }
        return new Promise((resolve, reject) => {
          resolve(true);
        })
        return true;
      },
      ...config,
    });
  };
  /**
   * 用户最终确认 发起提交
   */
  userTrue = () => {
    this.setState({
      isUser: true,
    });
  };
  /**
   * 展示确认级弹框状态
   */
  showModal = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          visible: true,
        });
      } else {
        console.error(err);
      }
    });
  };
  /**
   * 隐藏弹框
   */
  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };
  /**
   * 删除已添加人物
   */
  // removePeo = (id) => {
  //     this.setState({
  //         people: this.state.people.filter(item => item.id !== id)
  //     })
  // }
  /**
   * 下拉选择框事件
   */
  onChange = value => {
    console.log(`selected ${value}`);
  };
  /**
   * 确认提交后触发提交申请，返回true时提示用户提交完成
   */
  handleOk = e => {
    this.handleSubmit();
    // 关闭弹框
    this.handleCancel();
  };
  /**
   * 上传文件函数
   */
  normFile = e => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  /**
   * 确认完用户状态发起请求
   */
  handleSubmit = () => {
    let { dispatch, radioValue } = this.props;
    let isCloseFlowPath = sessionStorage.getItem('isCloseFlowPath')
      ? JSON.parse(sessionStorage.getItem('isCloseFlowPath'))
      : false;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (isCloseFlowPath) {
        } else if (!radioValue) {
          openToast('success', '请选择紧急度');
          return;
        }
        let newValues = deepCopy(values);
        preHandle(newValues);
        //如果是从流程仿真进入
        if (this.props.onSub && false) {
          dispatch({
            type: 'affair/startProcessByService',
            payload: {
              content: JSON.stringify(newValues), // 表单数据
              level: radioValue, // 流程紧急度 非必填 可以不传
              appId: this.state.appId, // 这里应该由上级路由跳转传入 事务Id
              id: !!this.state.draftId ? this.state.draftId : null, // 确认是否存在草稿表单Id存在即传入
              startUser: this.props.startUser ? this.props.startUser : null,
            },
            callback: val => {
              if (val) {
                this.props.onSub(val);
              } else {
                openToast('error', '保存失败', '请尝试');
              }
            },
          });
        } else {
          let params = {
            content: JSON.stringify(newValues), // 表单数据
            level: radioValue, // 流程紧急度 非必填 可以不传
            appId: this.state.appId, // 这里应该由上级路由跳转传入 事务Id
            id: !!this.state.draftId ? this.state.draftId : null, // 确认是否存在草稿表单Id存在即传入
            userNowInfo:
              (localStorage.getItem('user') &&
                isJSON(localStorage.getItem('user')) &&
                JSON.parse(localStorage.getItem('user'))) ||
              {}, // 用户信息
          };

          params = callbackApplyData(params);
          if (!params) {
            return;
          }
          beforeApplySubmit(params).then(resParams => {
            if (!resParams) {
              return false;
            }
            let applySubmitModalProps = resParams?.applySubmitModalProps  || undefined;
            delete resParams.applySubmitModalProps;
            message.info('正在提交申请,请等待');
            uaaRequest('UnifiedAppFormApi/startProcess', resParams).then((val) => {
              if (val) {
                this.info(applySubmitModalProps);
              } else {
                openToast('error', '保存失败', '请尝试');
              }
            })
            // dispatch({
            //   type: 'affair/startProcess',
            //   payload: resParams,
            //   callback: val => {
            //   },
            // });
          });
        }
      } else {
        openToast('error', '提交失败', '请填写必填项');
      }
    });
  };

  render() {
    let { disabled, visible, postData, isLoading } = this.state;
    let { init, noNeedApplyButton } = this.props;
    let routerState = {
      history: this.props?.history,
      location: this.props?.location,
      match: this.props?.match,
      computedMatch: this.props?.computedMatch,
      route: this.props?.route,
    };
    return (
      <>
        {isLoading ? (
          <>
            <div className={styles.form} id="add_form">
              {isEmpty(postData) === false ? (
                <ZdyTable
                  isCg={undefined}
                  get="web"
                  postData={postData}
                  form={this.props.form}
                  routerState={routerState}
                  init={init}
                />
              ) : (
                ''
              )}
              {isEmpty(postData) === false && !postData?.isUpdate && !noNeedApplyButton ? (
                <Form.Item
                  wrapperCol={{
                    span: 12,
                    offset: 6,
                  }}
                >
                  <Button
                    disabled={disabled}
                    type="primary"
                    loading={this.props.loading}
                    onClick={this.showModal}
                    style={{ marginLeft: 16 }}
                  >
                    提交
                  </Button>
                </Form.Item>
              ) : (
                ''
              )}
              <AddModal
                visible={visible}
                handleOk={this.handleOk}
                userTrue={this.userTrue}
                loading={this.props.loading}
                handleCancel={this.handleCancel}
              />
            </div>
          </>
        ) : (
          <div
            style={{
              width: '100%',
              height: 200,
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <Spin size="large" />
          </div>
        )}
      </>
    );
  }
}

@connect(({ affair, loading }) => ({
  affair,
  loading: loading.models.affair,
}))
export default class SponsorFormDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      postData: null,
    };
  }

  componentDidMount() {
    let { id, dispatch } = this.props;
    dispatch({
      type: 'modileHome/getDetail',
      payload: {
        id: id,
        userCode: this.props.startUser ? this.props.startUser : null,
      },
      callback: val => {
        if (val) {
          this.setState(
            {
              appId: val.id,
              isLoading: true,
              postData: val,
              draftId:  '',
            },
            () => {},
          );
        }
      },
    });
  }

  render() {
    const { postData } = this.state;
    if (!postData) {
      return null;
    } else {
      const SponsorFormNew = Form.create(
        window.zdyTableTemplateWillMountProps?.formCreateOptions || undefined,
      )(SponsorForm);
      return <SponsorFormNew {...this.props} propsState={this.state} />;
    }
  }
}
