import { useEffect, useRef, useState } from 'react'
import { ActionsButton } from 'components'
import style from '../style.module.scss'
import { AntUploadProps, addExampleFile, deleteExampleFile } from 'api'
import { UploadOutlined } from '@ant-design/icons'
import { confirm } from 'utils'
import { 
  Modal, 
  Button, 
  Table, 
  Empty,
  Form, 
  Input, 
  Select,
  Upload,
  message,
  ConfigProvider
} from 'antd'
import { 
  useDispatch, 
  useSelector, 
  fetchExampleFileTypes, 
  fetchExampleFiles,
  exampleTypeFiles
} from 'store'

import type { Example, ExampleFile } from "api";
import type { ColumnsType } from 'antd/es/table'
import type { FormInstance } from 'antd/es/form'
import type { UploadProps } from 'antd'


export type ExampleScenesProps = Pick<Example, 'caseId'> & { onClose: () => void,}

export const ExampleFiles = (props: ExampleScenesProps) => {
  const [inertCaseId, setInsertCaseId] = useState<Example['caseId'] | null>(null)
  const typeFiles = useSelector(exampleTypeFiles)
  const dispatch = useDispatch()
  const fileColumns: ColumnsType<ExampleFile> = [
    {
      width: '300px',
      title: '名称',
      dataIndex: 'filesTitle',
      key: 'filesTitle',
    },
    {
      width: '200px',
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render(data: ExampleFile) {
        const actions = [
          {
            text: '查看', 
            action: () => {
              window.open(data.filesUrl)
            }, 
          },
          {
            text: '删除', 
            action: async () => {
              if (await confirm('确定要删除此数据？')) {
                await deleteExampleFile(data)
                dispatch(fetchExampleFiles({ caseId: props.caseId }))
              }
            }, 
          },
        ]
        return <ActionsButton actions={actions} />
      }
    },
  ]


  useEffect(() => {
    dispatch(fetchExampleFileTypes())
    dispatch(fetchExampleFiles({ caseId: props.caseId }))
  }, [dispatch, props.caseId])

  const total = typeFiles.reduce((t, c) => t + c.children.length ,0)

  const renderContent = total 
    ? typeFiles.map((typeFile, i) => 
      !!typeFile.children.length && (
          <>
            <p className={style['file-type-name']}>{typeFile.filesTypeName}</p>
            <Table 
              showHeader={false}
              key={typeFile.filesTypeId}
              pagination={false}
              columns={fileColumns}
              dataSource={typeFile.children}
            />
          </>
        )
      )
    : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  
  const renderAddFile = inertCaseId 
    && <AddExampleFile caseId={inertCaseId} onClose={() => setInsertCaseId(null)} />

  return (
    <Modal 
      width="800px"
      title="卷宗管理" 
      visible={true} 
      onOk={props.onClose} 
      onCancel={props.onClose}
      okText="确定"
      cancelText="取消"
    >
      {renderAddFile}
      <div className={style['model-header']}>
        <Button type="primary" onClick={() => setInsertCaseId(props.caseId)}>
          上传附件
        </Button>
      </div>
      <ConfigProvider renderEmpty={() => null}>
        <Table 
          className={style['header-table']}
          pagination={false}
          columns={fileColumns}
          dataSource={[]}
        />
      </ConfigProvider>
      { renderContent }
    </Modal>
  )
}

export type AddExampleFileProps = Pick<Example, 'caseId'> & { onClose: () => void,}
export const AddExampleFile = (props: AddExampleFileProps) => {
  const dispatch = useDispatch()
  const from = useRef<FormInstance | null>(null)
  const types = useSelector(state => state['example/file'].types)
  const renderTypeOptions = types.map(type => (
    <Select.Option value={type.filesTypeId} children={type.filesTypeName} key={type.filesTypeId} />
  ))
  const onFinish = async (values: any) => {
    if (!values.filesUrl.fileList.length) {
      message.error('附件文件不能为空！')
    }
    await addExampleFile({
      ...values,
      caseId: props.caseId,
      filesUrl: values.filesUrl.fileList[0].response
    })
    props.onClose()
    dispatch(fetchExampleFiles({ caseId: props.caseId }))
  };
  const onSubmit = () => {
    from.current?.submit()
  }

  const uploadProps: UploadProps = {
    ...AntUploadProps,
    listType: 'picture',
    maxCount: 1,
    onPreview(file) {
      window.open(file.response)
    }
  };

  return (
    <Modal 
      width="400px"
      title="上传附件" 
      visible={true} 
      onOk={onSubmit} 
      onCancel={props.onClose}
      okText="确定"
      cancelText="取消"
    >
      <Form 
        labelCol={{span: 8}} 
        wrapperCol={{span: 16}}  
        name="control-ref" 
        ref={from} 
        onFinish={onFinish}
      >
        <Form.Item name="filesTypeId" label="附件类型" rules={[{ required: true, message: '附件类型不能为空' }]}>
          <Select placeholder="选择附件类型">
            {renderTypeOptions}
          </Select>
        </Form.Item>
        <Form.Item name="filesUrl" label="上传附件" rules={[{ required: true, message: '附件文件不能为空' }]}>
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>请上传pdf/word/jpg格式文件</Button>
          </Upload>
        </Form.Item>
        <Form.Item name="filesTitle" label="附件标题" rules={[{ required: true, message: '附件标题不能为空' }]}>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}