import React from "react"
import { Modal, Button, Form, Select, Spin, Checkbox, Space, Row } from "antd"
import { debounceTime, Subject } from 'rxjs'

import { dispatch } from '../../../model'
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.distributeTask',
        payload: { 
          data: {
            resourceIds: (items??[]).map(item => item.id),
            nextProcessUsers: rows.users,
          }
        },
        callback: (data) => {
          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.Item
        label='通知方式'
        name='noticeTypes'
        rules={[{ required: true, message: '请选择通知方式!' }]}
      >
        <NoticeItem />
      </Form.Item> */}
    </Form>
  )
})

export const HandlersItem = ({ value, onChange }) => {
  const [loading, setLoading] = React.useState(false)
  const [users, setUsers] = React.useState()
  const [options, setOptions] = React.useState([])

  React.useEffect(() => {
    getHandlers()
  }, [])

  const getHandlers = () => {
    setLoading(true)
    dispatch({
      type: 'user.getUsers',
      callback: (data) => {
        setLoading(false)
        setUsers(data)
        setOptions(
          (data??[]).map(item => ({
            label: item.name,
            value: item.id,
          }))
        )
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onHandleChange = (val) => {
    const newUsers = (users??[]).filter(item => (val??[]).includes(item.id)).map(item => ({...item, displayName: item.dname}))
    onChange?.(newUsers)
  }

  return (
    <Select 
      placeholder='请选择用户' 
      loading={loading}
      value={value?value.map(item => item.id):undefined}
      onChange={onHandleChange}
      allowClear
      mode='multiple'
      filterOption={true}
      optionFilterProp='label'
      options={options??[]}
    />
  )
}

const NoticeItem = ({ value, onChange }) => {
  const [noticeTypes, setNoticeTypes] = React.useState()
  const [modal, contextHolder] = Modal.useModal()

  React.useEffect(() => {
    getNoticeTypes()
  }, [])

  const getNoticeTypes = () => {
    dispatch({
      type: 'assetmanage.getNoticeTypes',
      callback: (data) => {
        setNoticeTypes(data)
      }
    })
  }

  return (
    <div style={{ lineHeight: '32px' }}>
    {
      (noticeTypes??[]).map((item, index) => (
        <Row key={index}>
          <Space>
            <Checkbox checked={(value??[]).indexOf(item.type) !== -1} value={item.type} style={{ width: 100 }} onChange={(e) => {
              if (e.target.checked) {
                onChange?.([...value??[], item.type])
              } else {
                onChange?.((value??[]).filter(item => item !== e.target.value))
              }
            }}>{item.desc}</Checkbox>
            <a onClick={() => {
               dispatch({
                type: 'assetmanage.getNoticeTemplate',
                payload: {
                  module: 'dataAsset',
                  type: item.desc
                },
                callback: (content) => {
                  modal.info({
                    title: '模版信息',
                    content: content??'',
                  })
                }
              })
            }}>查看通知模版</a>
          </Space>
        </Row>
      ))
    }
    {contextHolder}
    </div>
  )
}