import { connect } from 'dva'
import { Form } from 'antd'
import EditComponent from "../../baseComponents/EditComponent"
import { isEqual } from 'lodash'

class Edit extends EditComponent {
  constructor(props) {
    super(props)
    this.state = {
      initData: {
        ENABLE_STATUS: 0
      },
      columns: [],
      data: {},
      editData: {},
      btnData: [],
      formData: {},
      jsFile: '',
      loading: false,
      subTable: [],
      isRegSaveFunc: false,
      btnLoading: false,          // 触发按钮loading
      cusLoading: false,          // 触发自定义按钮loading
    }
    this.subEditTables = {}
    this.updateSubSource = {}
  };

  componentWillReceiveProps (NextProps) {
    super.componentWillReceiveProps(NextProps)
    const data = NextProps.data
    const reloadKey = data && data.reloadKey ? data.reloadKey : null
    let reload = false
    if (reloadKey) {
      reload = NextProps.editPage[reloadKey]
    }
    if (NextProps.id !== this.props.id || this.props.isAdd !== NextProps.isAdd || reload) {
      console.log('reload')
      const tempReloadKey = reloadKey
      this.props.form.resetFields()
      this.onLoadData()
      if (reload) {
        this.props.dispatch({
          type: 'editPage/save',
          payload: {
            [tempReloadKey]: false,
          }
        })

        // 表单加载日志埋点
        const { CODE, NAME } = this.state.formData
        if (CODE && NAME) {
          this.props.dispatch({
            type: 'app/operateLog',
            payload: {
              FormCode: CODE,
              FormName: NAME,
              UserId: this.props.login.userId,
              OrgId: this.props.login.OrgId
            }
          })
        }
      }
    }
    if (this.props.data) {
      const onRegSaveFunc = this.props.data.onRegSaveFunc
      if (typeof onRegSaveFunc === 'function' && !this.state.isRegSaveFunc) {
        onRegSaveFunc(this.handleOk)
        this.setState({
          isRegSaveFunc: true,
        })
      }
    }
  }

  componentDidUpdate (prevProps, prevState) {
    if (!isEqual(prevState.formData, this.state.formData)) {
      // 表单加载日志埋点
      const { CODE, NAME } = this.state.formData
      if (CODE && NAME) {
        this.props.dispatch({
          type: 'app/operateLog',
          payload: {
            FormCode: CODE,
            FormName: NAME,
            UserId: this.props.login.userId,
            OrgId: this.props.login.OrgId
          }
        })
      }
    }
  }
}

export default connect(({ login, app, loading, editPage, custom }) => ({ login, app, loading, editPage, custom }))(Form.create()(Edit))
