import React from "react"
import { Modal, Button, Form, Select, Spin } from "antd"

import { dispatch } from '../../../model'
import { HandlersItem } from "./distribute-task"
import { showMessage } from "../../../util"

const FC = (props) => {
  const { visible, items, onCancel } = props
  const [waiting, setWaiting] = React.useState(false)

  const basicRef = React.useRef()

  const close = (refresh = false) => {
    setWaiting(false)
    onCancel?.(refresh)
  }

  const save = async() => {
    try {
      const rows = await basicRef.current?.validate()

      setWaiting(true)
      dispatch({
        type: 'assetmanage.reDistributeTask',
        payload: { 
          data: {
            resourceIds: (items??[]).map(item => item.id),
            taskUserList: rows.users,
          }
        },
        callback: () => {
          setWaiting(false)
          showMessage('success', '转分配成功')
          onCancel(true)
        },
        error: () => {
          setWaiting(false)
        }
      })

    } catch (e) {
      
    }
  }

  const footer = React.useMemo(() => {
    return [
      <Button key={'cancel'}
        onClick={() => close()}
      >取消</Button>,
      <Button key={'save'} type='primary'
        onClick={() => save()}
      >确定</Button>
    ]
  }, [close, save])

  return (
    <Modal
      visible={visible}
      footer={footer}
      width='800px'
      bodyStyle={{ padding: '15px', overflowX: 'auto', maxHeight: '80vh' }}
      title='任务转分配'
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <Spin spinning={waiting}>
        <Basic ref={basicRef} />
      </Spin>
    </Modal>  
  )
}

export default FC

export const Basic = React.forwardRef(function ({ items }, ref) {
  const [form] = Form.useForm()

  React.useImperativeHandle(ref, () => ({
    validate: async () => {
      return await form.validateFields()
    },
  }), [form])

  const onValuesChange = (changedValues, allValues) => {
    console.log('all values', allValues)
  }

  return (
    <Form
      form={form}
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 21 }}
      autoComplete="off"
      onValuesChange={onValuesChange}
    >
      <Form.Item
        label='分配用户'
        name='users'
        rules={[{ required: true, message: '请选择用户!' }]}
      >
        <HandlersItem />
      </Form.Item>
    </Form>
  )
})