import React, { useState, useCallback, useEffect } from 'react'
import { Spin, Card, Layout, Row, Col, Form, Input, Checkbox, AntdSelect as Select, Button, Message } from '@ttk/component'
import { Modal } from "antd"
import { useData, useActions, useCommit } from '@ttk/app-loader'
import moment from 'moment'

export default function Component(props) {

  const commit = useCommit()
  const actions = useActions(props)
  const resetValidateState = useData([props, 'resetValidateState']).toJS()
  const resetFormObj = useData([props, 'resetFormObj']).toJS()
  const showResetModal = useData([props, 'tempState', 'showResetModal'])
  
  // 内部管理loading状态
  const [loading, setLoading] = useState(false)

  // 初始化
  useEffect(() => {
    actions.initResetForm()
  }, []) 

  // 更新表单方法
  const updateForm = useCallback((e) => {
    async function asyncFun(arges) {
      await actions.updateResetFormObj(e)
    }
    asyncFun(e)
  }, [])

  // 提交方法
  const onSave = useCallback(() => {
    async function asyncFun() {
      // 使用commit直接更新reducer数据。这种方式可跳过action直接更新reducer数据
      setLoading(true)
      const resutl = await actions.resetFormSave()
      if (resutl) {
        Message.info('提交成功')
      }
      setLoading(false)
      commit([props, 'tempState'], { type: 'setResetModal', data: false })
    }
    async function validate() {
      const result = await actions.updateResetFormObj()
      if (!result) return;
      asyncFun() 
    }
    validate()
  })

  // 清除方法
  const onCancel = useCallback(() => {
    commit([props, 'tempState'], { type: 'setResetModal', data: false })
    commit([props, 'resetValidateState'], { type: 'clear' })
    actions.initForm()
  }, [])
  
  return (
    <Modal
      className="ttk-card-form"
      width={400}
      title="重置密码"
      visible={showResetModal}
      okText="确定"
      cancelText="取消"
      onOk={onSave}
      onCancel={onCancel}
    >
      <Spin spinning={loading}>
        <Layout className="content">
          <Form className="label120">
            <Row>
              <Col span={24}>
                <Form.Item
                  label="新密码"
                  required={true}
                  validateStatus={resetValidateState.password.state}
                  help={resetValidateState.password.message}>
                  <Input placeholder="请输入新密码" value={resetFormObj.password} onChange={e => updateForm({ password: e.target.value })} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="确认密码"
                  required={true}
                  validateStatus={resetValidateState.password2.state}
                  help={resetValidateState.password2.message}>
                  <Input placeholder="请确认密码" value={resetFormObj.password2} onChange={e => updateForm({ password2: e.target.value })} />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Layout>
      </Spin>
    </Modal>
  )
}