import React, { useState, useCallback, useEffect } from 'react'
import { Spin, Card, Layout, Row, Col, Form, Input, Radio, Checkbox, AntdSelect as Select, Switch, Button, Message, DatePicker, Modal } from '@ttk/component'
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 loading = useData([props, 'dialogTempState', 'loading'])
  const validateState = useData([props, 'validateState']).toJS()
  const formObj = useData([props, 'attributeForm']).toJS()
  
  // 内部管理loading状态
  const [loading, setLoading] = useState(false)
  const isCycle = ['否', '是']
  const isUse = ['否', '是']
  // 定义form表单字段，用于清除重置时回显和首次校验
  const formData = {
    name: null,
    sortNo: null,
    isCycle: null,
    isUse: null,
    dateStart: null,
    dateEnd: "2019-10-01",
    testType: ["A", "B"],
    isDefault: null,
    remark: null
  }

  // 初始化
  useEffect(() => {
    const id = props.location.params.id;
    async function fetch() {
      setLoading(true)
      await actions.initForm({id: id})
      setLoading(false)
    }
    function init() {
      actions.initForm(formData)
    }
    if (id) {
      fetch();
    } else {
      init()
    }
  }, []) 

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

  // 提交方法
  const save = useCallback(() => {
    async function asyncFun() {
      // 使用commit直接更新reducer数据。这种方式可跳过action直接更新reducer数据
      setLoading(true)
      const resutl = await actions.dialogSave()
      if (resutl) {
        Message.info('提交成功')
      }
      setLoading(false)
    }
    async function validate() {
      let { form } = props;
      const result = await actions.updateFormObj()
      if (!result) return;
      const modal = Modal.confirm({
        title: '确认',
        content: '是否确认提交表单',
        onOk: () => { 
          asyncFun() 
        }
      })
    }
    validate()
  }, [formObj.parentId])

  // 清除方法
  const onReset = useCallback(() => {
    commit([props, 'attributeForm'], { type: 'update', data: null })
  }, [])
  return (
    <Card
      className="ttk-card-form"
    >
      <Spin spinning={loading} delay={50}>
        <Layout className="content">
          <Form className="label160">
            <Row>
              <Col span={12}>
                <Form.Item
                  label="名称(异步校验)"
                  required={true}
                  validateStatus={validateState.name.state}
                  help={validateState.name.message}>
                  <Input placeholder="请输入名称" disabled={false} value={formObj.name} onChange={e => updateForm({ name: e.target.value })} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="排序"
                  required={true}
                  validateStatus={validateState.sortNo.state}
                  help={validateState.sortNo.message}>
                  <Input placeholder="请输入优先级" disabled={false} value={formObj.sortNo} onChange={e => updateForm({ sortNo: e.target.value })} />
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label="是否循环"
                  required={true}
                  validateStatus={validateState.isCycle.state}
                  help={validateState.isCycle.message}>
                  <Select
                    placeholder="请选择是否循环"
                    filterOption={null}
                    allowClear={true}
                    disabled={false}
                    value={formObj.isCycle}
                    onChange={e => updateForm({ isCycle: e })} >
                    {
                      isCycle.map((item, index) => <Select.Option key={`${index}${item}`} value={Number(index)}>{item}</Select.Option>)
                    }
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="启用"
                  required={true}
                  validateStatus={validateState.isUse.state}
                  help={validateState.isUse.message}>
                  <Select
                    key={'select2'}
                    placeholder="请选择启用"
                    filterOption={null}
                    allowClear={true}
                    disabled={false}
                    value={formObj.isUse}
                    onChange={e => updateForm({ isUse: e })} >
                    {
                      isUse.map((item, index) => <Select.Option key={`${index}${item}`} value={Number(index)}>{item}</Select.Option>)
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={12}>
                <Form.Item
                  label="有效期起"
                // required={true}
                >
                  <DatePicker placeholder="请选择有效期起" value={formObj.dateStart && moment(formObj.dateStart)} onChange={e => updateForm({ dateStart: e })} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="有效期止"
                // required={true}
                >
                  <DatePicker placeholder="请选择有效期止" value={formObj.dateEnd && moment(formObj.dateEnd)} onChange={e => updateForm({ dateEnd: e })} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="测试类型"
                >
                  <Checkbox.Group style={{ width: '100%' }} value={formObj.testType} onChange={value => updateForm({ testType: value })}>
                    <Row>
                      <Col span={8}>
                        <Checkbox value="A">A</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox disabled value="B">
                          B
                        </Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="C">C</Checkbox>
                      </Col>
                    </Row>
                  </Checkbox.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="是否默认"
                >
                  <Switch defaultChecked checked={formObj.isDefault} onChange={value => updateForm({ isDefault: value })}/>
                </Form.Item>
              </Col>

              <Col span={24}>
                <Form.Item
                  label="描述(同步校验)"
                  validateStatus={validateState.remark.state}
                  help={validateState.remark.message}
                >
                  <Input.TextArea  placeholder="请输入描述" row={4} value={formObj.remark} onChange={e => updateForm({ remark: e.target.value })} />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col className="form-footer" span={24}>
                <Button type="primary" onClick={save}>保存</Button>
                <Button onClick={onReset}>清除</Button>
              </Col>
            </Row>
          </Form>
        </Layout>
      </Spin>
    </Card>
  )
}