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, {
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from "@ant-design/pro-form";
import { Button, Col, Drawer, Modal, Row, Spin, Image, message } from "antd";
import ProTable from "@ant-design/pro-table";
import { handleDailyException, 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";
import east from "@/assets/DataVerification/east.png";
import south from "@/assets/DataVerification/south.png";
import west from "@/assets/DataVerification/west.png";
import north from "@/assets/DataVerification/north.png";
import moment from "moment";

const checkDetail: React.FC<{ currentRow?: any, currentUser: any, onRef: any, closeModal: any, handleGetTableList: any, handleChangeShowDisable?: any }> = ({ currentRow, currentUser, onRef, closeModal, handleGetTableList, handleChangeShowDisable }) => {
  const formRef = useRef()
  const timeFormRef = useRef()
  const modalRef = useRef()
  // 显示的加载框
  const [showDetailLoading, setShowDetailLoading] = useState<boolean>(false)
  // 操作记录表格数据
  const [tableData, setTableData] = useState<any>()
  // 详情
  const [dataDetail, setDataDetail] = useState<any>()
  // 流水冲正的表格数据
  const [supplementData, setSupplementData] = useState<any>()
  // 显示抽屉
  const [showDrawer, setShowDrawer] = useState<boolean>(false)
  // 显示悬浮框
  const [showModal, setShowModal] = useState<boolean>(false)
  // 流水冲正表格的columns
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInSearch: true,
      width: 70,
    },
    {
      title: '操作类型',
      dataIndex: 'OPERATELOG_TYPE ',
      hideInSearch: true,
      width: 120,
      valueEnum: {
        3000: { text: '无效数据' },
        3001: { text: '回退数据' },
        3002: { text: '变更日期' },
        3003: { text: '变更金额' },
      },
      render: (_, record) => {
        return <span>{
          record.OPERATELOG_TYPE === 3000 ? '无效数据' :
            record.OPERATELOG_TYPE === 3001 ? '回退数据' :
              record.OPERATELOG_TYPE === 3002 ? '变更日期' :
                record.OPERATELOG_TYPE === 3003 ? '变更金额' :
                  record.OPERATELOG_TYPE === 3004 ? '有效数据' : ''}</span>
      }
    },
    {
      title: '操作人员',
      dataIndex: 'USER_NAME',
      hideInSearch: true,
    },
    {
      title: '操作时间',
      dataIndex: 'OPERATE_DATE',
      hideInSearch: true,
    },
    {
      title: '操作说明',
      width: 500,
      ellipsis: true,
      dataIndex: 'OPERATELOG_DESC',
      hideInSearch: true,
    }
  ]
  // 显示悬浮框
  const handleShowModal = () => {
    setShowModal(true)
  }

  // 日期账期异常处理的  1保存   2回退   3无效
  const handleError = async (type: number, time?: any) => {
    let req = {}
    if (type === 1) {
      req = {
        OperateType: type,
        EndaccountIds: currentRow.Endaccount_Id,
        StatisticsDate: moment(time).format('YYYY-MM-DD')
      }
    }

    const data = await handleDailyException(req)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
      closeModal()
      handleGetTableList()
    } else {
      message.error(data.Result_Desc)
    }
  }


  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'
    })
    timeFormRef.current?.setFieldsValue({
      adjustTime: data.Statistics_Date
    })
    if (data.OPERATELOGList && data.OPERATELOGList.length > 0) {
      data.OPERATELOGList.forEach((item: any, index: number) => {
        item.key = index + 1
      })
    }
    setTableData(data.OPERATELOGList)
    setShowDetailLoading(false)
    handleChangeShowDisable(false)
  }, []);

  useImperativeHandle(onRef, () => ({
    showDetailLoading,
    formRef,
    handleShowModal
  }));
  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
          formRef={formRef}
          onFinishFailed={(values, errorFields, outOfDate) => {
            if (values.errorFields && values.errorFields.length > 0) {
              message.error('请填写操作说明！')
            }
          }}
          submitter={{
            // 清空表单自带的按钮
            render: (props, doms) => {
              return []
            }
          }}
        >
          <div className={'contentDetail'}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <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
                }
                console.log('dataDetail', dataDetail)
                console.log('req', req)
                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="审核意见"
                    disabled
                    name='Approved_Info'
                    fieldProps={{
                      placeholder: "",
                    }}
                  />
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <ProFormTextArea
                    label="操作说明"
                    name='Review_Info'
                    rules={[
                      {
                        required: true,
                        message: '请输入操作说明'
                      }
                    ]}
                    fieldProps={{
                      placeholder: "",
                    }}
                  />
                </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>
                <Col span={6}>
                  <ProForm
                    formRef={timeFormRef}
                    submitter={{
                      // 清空表单自带的按钮
                      render: (props, doms) => {
                        return []
                      }
                    }}
                  >
                    <div style={{ display: 'flex' }}>
                      <ProFormDatePicker
                        label='统计日期'
                        name='adjustTime'
                        disabled={currentRow?.Endaccount_State === 0}
                        rules={[
                          {
                            required: true,
                            message: '请选择调整时间'
                          }
                        ]}
                      />
                      <Button disabled={currentRow?.Endaccount_State === 0} style={{ marginTop: '30px', marginLeft: '8px' }} type='primary' onClick={() => {
                        timeFormRef.current?.validateFields().then(res => {
                          if (res) {
                            handleError(1, res.adjustTime)
                          }
                        })
                      }}>调整</Button>
                    </div>
                  </ProForm>
                </Col>
                {/* <Col span={6}> */}
                {/*   <Button disabled={currentRow?.Endaccount_State===0} style={{marginTop: '30px'}} type='primary' onClick={()=>{ */}
                {/*     timeFormRef.current?.validateFields().then(res=>{ */}
                {/*       if (res){ */}
                {/*         handleError(1,res.adjustTime) */}
                {/*       } */}
                {/*     }) */}
                {/*   }}>调整</Button> */}
                {/* </Col> */}
              </Row>
            </div>

            <p className={'detailTitle'}>操作记录</p>
            <div>
              <ProTable
                search={false}
                options={false}
                dataSource={tableData}
                columns={columns}
                pagination={{ pageSize: 10 }}
              />
            </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' }}>
          <ProTable
            search={false}
            options={false}
            columns={columns}
            dataSource={supplementData}
          >
          </ProTable>
        </div>
      </Drawer>
    </div>
  )
}
export default checkDetail
