import React from 'react'
import { Modal, Spin, Button, Form, Input, TreeSelect, Row, Col, Checkbox } from "antd"
import produce from "immer"

import { dispatch } from '../../../model'

const FC = (props) => {
  const { visible, item, action, onCancel } = props
  const [waiting, setWaiting] = React.useState(false)
  const [loading, setLoading] = React.useState(false)
  const [elements, setElements] = React.useState()

  const basicRef = React.useRef(null)

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

  const getElements = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.listComputableElements',
      callback: data => {
        setElements(data??[])
        setLoading(false)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

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

  const save = async () => {
    try {
      const row = await basicRef.current?.validate()
      setWaiting(true)
      dispatch({
        type: 'assetmanage.saveEvaluation',
        payload: {
          data: (action==='add')?row:{...item, ...row}
        },
        callback: data => {
          close(true)
        },
        error: () => {
          setWaiting(false)
        }
      })
    } catch (e) {
      
    }
  }

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

  return (
    <Modal
      visible={visible}
      footer={footer}
      width='50%'
      bodyStyle={{ padding: '15px 15px 0px 15px', overflowX: 'auto', maxHeight: '80vh' }}
      title='新增评估方案'
      centered destroyOnClose
      onCancel={() => { close() }}
    >
      <Spin spinning={loading || waiting}>
        <Basic ref={basicRef} item={item} elements={elements} />
      </Spin>
    </Modal>  
  )
}

export default FC

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

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

  React.useEffect(() => {
    if (item) {
      form?.setFieldsValue(item)
    }
  }, [item])

  return (
    <Form
      form={form}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      autoComplete="off"
    >
      <Form.Item
        label="方案名称"
        name="name"
        rules={[{ required: true, message: '请输入方案名称!' }]}
      >
        <Input placeholder="请输入方案名称" /> 
      </Form.Item>
      <Form.Item
        name='dirs'
        label='资产目录'
        rules={[{ required: true, message: '请选择资产目录!' }]}
      >
        <AssetCatalogItem />
      </Form.Item>
      <Form.Item
        name='elementIds'
        label='评估要素'
        rules={[{ required: true, message: '请选择评估要素!' }]}
      >
        <Checkbox.Group style={{ width: '100%' }}>
          <Row>
          {
            (elements??[]).map((item, index) => {
              return (
                <Col span={6} key={index}>
                  <Checkbox
                    value={item.id}
                    style={{
                      lineHeight: '32px',
                    }}
                  >
                    {item.name}
                  </Checkbox>
                </Col>
              )
            })
          }
          </Row>
        </Checkbox.Group>       
      </Form.Item>
    </Form>
  )
})

const AssetCatalogItem = ({ value, onChange }) => {
  const [loadingTreeData, setLoadingTreeData] = React.useState(false)
  const [treeData, setTreeData] = React.useState()

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

  const treeData1 = React.useMemo(() => {
    if (treeData) {
      const newTreeData = produce(treeData, draft => {
        const setNode = (g) => {
          g.key = g.nodeId
          g.title = g.text
          g.value = g.nodeId
          g.children?.forEach((child) => {
            setNode(child)
          })
        }

        draft.forEach((child) => {
          setNode(child)
        })
      })

      return newTreeData
    }

    return undefined
  }, [treeData])

  const getTreeData = () => {
    setLoadingTreeData(true)
    dispatch({
      type: 'assetmanage.queryAssetDirectoryAsTree',
      callback: data => {
        setLoadingTreeData(false)
        setTreeData(data)
      },
      error: () => {
        setLoadingTreeData(false)
      }
    }) 
  }

  return (
    <TreeSelect
      value={(value??[]).map(item => {
        return {
          label: item.name,
          value: item.id
        }
      })}
      loading={loadingTreeData}
      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
      treeData={treeData1}
      placeholder="请选择资产目录"
      treeDefaultExpandAll
      treeCheckable={true}
      treeCheckStrictly={true}
      showCheckedStrategy={TreeSelect.SHOW_ALL}
      onChange={(value) => {
        onChange?.((value??[]).map(item => {
          return {
            id: item.value,
            name: item.label
          }
        }))
      }}
    />
  )
}