import React, {useEffect, useImperativeHandle, useRef, useState} from "react";
import closeIcon from "@/assets/brand/closeIcon.png";
import './auditDetail.less'
import ProForm, {ProFormDigit, ProFormText, ProFormTextArea} from "@ant-design/pro-form";
import {Col, Row, Image, Modal, Upload, Button, message} from "antd";
import ProTable from "@ant-design/pro-table";
import {handleGetAuditDetail} from "@/pages/DataVerification/list/service";
import moment from "moment";
import {deleteAHYDPicture, deletePicture, uploadAHYDPicture, uploadPicture} from "@/services/picture";
import type {UploadFile} from "antd/es/upload/interface";

// 上传资质图片
const customUploadRequest = async (fileList: UploadFile[], tableId: string) => {
  if (!fileList.length) {
    message.error("您上传的图片不存在.")
    return false
  }
  const formData = new FormData();
  fileList.forEach((file: any) => {
    formData.append('files[]', file.originFileObj);
  });

  formData.append('TableName', 'CHECKACCOUNT');
  formData.append('TableId', tableId);
  const success = await uploadAHYDPicture(formData)
  if (success) {
    return true
  }
  return false
}




// currentDetail 父级的表单详情
const auditDetail: React.FC<{isShow: boolean,rowDetail: any,currentDetail?: any,onRef?: any}> = ({isShow, rowDetail,currentDetail,onRef}) => {
  const auditFormRef = useRef<any>()
  const [detailRow,setDetailRow] = useState<any>()
  const [showModal,setShowMoadl] = useState<boolean>(false)
  const [fileList,setFileList] = useState<any>()
  // 图片列表
  const [picList,setPicList] = useState<any>()
  // 查看记录表格数据
  const [viewRecords,setViewRecords] = useState<any>()
  const columns: any = [
    {
      dataIndex: 'OPERATE_DATE',
      title: '操作时间',
      render:(_,record)=>{
        return <span>{moment(record.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      dataIndex: 'USER_NAME',
      title: '操作人员',
    },
    {
      dataIndex: 'VIDEOLOG_TYPE ',
      title: '操作类型',
      render:(_,record)=>{
        return <span>{record.VIDEOLOG_TYPE===1000?'查看视频':record.VIDEOLOG_TYPE===2000?'稽核审核':record.VIDEOLOG_TYPE===3000?'下载视频':''}</span>
      }
    },
    {
      dataIndex: 'VIDEOLOG_DESC',
      title: '审核意见',
    },
  ]

  useEffect(  () => {
    if (isShow && rowDetail){
      console.log('rowDetail',rowDetail)
      handleDetail()
    }

  }, [rowDetail]);

  const handleDetail = async ()=>{
    const req = {
      CheckAccount_Id:rowDetail.Audit_Id
    }
    const data = await handleGetAuditDetail(req)
    auditFormRef.current?.setFieldsValue(data)
    if (data){
      setDetailRow(data)
      setViewRecords(data.VideoLogList)
      console.log('data',data)
      const imgList: any = []
      if (data.ImageList && data.ImageList.length>0){
        data.ImageList.forEach((item: any)=>{
          imgList.push({ImageId:item.ImageId,status:'done',url:item.ImageUrl,name:item.ImageName,uid:item.ImageId,ImagePath:item.ImagePath})
        })
        setPicList(imgList)
        setFileList(imgList)
      }
    }
  }

  useImperativeHandle(onRef, () => ({
    showModal,
    setShowMoadl,
    handleDetail,
    auditFormRef,
    detailRow,
    picList
  }));


  return (
    <div className={'auditDetail'}>
      <div className={'detailTop'}>
        <div style={{display:'flex',alignItems:'center'}}>
          <span className={'detailTitle'}>稽核反馈表</span>
        </div>
        <img className={'closeIcon'} src={closeIcon}/>
      </div>

      <div className={'detailContent'}>
        <div className={'contentTop'}>
          <span className={'label'}>{`收银机号： ${currentDetail?.MachineCode}`}</span>
          <span className={'label'}>{`稽查时间： ${moment(detailRow?.Audit_Time).format('YYYY-MM-DD HH:mm:ss')}`}</span>
        </div>
        <ProForm
          layout={'horizontal'}
          formRef={auditFormRef}
          onFinish={()=>{

          }}
          submitter={{
            // 清空表单自带的按钮
            render: () => {
              return []
            }
          }}
        >
          <div className={'contentTitle'}>稽查信息</div>
          <div className={'formBox'}>
            <Row>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Audit_ErrorRate'
                  label='稽核误差率'
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Different_Price'
                  label='长短款额'
                />
              </Col>
              {
                detailRow?.Different_Price<0?
                  <Col span={8}>
                    <ProFormText
                      name='Add_Amount'
                      readonly
                      label='补入现金'
                    />
                  </Col>:
                  <Col span={8}>
                    <ProFormDigit
                      name='Add_Amount'
                      readonly={detailRow?.Add_Amount || detailRow?.Add_Amount===0}
                      label='流水冲正'
                      rules={[
                        {
                          required: true,
                          message: '请输入流水冲正',
                        },
                      ]}
                    />
                  </Col>
              }

            </Row>

            <Row>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='TotalSell_Amount'
                  label='对客营收'
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Cash_Pay'
                  label='稽查现金'
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Cash'
                  label='对客现金'
                />
              </Col>
            </Row>

            <Row>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Audit_Type'
                  label='稽查类型'
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Worker_Name'
                  label='稽查人员'
                />
              </Col>
              <Col span={8}>
                <ProFormText
                  readonly
                  name='Cashier_Name'
                  label='收银人员'
                />
              </Col>
            </Row>

            <Row>
              <Col span={24}>
                <ProFormTextArea
                  label="稽核反馈"
                  name='CheckAccount_Desc'
                />
              </Col>
            </Row>
          </div>
          <div className={'contentTitle'}>图片信息</div>
          <div className={'imgBox'}>
            {/* { */}
            {/*   detailRow?.ImageList && detailRow?.ImageList.length>0? */}
            {/*   detailRow?.ImageList.map((item: any)=>{ */}
            {/*     return <Image className={'imgItem'} src={item.ImageUrl}/> */}
            {/*   }):'' */}
            {/* } */}
            <Upload
              listType="picture-card"
              fileList={picList}
              onRemove={async (file)=>{
                console.log('file',file)
                const list: any = []
                // const success = await deletePicture(file.ImagePath, file.uid)
                const success = await deleteAHYDPicture(file.ImagePath, file.uid)
                console.log('success',success)
                picList.forEach((item=>{
                  if (item.uid!==file.uid){
                    list.push(item)
                  }
                }))
                setPicList(list)
                setFileList(list)
                if (success){
                  message.success('删除成功')
                }else{
                  message.error('删除失败')
                }
              }}
            >
            </Upload>
          </div>
          <div className={'contentTitle'}>查看记录</div>

          <ProTable
            search={false}
            options={false}
            columns={columns}
            dataSource={viewRecords}
          >

          </ProTable>
        </ProForm>
      </div>
      <Modal
        title="上传单据"
        open={showModal}
        destroyOnClose
        onCancel={()=>{
          setShowMoadl(false)
        }}
        onOk={()=>{
          console.log('fileList',fileList)

          const waitUpload = fileList.filter(n => n.status === 'done')
          if (waitUpload.length > 0) {
            customUploadRequest(waitUpload,rowDetail.Audit_Id).then((uploadSuccess: any)=>{
              if (uploadSuccess) {
                console.log('uploadSuccess',uploadSuccess)
                message.success('上传成功')
                handleDetail()
                setPicList(waitUpload)
                setShowMoadl(false)
                return true
              }
              return false
            })
          }else{
            message.error('请先上传图片')
          }
        }}
      >
        <Upload
          listType="picture-card"
          fileList={fileList}
          onChange={(e)=>{
            console.log('e',e)
            setFileList(e.fileList)
          }}
        >
          <span>点击上传</span>
        </Upload>
      </Modal>
    </div>
  )
}

export default auditDetail
