import React,{useState,useEffect,useMemo} from "react"
import {Modal,Spin,Button,Form,Row,Col,Upload,Input,Tooltip,Typography,Table, message} from "antd"
import {UploadOutlined} from "@ant-design/icons"
import { AuditUsersItem,AttachesItem } from "../../AssetDraft/start-flow"
import { showMessage, showNotifaction } from '@/util'
import { dispatch } from '@/model'
import produce from 'immer'
import {useGetAssetQuestion,useGetFlowAction} from "../hooks/Detail"

const AssetFlow:React.FC<any>=(props)=>{

    const {visible,onCancel,item} = props
    const [uploading, setUploading] = useState(false)
    const [tableDatas, setTableData] = React.useState()

    const {loading,saveQuestionItem} = useGetFlowAction()

    const [form] = Form.useForm()

    const ids = useMemo(()=>{
      if(item.length){
        return (item||[]).map((item:any)=>{
          return item.id
        })
      }else{
        return []
      }
      
    },[item])

    const {tableData,tableloading} = useGetAssetQuestion({ids})

    useEffect(()=>{
      setTableData(tableData)
    },[tableData])

    const close=()=>{
      onCancel?.()
      form.resetFields()
      setTableData(tableData)
    }

    const save=()=>{
      form.validateFields().then((data)=>{
        data.submitItems=tableDatas;
        saveQuestionItem(data,()=>{
          message.success("操作成功")
          close()
        })
      })
    }

    const uploadProps = {
        beforeUpload: file => {
          const isLt5M = file.size / 1024 / 1024 <= 100
          if (!isLt5M) {
            showMessage('error', '上传文件限制最大100M')
            return false
          }
    
          setUploading(true)
          dispatch({
            type: 'assetmanage.uploadAttachment',
            payload: {
              fileList: [file],
            },
            callback: (data) => {
              setUploading(false)
              const prev = form?.getFieldValue('attachments')
              const newFileList = [...prev??[], data]
              form?.setFieldsValue({ attachments: newFileList })
            },
            error: () => {
              setUploading(false)
            }
          })
    
          return false
        },
        fileList: [],
      }

    const dprops:any={}

    const cols = [
        {
          title: '序号',
          dataIndex: 'index',
          width:60,
          render:(_, __, index)=> (index+1)
        },
        {
          title: '资产名称',
          dataIndex: 'enName',
          width: 160,
          render: (text, record) => (
            <Tooltip title={text}>
              <Typography.Text ellipsis={true}>
                {text}
              </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: '待完成属性',
          key: 'columns',
          dataIndex:'responsibilityAttributeMap',
          render: (text, record) => {
            const name = Object.values((text||{})).map((item:any)=>{
              return item.cnName
            })
            
            return (
              <Tooltip title={name.join(',')}>
                <Typography.Text ellipsis={true}>
                  {name.join(',')}
                </Typography.Text>
              </Tooltip>
            )
          }
        },
        {
          title: '送审备注',
          dataIndex: 'remarks',
          render: (_, __, index) => (
            <Input.TextArea rows={1}
              autoSize={{ minRows: 1, maxRows: 3 }}
              allowClear
              onChange={(e) => {
                setTableData(prev => {
                  return produce(prev, (draft) => {
                    draft[index].remarks = e.target.value
                  })
                })
              }} 
            />
          )
        },
    ]

    return(
        <Modal
            visible={visible}
            confirmLoading={loading}
            width='80%'
            bodyStyle={{ padding: '15px', overflowX: 'auto', height: '80vh' }}
            title='资产问责'
            centered 
            destroyOnClose
            onOk={save}
            onCancel={() => { close() }}
        >
            <Spin spinning={tableloading}>
                <Form
                    form={form}
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    autoComplete="off"
                    >
                    <Row gutter={10}>
                        <Col span={12}>
                        <Form.Item
                            label='评审人员'
                            name="nextAuditUsers"
                            style={{ marginBottom:15 }}
                            rules={[{ required: true, message: '请选择评审人员!' }]}
                        >
                            <AuditUsersItem {...dprops} />
                        </Form.Item>

                        <Form.Item
                            label='附件'
                            style={{ marginBottom:15 }}
                        >
                            <Upload {...uploadProps }>
                                <Button loading={uploading} icon={<UploadOutlined />}>点击上传</Button>
                            </Upload>
                        </Form.Item>

                        <Form.Item
                            label='已上传附件'
                            name='attachments'
                        >
                            <AttachesItem {...dprops} />
                        </Form.Item>
                        </Col>
                        <Col span={12}>
                        <Form.Item
                            label='送审说明'
                            name="opinion"
                            style={{ marginBottom:15 }}
                            rules={[{ required: true, message: '请填写送审说明!' }]}
                        >
                            <Input.TextArea rows={4} placeholder='请输入送审说明' />
                        </Form.Item>
                        </Col>
                    </Row>
                </Form>
                <Table
                    columns={cols??[]}
                    dataSource={tableDatas??[]}
                    pagination={false}
                    loading={tableloading}
                    rowKey="dataAssetId"
                />
            </Spin>
        </Modal>
    )
}

export default AssetFlow