import React from "react"
import { Space, Button, Descriptions, Form, Input, Tooltip, Typography, Select, Spin, Modal } from "antd"
import produce from "immer"

import Table from '../../../util/Component/Table'
import { isSzseEnv, getQueryParam, showMessage, showNotifaction } from "../../../util"
import { dispatch } from '../../../model'; 
import { AssetDraftReference } from "../../../util/constant"
import UpdateAsset from "../AssetManage/Component/AssetDetailDrawer"

const FC = (props) => {
  const [loading, setLoading] = React.useState(false)
  const [waiting, setWaiting] = React.useState(false)
  const [data, setData] = React.useState()
  const [form] = Form.useForm()
  const [modal, contextHolder] = Modal.useModal()

  const id = getQueryParam('id', props.location?.search)

  const listRef = React.useRef()

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

  const getDetail = () => {
    setLoading(true)
    dispatch({
      type: 'assetmanage.processDetail',
      payload: {
        processId: id,
      },
      callback: (data) => {
        setLoading(false)
        setData(data)
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onSubmitClick = async () => {
    try {
      const rows = await form.validateFields()
      await listRef.current?.validate()
      const tableData = listRef.current?.tableData

      console.log('table data', tableData)
      setWaiting(true)
      dispatch({
        type: 'assetmanage.auditProcess',
        payload: {
          data: {
            ...data,
            ...rows,
            submitItems: tableData,
          }
        },
        callback: (data) => {
          setWaiting(false)

          modal.success({
            title: '提示',
            content: '提交成功',
            okText: '确定',
            onOk: () => {
              getDetail()
            }
          })
        },
        error: () => {
          setWaiting(false)
        }
      })
    } catch (e) {
      
    }
  }

  return (
    <div className='p-5' style={{ height: '100%', overflow: 'auto' }}>
      <Spin spinning={loading||waiting}>
        {
          data && !data?.hasDeal && <div className='flex' style={{ justifyContent: 'end' }}>
            <Space>
              <Button onClick={onSubmitClick}>提交</Button>
            </Space>
          </div>
        }
        <div>
          <div className='flex my-3' style={{ justifyContent: 'center' }}>
            <h3>资产评审流程</h3>
          </div>
          <Descriptions bordered size='small' column={2}>
            <Descriptions.Item label="流程名称">{data?.applyUser?.userName?`${data?.applyUser?.userDisplayName}(${data?.applyUser?.userName})发起的物理模型评审流程`:''}</Descriptions.Item>
            <Descriptions.Item label="送审人">{`${data?.applyUser?.userDisplayName}(${data?.applyUser?.userName})`}</Descriptions.Item>
            <Descriptions.Item label="送审时间">{data?.createTimestamp?new Date(data?.createTimestamp).toLocaleString():''}</Descriptions.Item>
            <Descriptions.Item label="送审说明">{data?.desc}</Descriptions.Item>
            <Descriptions.Item label="附件">
              <Space>
              {
                (data?.attachments??[]).map(item => (
                  <a key={item.fileId} onClick={() => {
                    window.open(`/api/dataassetmanager/fileApi/downloadFile?fileId=${item.fileId}`)
                  }}>
                    {item.fileName}
                  </a>
                ))
              }
              </Space>
            </Descriptions.Item>
          </Descriptions>
        </div>
        <div className='my-5'>
          <Form
            form={form}
            autoComplete="off"
          >
            <Form.Item
              label="流程意见"
              name="opinion"
              rules={[{ required: true, message: '请填写流程意见!' }]}
              style={{ marginBottom: 0 }}
            >
              <Input.TextArea 
                rows={4} 
                allowClear 
                placeholder='请输入流程意见' 
                readOnly={data?.hasDeal}
              />
            </Form.Item>
          </Form>
        </div>
        <List ref={listRef} data={data} />
      </Spin>
      {contextHolder}
    </div>
  )
}

export default FC

const List = React.forwardRef(function ({data}, ref) {
  const [tableData, setTableData] = React.useState()
  const [updateAssetParams, setUpdateAssetParams] = React.useState({
    visible: false,
    id: undefined,
    dirId: undefined,
  })

  const [form] = Form.useForm()

  React.useEffect(() => {
    setTableData(data?.submitItems)
  }, [data])

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

  const cols = [
    {
      title: '序号',
      dataIndex: 'index',
      width:60,
      render:(_, __, index)=> (index+1)
    },
    {
      title: '资产名称',
      dataIndex: 'enName',
      width: 160,
      ellipsis: false,
      render: (text, record, index) => (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
            <a onClick={() => {
              setUpdateAssetParams({
                visible: true,
                id: record.draftId,
              })
            }}>{text}</a>
          </Typography.Text>
        </Tooltip>
      )
    },
    {
      title: '中文名称',
      dataIndex: 'cnName',
      width: 160,
      render: (text, record) => (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
            {text}
          </Typography.Text>
        </Tooltip>
      )
    },
    {
      title: '编码',
      dataIndex: 'code',
      width: 160,
      render: (text, record) => (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
            {text}
          </Typography.Text>
        </Tooltip>
      )
    },
    {
      title: '路径',
      dataIndex: 'path',
      width: 120,
      render: (text, record) => (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
            {text}
          </Typography.Text>
        </Tooltip>
      )
    },
    {
      title: '送审备注',
      dataIndex: 'remarks',
      render: (text, record) => (
        <Tooltip title={text}>
          <Typography.Text ellipsis={true}>
            {text}
          </Typography.Text>
        </Tooltip>
      )
    },
    {
      title: <span>
        <span style={{
          marginRight: 4,
          color: '#ff4d4f',
        }}>*</span>
        评审结论
      </span>,
      dataIndex: 'auditStatus',
      width: 120,
      className: 'highlight',
      render: (text, record, index) => {
        form?.setFieldsValue({ [`auditStatus${index}`]: text })
        return (
          <>
          {
            data?.hasDeal ? <Tooltip title={text==='0'?'不通过':'通过'}>
              <Typography.Text ellipsis={true}>
                {text==='0'?'不通过':'通过'}
              </Typography.Text>
            </Tooltip> : <Form.Item name={`auditStatus${index}`}
              rules={[{ required: true, message: '请选择评审结论!' }]}
              style={{ marginBottom: 0 }}
            >
              <Select 
                placeholder='请选择' 
                allowClear
                style={{
                  width: '100%'
                }}
                onChange={(val) => {
                  setTableData(prev => {
                    return produce(prev, (draft) => {
                      draft[index].auditStatus = val
                    })
                  })
                }}
              >
                <Select.Option value='1'>通过</Select.Option>
                <Select.Option value='0'>不通过</Select.Option>
              </Select>
            </Form.Item> 
          }
          </>
        )
      } 
    },
    {
      title: '评审意见',
      dataIndex: 'auditMsg',
      className: 'highlight',
      render: (text, record, index) => (
        <>
          {
            data?.hasDeal ? <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </Typography.Text>
            </Tooltip> : <Form.Item style={{ marginBottom: 0 }}>
              <Input.TextArea rows={1}
                value={text}
                autoSize={{ minRows: 1, maxRows: 3 }}
                allowClear
                onChange={(e) => {
                  setTableData(prev => {
                    return produce(prev, (draft) => {
                      draft[index].auditMsg = e.target.value
                    })
                  })
                }} 
              />
            </Form.Item>
          }
        </>
      )
    },
  ]

  return (
    <Form form={form}>
      <Table
        columns={cols??[]}
        dataSource={tableData??[]}
        pagination={false}
      />

      <UpdateAsset
        {...updateAssetParams}
        readonly={true}
        action='detail'
        reference={AssetDraftReference}
        onCancel={() => {
          setUpdateAssetParams({
            visible: false,
            id: undefined,
            dirId: undefined,
          })
        }}
      />
    </Form>
  )
})