import React, { useEffect, useRef, useState, useImperativeHandle } from "react";
import type { CurrentUser } from "@/models/user";
import './checkDetail.less'
import closeIcon from "@/assets/brand/closeIcon.png";
import ProForm, { ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import { Button, Col, Drawer, Modal, Row, Spin, Image } from "antd";
import ProTable from "@ant-design/pro-table";
import { handleGetAccountDetail, handleGetSupplement } from "@/pages/DataVerification/service";
import { getEndaccountPhoto, handleGetShopData } from "@/pages/DataVerification/list/service";
import ReportDetail from "@/pages/DataVerification/list/components/reportDetail";
import defaultIcon from "@/assets/brand/defaultIcon.png";
import fixed from "@/assets/DataVerification/fixed.png";
import allRealMoney from "@/assets/DataVerification/allRealMoney.png";

const checkDetail: React.FC<{ currentRow?: any, currentUser: any, onRef: any, handleChangeShowDisable: any }> = ({ currentRow, currentUser, onRef, handleChangeShowDisable }) => {
  const formRef = useRef()
  // 显示弹出框
  const [showModal, setShowModal] = useState<boolean>(false)
  // 显示抽屉
  const [showDrawer, setShowDrawer] = useState<boolean>(false)
  // 详情
  const [dataDetail, setDataDetail] = useState<any>()
  // 单品、香烟、移动支付报价抽屉
  const [quotationDrawer, setQuotationDrawer] = useState<boolean>(false)
  // 点击的是哪个报价查询
  const [quotationType, setQuotationType] = useState<number>(0)
  // 显示的加载框
  const [showDetailLoading, setShowDetailLoading] = useState<boolean>(false)
  // 流水冲正的表格数据
  const [supplementData, setSupplementData] = useState<any>()
  // 查看单据的悬浮框
  const [showSearchImg, setShowSearchImg] = useState<boolean>(false)
  // 单据图片列表
  const [searchImgList, setSearchImgList] = useState<any>()
  // 流水冲正表格的columns
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInSearch: true,
    },
    {
      title: '服务区名称',
      dataIndex: 'SERVERPART_NAME',
      hideInSearch: true,
      ellipsis: true,
      width: 100
    },
    {
      title: '门店名称',
      dataIndex: 'SHOPNAME',
      hideInSearch: true,
      ellipsis: true,
      width: 100
    },
    {
      title: '机器编码',
      dataIndex: 'MACHINECODE',
      hideInSearch: true,
      width: 100
    },
    {
      title: '商品名称',
      dataIndex: 'COMMODITY_NAME',
      hideInSearch: true,
      width: 100
    },
    {
      title: '冲正数量',
      dataIndex: 'SELLCOUNT',
      hideInSearch: true,
    },
    {
      title: '销售金额',
      dataIndex: 'FACTAMOUNT',
      hideInSearch: true,
    },
    {
      title: '冲正类型',
      dataIndex: 'COMMODITY_DESC',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '操作时间',
      dataIndex: 'OPERATE_DATE',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '冲正说明',
      dataIndex: 'SELLDESC',
      hideInSearch: true,
      width: 200,
      ellipsis: true
    },
  ]

  const handleGetQuotation = async (type: number) => {
    // type 1单品 2香烟 3移动支付
    setQuotationType(type)
    setQuotationDrawer(true)
  }
  // 请求单品数据 香烟和移动支付数据的接口
  useEffect(async () => {
    setShowDetailLoading(true)
    handleChangeShowDisable(true)
    const req = {
      EndaccountId: currentRow.Endaccount_Id
    }
    const data = await handleGetAccountDetail(req)
    setDataDetail(data)
    formRef.current?.setFieldsValue({
      ...data,
      Correct_TotalAmount: `${data.Correct_CashAmount}/${data.Correct_MobilePayAmount}`,
      Ticket_Average: data.Ticket_Count ? (data.TotalSell_Amount / data.Ticket_Count).toFixed(2) : '0'
    })
    setShowDetailLoading(false)
    handleChangeShowDisable(false)
  }, []);
  const handleEndaccountPhoto = async () => {
    setShowSearchImg(true)
    const data = await getEndaccountPhoto(dataDetail?.Endaccount_Id)
    setSearchImgList(data.List)
  }

  const handleGetApprovedInfo = () => {
    const data = formRef.current?.getFieldsValue('')
    return data
  }

  useImperativeHandle(onRef, () => ({
    showDetailLoading,
    handleEndaccountPhoto,
    handleGetApprovedInfo,
    formRef
  }));



  return (
    <div className={'checkDetail'}>
      {
        showDetailLoading ?
          <div className={'loading'}>
            <div className={'loadingBox'}>
              <Spin />
              <span style={{ marginLeft: '5px' }}>加载中...</span>
            </div>
          </div>
          : ''
      }
      <div className={'detailTop'}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <p className={'detailTitle'}>结账校验详情</p>
        </div>
        <img className={'closeIcon'} src={closeIcon} />
      </div>

      <div className={'contentTop'}>
        <img className={'brandIcon'} src={currentRow?.ServerpartShop_ICO || defaultIcon} />
        <div className={'contentTopRight'}>

          <div className={'detailRightTop'}>
            <div className={'nameType'}>
              <span className={'brandName'}>{currentRow?.ServerpartShop_Name}</span>
              {/* <span className={'brandType'}>{currentRow?.Business_Type}</span> */}
              <div className={'brandType'} style={{ background: currentRow?.Treatment_MarkState === -1 ? '#FFE4E4' : currentRow?.Treatment_MarkState === 1 ? '#EBEDEE' : '', color: currentRow?.Treatment_MarkState === -1 ? '#FF2F0D' : currentRow?.Treatment_MarkState === 1 ? '#686E75' : '' }}>
                {currentRow?.Treatment_MarkState === -1 ? '未上传' : currentRow?.Treatment_MarkState === 0 ? '待处理' : currentRow?.Treatment_MarkState === 1 ? '已处理' : ''}</div>
            </div>
            <div className={'serviceBox'}>
              <img className={'serviceIcon'} src={fixed} />
              <span className={'serviceName'}>{currentRow?.Serverpart_Name}</span>
            </div>
          </div>
          <div className={'detailBottom'}>
            <div className={'detailItem'}>
              <div className={'itemTop'}>
                <img className={'itemIcon'} src={allRealMoney} />
                <span className={'itemLabel'}>{`总销售额/元`}</span>
              </div>
              <span className={'itemValue'}>{dataDetail?.TotalSell_Amount}</span>
            </div>
            <div className={'detailItem'}>
              <div className={'itemTop'}>
                <img className={'itemIcon'} src={allRealMoney} />
                <span className={'itemLabel'}>{`缴款金额/元`}</span>
              </div>
              <span className={'itemValue'}>{dataDetail?.Payment_Amount}</span>
            </div>
            <div className={'detailItem'}>
              <div className={'itemTop'}>
                <img className={'itemIcon'} src={allRealMoney} />
                <span className={'itemLabel'}>{`实收金额/元`}</span>
              </div>
              <span className={'itemValue'}>{dataDetail?.Revenue_Amount}</span>
            </div>
          </div>
        </div>
      </div>

      <div className={'formDetail'}>
        <ProForm
          // layout={'horizontal'}
          formRef={formRef}
          submitter={{
            // 清空表单自带的按钮
            render: (props, doms) => {
              return []
            }
          }}
        >
          <div className={'contentDetail'}>

            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <p className={'detailTitle'}>账单校验说明</p>
              <Button style={{ marginRight: '8px' }} onClick={async () => {
                const req = {
                  EndaccountId: dataDetail?.Endaccount_Id,
                  Revenue_Amount: dataDetail?.Revenue_Amount,
                  FactAmount_Mobilepayment: dataDetail?.FactAmount_Mobilepayment
                }
                const data = await handleGetSupplement(req)
                if (data.CorrectList && data.CorrectList.length > 0) {
                  const list: any = []
                  data.CorrectList.forEach((item: any, index: number) => {
                    item.key = index + 1
                    list.push(item)
                  })
                  setSupplementData(list)
                }
                setShowDrawer(true);
              }}>流水冲正</Button>
            </div>
            <div className={'specialField'} >
              <div style={{ paddingLeft: '20px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: "space-between" }}>
                <div className={'fieldItem'}>
                  <ProFormText
                    label="实收金额"
                    name='Revenue_Amount'
                  />
                </div>
                <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'='}</span>
                <div className={'fieldItem'}>
                  <ProFormText
                    // readonly
                    disabled
                    label="总销售额"
                    name='TotalSell_Amount'
                  />
                </div>
                <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'+'}</span>
                <div className={'fieldItem'}>
                  <ProFormText
                    // readonly
                    disabled
                    label="冲正金额"
                    name='Correct_TotalAmount'
                  />
                </div>
                <div className={'fieldItem'} style={{ width: 'calc(25% + 10px)' }}>
                </div>
              </div>
            </div>
            <div style={{ paddingLeft: '20px', width: '100%' }}>
              <Row>
                <Col span={24}>

                  <ProFormTextArea
                    label="校验说明"
                    disabled
                    name='Description_Info'
                    fieldProps={{
                      placeholder: ""
                    }}
                  />
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <ProFormTextArea
                    label="审核意见"
                    name='Approved_Info'
                    rules={[
                      {
                        required: true,
                        message: '请输入审核意见'
                      }
                    ]}
                  />
                </Col>
              </Row>
            </div>

            <p className={'detailTitle'}>账单销售信息</p>
            <div style={{ paddingLeft: '20px', width: '100%' }}>
              <Row>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='客单数量'
                    name='Ticket_Count'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='客单均价'
                    name='AvgTicketPrice'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='优惠金额'
                    name='TotalOff_Amount'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='稽核补录'
                    name='Check_Replenish'
                  />
                </Col>
              </Row>
            </div>
            <div className={'specialField'} style={{ paddingLeft: '20px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: "space-between" }}>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="总销售额"
                  name='TotalSell_Amount'
                />
              </div>
              <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'='}</span>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="现金支付"
                  name='Cash_Amount'
                />
              </div>
              <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'+'}</span>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="移动支付"
                  name='MobilePay_Amount'
                />
              </div>
              <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'+'}</span>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="其他支付"
                  name='OtherPay_Amount'
                />
              </div>
            </div>
            <div className={'specialField'} style={{ paddingLeft: '20px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: "space-between" }}>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="长款金额"
                  name='Difference_Amount'
                />
              </div>
              <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'='}</span>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="缴款金额"
                  name='Payment_Amount'
                />
              </div>
              <span style={{ width: '10px', textAlign: 'center', marginTop: '15px' }}>{'+'}</span>
              <div className={'fieldItem'}>
                <ProFormText
                  // readonly
                  disabled
                  label="现金支付"
                  name='Cash_Amount'
                />
              </div>
              {/* <span>{'+'}</span> */}
              <div className={'fieldItem'} style={{ width: 'calc(25% + 10px)' }}>
              </div>
            </div>

            <p className={'detailTitle'}>结账单数据</p>
            <div style={{ paddingLeft: '20px', width: '100%' }}>
              <Row>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='收银机号'
                    name='MachineCode'
                  />
                </Col>
                <Col className={'CashierName'} span={6}>
                  <ProFormText

                    readonly
                    label='收银人员'
                    name='Cashier_Name'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='结账人员'
                    name='Checkout_Name'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='稽核人员'
                    name='Auditor_Name'
                  />
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='起始时间'
                    name='Endaccount_StartDate'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    readonly
                    label='结账时间'
                    name='Endaccount_EndDate'
                  />
                </Col>
              </Row>
            </div>



            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <p className={'detailTitle'}>单品数据</p>
              <Button onClick={() => {
                handleGetQuotation(1)
              }}>查询单品报表</Button>
            </div>
            <div style={{ paddingLeft: '20px', width: '100%' }}>
              <Row gutter={8}>
                <Col span={6}>
                  <ProFormText
                    label='销售数量'
                    disabled
                    readonly
                    name='SellCount_Sale'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    label='销售金额'
                    disabled
                    readonly
                    name='FactAmount_Sale'
                  />
                </Col>
              </Row>
            </div>
            {
              dataDetail?.ShowCigarette ?
                <>
                  <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <p className={'detailTitle'}>香烟数据</p>
                    <Button onClick={() => {
                      handleGetQuotation(2)
                    }}>查询香烟数据</Button>
                  </div>
                  <div style={{ paddingLeft: '20px', width: '100%' }}>
                    <Row gutter={8}>
                      <Col span={6}>
                        <ProFormText
                          label='销售数量'
                          disabled
                          readonly
                          name='SellCount_Cigarette'
                        />
                      </Col>
                      <Col span={6}>
                        <ProFormText
                          label='销售金额'
                          disabled
                          readonly
                          name='FactAmount_Cigarette'
                        />
                      </Col>
                    </Row>
                  </div>
                </>
                : ''
            }
            <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <p className={'detailTitle'}>移动支付</p>
              <Button onClick={() => {
                handleGetQuotation(3)
              }}>查询移动支付</Button>
            </div>
            <div style={{ paddingLeft: '20px', width: '100%' }}>
              <Row gutter={8}>
                <Col span={6}>
                  <ProFormText
                    label='客单数量'
                    disabled
                    readonly
                    name='TicketCount_Mobilepayment'
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    label='销售金额'
                    disabled
                    readonly
                    name='FactAmount_Mobilepayment'
                  />
                </Col>
              </Row>
            </div>
            {/* <div  style={{paddingLeft:'20px',width: '100%'}}> */}
            {/*    */}
            {/*   <Button onClick={()=>{ */}
            {/*     setShowModal(true) */}
            {/*   }}>帮助说明</Button> */}
            {/* </div> */}
          </div>
        </ProForm>
      </div>

      {/* 流水冲正的抽屉 */}
      <Drawer
        width={'60%'}
        closable={false}
        visible={showDrawer}
        bodyStyle={{ padding: 0 }}
        destroyOnClose={true}
        onClose={() => {
          setShowDrawer(false);
        }}
        footer={
          <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={() => { setShowDrawer(false) }}>取消</Button>
          </div>
        }
      >
        <div style={{ width: '100%', height: '100%', boxSizing: 'border-box', padding: '24px' }}>
          <p style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '8px' }}>冲正商品列表</p>
          <ProTable
            search={false}
            options={false}
            columns={columns}
            dataSource={supplementData}
          >
          </ProTable>
        </div>
      </Drawer>
      {/* 三个报价的抽屉 */}
      <Drawer
        width={'60%'}
        closable={false}
        visible={quotationDrawer}
        bodyStyle={{ padding: 0 }}
        destroyOnClose={true}
        onClose={() => {
          setQuotationDrawer(false);
        }}
        footer={
          <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
            <Button onClick={() => { setQuotationDrawer(false) }}>取消</Button>
          </div>
        }
      >
        <ReportDetail currentUser={currentUser} queryRecords={quotationDrawer} selectQueryType={quotationType} currentItem={dataDetail} currentRow={currentRow} />
      </Drawer>

      <Modal
        title="帮助说明"
        width={700}
        destroyOnClose={true}
        open={showModal}
        onCancel={() => {
          setShowModal(false)
        }}
        footer={() => (<></>)}
      >
        <div>
          <p style={{ color: "red" }}>注：1、如出现长款，说明系统交易记录缺失，需在系统内进行流水冲正补回。</p>
          <p style={{ color: "red", textIndent: '2rem' }}>2、如移动支付出现校验失败，说明服务器交易记录返回失败，需在系统内进行移动冲正补回。</p>
          <p style={{ color: "red", textIndent: '2rem' }}>3、结账校验公式为：实收金额 = 总销售额 + 冲正金额。</p>
          <p style={{ color: "red", textIndent: '2rem' }}>4、长短款额公式为：长短款额 = 缴款金额 + 移动支付 + 消费券 - 总销售额。</p>
        </div>
      </Modal>

      <Modal
        title="查看单据"
        width={700}
        destroyOnClose={true}
        open={showSearchImg}
        onCancel={() => {
          setShowSearchImg(false)
        }}
        footer={() => (<></>)}
      >
        <div>
          {
            searchImgList && searchImgList.length > 0 ?
              <>
                {
                  searchImgList.map((item: any) => {
                    return <Image style={{ width: '200px', height: '200px', marginRight: '8px' }} src={item.ImageUrl} />
                  })
                }
              </>
              : '还未上传凭证'
          }
        </div>
      </Modal>
    </div>
  )
}
export default checkDetail
