import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Button, Col, Drawer, message, Modal, Popconfirm, Row } from "antd";
import { useRef, useState } from "react";
import moment from 'moment'
import { handleApprovePeriodAccount, handleGetPictureList } from "../service";
import YearContentTable from "./yearContentTable";
import AfterSettlement from "./afterSettlement";
import Draggable from "react-draggable";
import YearExamineTable from "./yearExamineTable";
import ReviewProcess from "../../revenueConfirmation/components/ReviewProcess";
import ProForm, { ProFormRadio, ProFormSelect, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import { handleGetAPPROVALROUTEDetail, handleGetGetBUSINESSAPPROVALDetail } from "../../ShopExpenseDetail/service";
import { handleGetBUSINESSAPPROVALDetail } from "@/pages/examine/monthSettlement/service";
import MonthSettlement from "../../revenueConfirmation/components/monthSettlement";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { handleApproveAccount, handleApproveMonthAccountProinst, handleRejectAccount, handleRejectMonthAccountProinst } from "@/pages/examine/reconciliationApproval/base/service";
import React from "react";
import { handleCreateSettlement } from "@/pages/reports/settlementDetail/service";
import Item from "antd/lib/list/Item";
import { deletePicture, uploadPicture } from "@/services/picture";

const { confirm } = Modal;
type DetailProps = {
    currentUser?: any
    onShow: boolean  // 显示年度结算的内容
    setOnShow: any  // 设置是否显示整个组件
    parentRow: any  // 传入的行数据
    setParentRow: any // 设置传入的行数据 关闭抽屉要清空
    setCurrentApprovalstate: any // 当前的审核状态 关闭抽屉要清除
    currentApprovalstate: any // 当前的审批状态
    actionRef?: any // 同级表格
    parentRef?: any // 父级表格
    isChangeFile?: any // 是否可以删除上传的附件
    isYear?: any
}
const YearExamineProcess = ({ currentUser, onShow, setOnShow, parentRow, setParentRow, setCurrentApprovalstate, currentApprovalstate, actionRef, parentRef, isChangeFile, isYear }: DetailProps) => {
    const YearContentTableRef = useRef<any>()
    const AfterSettlementRef = useRef<any>()
    const formDescRef = useRef<any>();
    const draggleRef = React.createRef<any>()

    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    // 是否显示批量月度审批的按钮
    const [isShowMonthBtn, setIsShowMonthBtn] = useState<boolean>(false)
    // 批量月度结算按钮的加载效果
    const [monthLoading, setMonthLoading] = useState<boolean>(false)
    // 判断年度的是否可以结算
    const [isYearAllowSettlement, setIsYearAllowSettlement] = useState<boolean>(false)
    // 发起结算的抽屉
    const [showSettlementDrawer, setShowSettlementDrawer] = useState<boolean>(false)
    // 点击审核还是驳回 1审核 2 驳回
    const [toExamineType, setToExamineType] = useState<number>(0)
    // 点击出现审核和驳回悬浮框
    const [showToExamineModal, setShowToExamineModal] = useState<boolean>(false)
    // 判断是否已经重新校准了
    const [isFinishCalibration, setIsFinishCalibration] = useState<boolean>(false)
    // 审核确认按钮的加载按钮
    const [showModalLoading, setShowModalLoading] = useState<boolean>(false)
    // 当前状态
    const [currentNowState, setCurrentNowState] = useState<any>()
    // 下一状态
    const [currentNextState, setCurrentNextState] = useState<any>()
    // 拖动开始
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    // 判断是否有驳回状态, 有驳回按照驳回的走 没驳回直接1000的驳回
    const [handleHaveReject, setHandleHaveReject] = useState<boolean>(false)
    // 是否显示商户交费明细
    const [isShowShopMonthTable, setIsShowShopMonthTable] = useState<boolean>(false)
    // 点击小计展开抽屉的时候 是否是只读
    const [isDrawerReadOnly, setIsDrawerReadOnly] = useState<boolean>(false)
    // 确认发起结算的按钮loading
    const [submitBtnLoading, setSubmitBtnLoading] = useState<boolean>(false)
    const [fileLists, setFileLists] = useState<any>()
    // 判断拿到驳回类型
    const [rejectTypeDetail, setRejectTypeDetail] = useState<any>()

    // 新建结算申请
    const handleCreateSettlementApplication = async () => {
        setSubmitBtnLoading(true)
        // node
        const allList: any = []
        const node: any = {}
        // 给精算数据的对象单独存一个
        let actuarialData: any = {}

        const res = AfterSettlementRef.current?.settlementRef?.current?.getFieldsValue()

        const realTableData: any = AfterSettlementRef.current?.tableData
        console.log('realTableData', realTableData);

        const resultList: any = []
        if (realTableData && realTableData.length > 0) {
            realTableData.forEach((item: any) => {
                if (item.PeriodDesc !== '精算数据') {
                    resultList.push(item)
                } else {
                    actuarialData = item
                }
            })
        }

        const settlementYearTableData = realTableData

        console.log('settlementYearTableData', settlementYearTableData);

        // 拿到精算数据
        const resObj: any = settlementYearTableData[settlementYearTableData.length - 1]
        if (resObj) {
            resObj.CORRECT_AMOUNT = resObj?.CORRECT_AMOUNT || 0
        }

        // 保留原本的数据遍历添加参数
        // 只是把原本数组的最后一项变为精算之后的数据 且替换新字段CORRECT_AMOUNT 为 冲正的金额
        if (settlementYearTableData && settlementYearTableData.length > 0) {
            const newList: any = []
            const reqList: any = JSON.parse(JSON.stringify(resultList))

            reqList.forEach((item: any) => {
                if (item.PeriodIndex === resObj.PeriodIndex) {
                    newList.push({
                        ...resObj,
                        RevenueConfirmId: item.RevenueConfirmId,
                        children: item.children
                    })
                } else {
                    newList.push(item)
                }
            })
            console.log('newList', newList);

            newList.forEach((item: any, index: number) => {
                // node= reqDetailListDetail[0]
                if (item.children && item.children.length > 0) {
                    const childrenList = item.children
                    // 传给接口的list
                    const modalList: any = []
                    if (childrenList && childrenList.length > 0) {
                        childrenList.forEach((subItem: any) => {
                            modalList.push({
                                BUSINESSPROJECT_ID: parentRow?.BUSINESSPROJECT_ID,
                                BUSINESSPROJECT_NAME: parentRow?.BUSINESSPROJECT_NAME,
                                SHOPROYALTY_ID: subItem.ShopRoyalty_Id,
                                SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
                                BUSINESS_STARTDATE: subItem.StartDate,
                                BUSINESS_ENDDATE: subItem.EndDate,
                                REVENUECONFIRM_ID: subItem.RevenueConfirmId,
                                GUARANTEE_AMOUNT: subItem.MinturnOver,
                                GUARANTEERATIO: subItem.GuaranteeRatio,
                                ACTUAL_REVENUE: subItem.RevenueAmount,
                                PARTYA_SHAREPROFIT: subItem.RoyaltyTheory,
                                PARTYB_SHAREPROFIT: subItem.SubroyaltyTheory,
                                LIQUIDATION_AMOUNT: subItem.RefundSupplement,
                                ACTUAL_ACCOUNTS: subItem?.GuaranteeFee,
                                ROYALTY_PRICE: subItem.RoyaltyAmount,
                                SUBROYALTY_PRICE: subItem.SubroyaltyAmount,
                                MOBILEPAY_AMOUNT: subItem.MobilePayAmount,
                                CASHPAY_AMOUNT: subItem.CashAmount,
                                MERCHANTS_ID: parentRow?.MERCHANTS_ID,
                                MERCHANTS_NAME: parentRow?.MERCHANTS_NAME,
                                BUSINESS_PERIOD: subItem.PeriodIndexStr,
                                PERIOD_INDEX: subItem.PeriodIndex,
                                PROPERTYFEE: subItem.PropertyFee,
                                HOUSERENT: subItem.HouseRent,
                                BREACHPENALTY: subItem.BreachPenalty,
                                ELECTRICITYCHARGE: subItem.ElectricityCharge,
                                WATERCHARGE: subItem.WaterCharge,
                                OTHERFEE: subItem.OtherFee,
                                BUSINESSAPPROVAL_ID: parentRow?.BUSINESSAPPROVAL_ID,
                                PAID_AMOUNT: subItem.PaidFee,
                                EARLY_SETTLEMENT: subItem.EarlySettlement ? 1 : 0,
                                REVENUECONFIRM_DESC: `9010:${subItem.PaidFee_9010 || 0},9020:${subItem.PaidFee_9020 || 0},9030:${subItem.PaidFee_9030 || 0},9050:${subItem.PaidFee_9050 || 0},9090:${subItem.PaidFee_9090 || 0},9099:${subItem.PaidFee_9099 || 0}`
                            })
                        })
                    }
                    if (index + 1 === newList.length) {
                        allList.push({
                            node: {
                                BUSINESSPROJECT_ID: parentRow?.BUSINESSPROJECT_ID,
                                BUSINESSPROJECT_NAME: parentRow?.BUSINESSPROJECT_NAME,
                                SHOPROYALTY_ID: item.ShopRoyalty_Id,
                                SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
                                BUSINESS_STARTDATE: item.StartDate,
                                BUSINESS_ENDDATE: item.EndDate,
                                GUARANTEE_AMOUNT: item.MinturnOver,
                                GUARANTEERATIO: item.GuaranteeRatio,
                                REVENUECONFIRM_ID: item.RevenueConfirmId,
                                ACTUAL_REVENUE: item.RevenueAmount,
                                PARTYA_SHAREPROFIT: item.RoyaltyTheory,
                                PARTYB_SHAREPROFIT: item.SubroyaltyTheory,
                                LIQUIDATION_AMOUNT: item.RefundSupplement,
                                ACTUAL_ACCOUNTS: item?.GuaranteeFee,
                                ROYALTY_PRICE: item.RoyaltyAmount,
                                SUBROYALTY_PRICE: item.SubroyaltyAmount,
                                MOBILEPAY_AMOUNT: item.MobilePayAmount,
                                CASHPAY_AMOUNT: item.CashAmount,
                                MERCHANTS_ID: parentRow?.MERCHANTS_ID,
                                MERCHANTS_NAME: parentRow?.MERCHANTS_NAME,
                                BUSINESS_PERIOD: item.PeriodIndexStr,
                                PERIOD_INDEX: item.PeriodIndex,
                                PROPERTYFEE: item.PropertyFee,
                                HOUSERENT: item.HouseRent,
                                BREACHPENALTY: item.BreachPenalty,
                                ELECTRICITYCHARGE: item.ElectricityCharge,
                                WATERCHARGE: item.WaterCharge,
                                OTHERFEE: item.OtherFee,
                                CORRECT_AMOUNT: res?.CORRECT_AMOUNT,
                                BUSINESSAPPROVAL_ID: parentRow?.BUSINESSAPPROVAL_ID,
                                PAID_AMOUNT: item.PaidFee,
                                EARLY_SETTLEMENT: item.EarlySettlement ? 1 : 0,
                                REVENUECONFIRM_DESC: `9010:${item.PaidFee_9010 || 0},9020:${item.PaidFee_9020 || 0},9030:${item.PaidFee_9030 || 0},9050:${item.PaidFee_9050 || 0},9090:${item.PaidFee_9090 || 0},9099:${item.PaidFee_9099 || 0}`
                            },
                            children: modalList
                        })
                    } else {
                        allList.push({
                            node: {
                                BUSINESSPROJECT_ID: parentRow?.BUSINESSPROJECT_ID,
                                BUSINESSPROJECT_NAME: parentRow?.BUSINESSPROJECT_NAME,
                                SHOPROYALTY_ID: item.ShopRoyalty_Id,
                                SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
                                BUSINESS_STARTDATE: item.StartDate,
                                BUSINESS_ENDDATE: item.EndDate,
                                GUARANTEE_AMOUNT: item.MinturnOver,
                                GUARANTEERATIO: item.GuaranteeRatio,
                                ACTUAL_REVENUE: item.RevenueAmount,
                                REVENUECONFIRM_ID: item.RevenueConfirmId,
                                PARTYA_SHAREPROFIT: item.RoyaltyTheory,
                                PARTYB_SHAREPROFIT: item.SubroyaltyTheory,
                                LIQUIDATION_AMOUNT: item.RefundSupplement,
                                ACTUAL_ACCOUNTS: item?.GuaranteeFee,
                                ROYALTY_PRICE: item.RoyaltyAmount,
                                SUBROYALTY_PRICE: item.SubroyaltyAmount,
                                MOBILEPAY_AMOUNT: item.MobilePayAmount,
                                CASHPAY_AMOUNT: item.CashAmount,
                                MERCHANTS_ID: parentRow?.MERCHANTS_ID,
                                MERCHANTS_NAME: parentRow?.MERCHANTS_NAME,
                                BUSINESS_PERIOD: item.PeriodIndexStr,
                                PERIOD_INDEX: item.PeriodIndex,
                                PROPERTYFEE: item.PropertyFee,
                                HOUSERENT: item.HouseRent,
                                BREACHPENALTY: item.BreachPenalty,
                                ELECTRICITYCHARGE: item.ElectricityCharge,
                                WATERCHARGE: item.WaterCharge,
                                OTHERFEE: item.OtherFee,
                                BUSINESSAPPROVAL_ID: parentRow?.BUSINESSAPPROVAL_ID,
                                PAID_AMOUNT: item.PaidFee,
                                EARLY_SETTLEMENT: item.EarlySettlement ? 1 : 0,
                                REVENUECONFIRM_DESC: `9010:${item.PaidFee_9010 || 0},9020:${item.PaidFee_9020 || 0},9030:${item.PaidFee_9030 || 0},9050:${item.PaidFee_9050 || 0},9090:${item.PaidFee_9090 || 0},9099:${item.PaidFee_9099 || 0}`
                            },
                            children: modalList
                        })
                    }
                } else {
                    allList.push({
                        node: {
                            BUSINESSPROJECT_ID: parentRow?.BUSINESSPROJECT_ID,
                            BUSINESSPROJECT_NAME: parentRow?.BUSINESSPROJECT_NAME,
                            SHOPROYALTY_ID: item.ShopRoyalty_Id,
                            SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
                            BUSINESS_STARTDATE: item.StartDate,
                            BUSINESS_ENDDATE: item.EndDate,
                            GUARANTEE_AMOUNT: item.MinturnOver,
                            GUARANTEERATIO: item.GuaranteeRatio,
                            ACTUAL_REVENUE: item.RevenueAmount,
                            REVENUECONFIRM_ID: item.RevenueConfirmId,
                            PARTYA_SHAREPROFIT: item.RoyaltyTheory,
                            PARTYB_SHAREPROFIT: item.SubroyaltyTheory,
                            LIQUIDATION_AMOUNT: item.RefundSupplement,
                            ACTUAL_ACCOUNTS: item?.GuaranteeFee,
                            ROYALTY_PRICE: item.RoyaltyAmount,
                            SUBROYALTY_PRICE: item.SubroyaltyAmount,
                            MOBILEPAY_AMOUNT: item.MobilePayAmount,
                            CASHPAY_AMOUNT: item.CashAmount,
                            MERCHANTS_ID: parentRow?.MERCHANTS_ID,
                            MERCHANTS_NAME: parentRow?.MERCHANTS_NAME,
                            BUSINESS_PERIOD: item.PeriodIndexStr,
                            PERIOD_INDEX: item.PeriodIndex,
                            PROPERTYFEE: item.PropertyFee,
                            HOUSERENT: item.HouseRent,
                            BREACHPENALTY: item.BreachPenalty,
                            ELECTRICITYCHARGE: item.ElectricityCharge,
                            WATERCHARGE: item.WaterCharge,
                            OTHERFEE: item.OtherFee,
                            BUSINESSAPPROVAL_ID: parentRow?.BUSINESSAPPROVAL_ID,
                            PAID_AMOUNT: item.PaidFee,
                            EARLY_SETTLEMENT: item.EarlySettlement ? 1 : 0,
                            REVENUECONFIRM_DESC: `9010:${item.PaidFee_9010 || 0},9020:${item.PaidFee_9020 || 0},9030:${item.PaidFee_9030 || 0},9050:${item.PaidFee_9050 || 0},9090:${item.PaidFee_9090 || 0},9099:${item.PaidFee_9099 || 0}`
                        },
                        children: []
                    })
                }
            })
        }
        // if (actuarialData) {
        //     allList[allList.length - 1].node = actuarialData
        // }


        const obj: any = {
            BUSINESSPROJECT_ID: parentRow?.BUSINESSPROJECT_ID,
            BUSINESSPROJECT_NAME: parentRow?.BUSINESSPROJECT_NAME,
            SHOPROYALTY_ID: node?.ShopRoyalty_Id,
            SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
            // BUSINESS_TRADE:'',
            // BUSINESS_BRAND:'',
            BUSINESS_STARTDATE: node?.StartDate,
            BUSINESS_ENDDATE: node?.EndDate,
            BUSINESS_PERIOD: node?.PeriodIndexStr,
            PERIOD_INDEX: node?.PeriodIndex,
            // BUSINESS_DAYS:'',
            GUARANTEE_AMOUNT: node?.MinturnOver,
            GUARANTEERATIO: node?.GuaranteeRatio,
            ACTUAL_REVENUE: node?.RevenueAmount,
            PARTYA_SHAREPROFIT: node?.RoyaltyTheory,
            PARTYB_SHAREPROFIT: node?.SubroyaltyTheory,
            LIQUIDATION_AMOUNT: node?.RefundSupplement,
            ACTUAL_ACCOUNTS: node?.GuaranteeFee,
            ROYALTY_PRICE: node?.RoyaltyAmount,
            SUBROYALTY_PRICE: node?.SubroyaltyAmount,
            MOBILEPAY_AMOUNT: node?.MobilePayAmount,
            CASHPAY_AMOUNT: node?.CashAmount,
            // OTHERPAY_AMOUNT:'',
            MERCHANTS_ID: parentRow?.MERCHANTS_ID,
            MERCHANTS_NAME: parentRow?.MERCHANTS_NAME,
            // REVENUE_VALID:'',
            // REVENUECONFIRM_DESC:'',
            PROPERTYFEE: node?.PropertyFee,
            HOUSERENT: node?.HouseRent,
            BREACHPENALTY: node?.BreachPenalty,
            ELECTRICITYCHARGE: node?.ElectricityCharge,
            WATERCHARGE: node?.WaterCharge,
            OTHERFEE: node?.OtherFee,
        }

        let [APPOVED_IDS, APPOVED_NAME]: any = []
        if (res.APPROVALSTAFF_ID) {
            [APPOVED_NAME, APPOVED_IDS] = res.APPROVALSTAFF_ID.split('-')
        }
        console.log('parentRow', parentRow);

        let detail: any = {}
        if (parentRow?.BUSINESSAPPROVAL_ID) {
            detail = await handleGetBUSINESSAPPROVALDetail({ BUSINESSAPPROVALId: parentRow?.BUSINESSAPPROVAL_ID })
        }
        console.log('detail', detail);

        const req = {
            BusinessapprovalModel: {
                BUSINESSAPPROVAL_ID: parentRow?.BUSINESSAPPROVAL_ID,
                OPERATION_TYPE: '11',
                BUSINESSPROCESS_ID: parentRow?.BUSINESSPROJECT_ID,
                PROINST_ID: parentRow?.SHOPROYALTY_ID,
                SERVERPART_ID: parentRow?.SERVERPART_ID || parentRow?.Serverpart_ID || '',
                SERVERPART_IDS: parentRow?.SERVERPART_ID || parentRow?.Serverpart_ID || '',
                BUSINESSPROCESS_NAME: `【${parentRow?.STARTDATE}-${parentRow?.ENDDATE}】${parentRow?.BUSINESSPROJECT_NAME}年度结算`,
                BUSINESS_STARTDATE: parentRow?.BUSINESSAPPROVAL_ID ? detail?.BUSINESS_STARTDATE : moment().format('YYYY-MM-DD HH:mm:ss'),
                BUSINESSAPPROVAL_STATE: 1000,
                BUSINESSAPPROVAL_DESC: res?.BUSINESSAPPROVAL_DESC || '',
                STAFF_NAME: currentUser.Name,
                STAFF_ID: currentUser?.ID,
                Serverpart_Name: parentRow?.SERVERPART_NAME || parentRow?.Serverpart_Name,
                SERVERPARTSHOP_ID: parentRow?.SERVERPARTSHOP_ID,
                SERVERPARTSHOP_NAME: parentRow?.SERVERPARTSHOP_NAME,
                CORRECT_AMOUNT: res.CORRECT_AMOUNT,
                APPOVED_IDS,
                APPOVED_NAME
            },
            RevenueconfirmModel: allList,
            nextApproveState: AfterSettlementRef.current?.nextState || ''
        }
        console.log('req', req);
        const data = await handleCreateSettlement(req)
        if (data.Result_Code === 100) {
            const fileList: any = AfterSettlementRef.current?.fileList
            if (fileList && fileList.length > 0) {
                console.log('fileList', fileList);
                console.log('data', data);
                const detail: any = data.Result_Data

                const formData = new FormData();
                fileList.forEach((item: any) => {
                    console.log('item', item);
                    formData.append('files[]', item.originFileObj);
                    // formData.append('ImageName', item.name);
                })
                formData.append('TableType', '1130');
                formData.append('TableId', detail?.BUSINESSAPPROVAL_ID);
                const success = await uploadPicture(formData)
                console.log('success', success);
            }



            message.success(data.Result_Desc)
            setOnShow(false)
            setParentRow(undefined)
            setCurrentApprovalstate(undefined)
            setShowSettlementDrawer(false)
            actionRef.current?.reload()
            if (parentRef) {
                parentRef.current?.reload()
            }
        } else {
            message.error(data.Result_Desc)
        }

        setSubmitBtnLoading(false)
    }

    // 审批的方法
    const handleGetToExamine = async (desc: string, target: any, nextPerson: any, allForm?: any) => {
        let req: any = {}
        let data: any = {}
        // 审核


        if (toExamineType === 1) {
            req = {
                businessApprovalID: parentRow?.BUSINESSAPPROVAL_ID,
                curProinstState: currentNowState,
                approveedInfo: desc,
                approveedStaffId: currentUser?.ID,
                approveedStaffName: currentUser?.Name,
                nextId: nextPerson,
                nextState: currentNextState || ''
                // targetProinstState: target
            }
            data = await handleApproveAccount(req)
            // if (parentRow?.SETTLEMENT_TYPE === 2) {
            //     data = await handleApproveMonthAccountProinst(req)
            // } else {
            //
            // }

        } else if (toExamineType === 2) {
            //   驳回
            const backObj = JSON.parse(target)
            console.log('backObj', backObj);
            req = {
                businessApprovalID: parentRow?.BUSINESSAPPROVAL_ID,
                approveedStaffId: currentUser?.ID,
                approveedStaffName: currentUser?.Name,
                approveedInfo: desc,
                targetProinstState: backObj?.APPROVALROUTE_STATE,
                rejectType: allForm?.rejectType
            }
            data = await handleRejectAccount(req)
            // if (parentRow?.SETTLEMENT_TYPE === 2) {
            //     data = await handleRejectMonthAccountProinst(req)
            // } else {
            //     data = await handleRejectAccount(req)
            // }
        }
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            setShowModalLoading(false)
            setToExamineType(0)
            setShowToExamineModal(false)
            setCurrentNowState(undefined)
            setCurrentNextState(undefined)
            setOnShow(false)
            setParentRow(undefined)
            setCurrentApprovalstate(undefined)
            if (actionRef) {
                actionRef.current?.reload()
            }
            if (parentRef) {
                parentRef.current?.reload()
            }
        } else {
            message.error(data.Result_Desc)
            setShowModalLoading(false)
        }
    }

    const onDraggaleStart = (event, uiData) => {

        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };

    // 点击小计的时候可以弹出发起的页面查看详情
    const handleShowSettlementDetail = () => {
        setShowSettlementDrawer(true)
        setIsDrawerReadOnly(true)
    }

    // 拿到附件列表
    const handleGetFile = async () => {
        if (!parentRow?.BUSINESSAPPROVAL_ID) {
            return
        }
        const req: any = {
            TableId: parentRow?.BUSINESSAPPROVAL_ID,
            TableType: 1130,
        }
        const data = await handleGetPictureList(req)
        console.log('data', data);
        const list: any = data.Result_Data.List
        const res: any = []
        if (list && list.length > 0) {
            list.forEach((item: any) => {
                res.push({
                    uid: `${item.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                    name: item.ImageName,
                    status: 'done',
                    url: item.ImageUrl, // url 是展示在页面上的绝对链接
                    imgUrl: item.ImagePath  // + success.ImageUrl,
                })
            })
        }
        console.log('res', res);
        setFileLists(res)
    }

    return (
        <div>
            {/* 年度结算的项目详情 */}
            <Drawer
                width="85%"
                visible={onShow}
                destroyOnClose
                onClose={() => {
                    setOnShow(false)
                    setParentRow(undefined)
                    setCurrentApprovalstate(undefined)
                }}
                bodyStyle={{ backgroundColor: "#fff", padding: 0 }}
                closable={false}
                footer={
                    parentRow?.SETTLEMENT_STATE === 0 ?
                        <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                            <>
                                {
                                    currentUser?.UserName === 'ahyd_system' || currentUser?.UserName === 'yanlj' || currentUser?.UserName === 'chenyz' || currentUser?.UserName === 'yuzhichao' ?
                                        <>
                                            {
                                                !isShowMonthBtn ?
                                                    <Popconfirm
                                                        title={'确认审结所有月份？'}
                                                        onConfirm={async () => {
                                                            console.log('parentRow', parentRow);

                                                            let ShopRoyaltyIdStr: string = ''
                                                            let minStartTime: string = ''
                                                            let maxEndTime: string = ''
                                                            const list: any = YearContentTableRef.current?.YearExamineDetailTableRef?.current?.reqDetailListDetail
                                                            if (list && list.length > 0) {
                                                                list.forEach((item: any, index: number) => {
                                                                    if (item.PeriodDesc !== '合计') {
                                                                        if (minStartTime) {
                                                                            if (new Date(minStartTime).getTime() > new Date(moment(item.StartDate).format('YYYY-MM-DD')).getTime()) {
                                                                                minStartTime = moment(item.StartDate).format('YYYY-MM-DD')
                                                                            }
                                                                        } else {
                                                                            minStartTime = moment(item.StartDate).format('YYYY-MM-DD')
                                                                        }
                                                                        if (maxEndTime) {
                                                                            if (new Date(maxEndTime).getTime() < new Date(moment(item.EndDate).format('YYYY-MM-DD')).getTime()) {
                                                                                maxEndTime = moment(item.EndDate).format('YYYY-MM-DD')
                                                                            }
                                                                        } else {
                                                                            maxEndTime = moment(item.EndDate).format('YYYY-MM-DD')
                                                                        }
                                                                    }

                                                                    if (item.ShopRoyalty_Id || item.ShopRoyalty_Id === 0) {
                                                                        if (ShopRoyaltyIdStr) {
                                                                            ShopRoyaltyIdStr += `,${item.ShopRoyalty_Id}`
                                                                        } else {
                                                                            ShopRoyaltyIdStr = `${item.ShopRoyalty_Id}`
                                                                        }
                                                                    }

                                                                })
                                                            }
                                                            const req: any = {
                                                                ProjectId: parentRow?.BUSINESSPROJECT_ID,
                                                                ShopRoyaltyId: ShopRoyaltyIdStr,
                                                                StartMonth: minStartTime ? moment(minStartTime).format('YYYYMM') : '',
                                                                EndMonth: maxEndTime ? moment(maxEndTime).format('YYYYMM') : '',
                                                            }
                                                            setMonthLoading(true)
                                                            const data = await handleApprovePeriodAccount(req)
                                                            if (data.Result_Code === 100) {
                                                                setMonthLoading(false)
                                                                message.success(data.Result_Desc)
                                                                YearContentTableRef.current?.YearExamineDetailTableRef?.current?.handleGetTableData(parentRow?.BUSINESSPROJECT_ID, parentRow?.SHOPROYALTY_ID, parentRow)
                                                            } else {
                                                                message.success(data.Result_Desc)
                                                                setMonthLoading(false)
                                                            }
                                                        }}
                                                    >
                                                        <Button loading={monthLoading} type="primary" onClick={() => {
                                                            console.log('YearContentTableRef', YearContentTableRef);

                                                        }}>月度结算</Button>
                                                    </Popconfirm>
                                                    : ''
                                            }
                                        </> :
                                        ''
                                }
                            </>
                            {
                                isYearAllowSettlement ?
                                    <Button type="primary" style={{ marginLeft: '8px' }} onClick={() => {
                                        // || currentUser?.ID === 2785
                                        if (isYearAllowSettlement) {
                                            setShowSettlementDrawer(true)
                                        } else {
                                            message.error('项目还未审结，请先完成月度项目结算！')
                                        }
                                    }}>年度结算</Button> : ''
                            }
                        </div> : currentApprovalstate > 0 && parentRow?.PEND_STATE === 0 && parentRow?.APPLY_PROCCESS ?
                            <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                                <Button type={'primary'} onClick={() => {
                                    setShowSettlementDrawer(true)
                                }}>
                                    重新申请
                                </Button>
                            </div>
                            : parentRow?.PEND_STATE === 0 ?
                                <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                                    <div>
                                        <Button type='primary' style={{ marginRight: '8px' }} onClick={() => {
                                            // 判断是不是重新申请一遍 是的话 就调用重新申请的内容 别的情况还是正常走审核
                                            setToExamineType(1)
                                            setShowToExamineModal(true)
                                        }}>审核</Button>
                                        {/* 重新申请时 不显示驳回按钮 */}
                                        <Button type='primary' style={{ marginRight: '8px' }} onClick={() => {
                                            setToExamineType(2)
                                            setShowToExamineModal(true)
                                        }}>驳回</Button>
                                    </div>
                                </div> : false
                }
            >
                <YearContentTable parentRow={parentRow} currentApprovalstate={currentApprovalstate} onRef={YearContentTableRef}
                    setIsShowMonthBtn={setIsShowMonthBtn} setIsYearAllowSettlement={setIsYearAllowSettlement} onShow={onShow}
                    handleShowSettlementDetail={handleShowSettlementDetail} isChangeFile={isChangeFile} isYear={isYear} />
            </Drawer>


            <Drawer
                width="85%"
                visible={showSettlementDrawer}
                destroyOnClose
                onClose={() => {
                    setShowSettlementDrawer(false)
                    setIsFinishCalibration(false)
                    setIsDrawerReadOnly(false)
                    setSubmitBtnLoading(false)
                }}
                bodyStyle={{ backgroundColor: "#fff", padding: 0 }}
                closable={false}
                footer={isDrawerReadOnly ? false : <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                    {/* <Button type={'primary'} onClick={() => {
                        setShowUpLoadFile(true)
                    }}>上传附件</Button> */}
                    <Popconfirm
                        title={'确认发起结算？'}
                        onConfirm={() => {

                            AfterSettlementRef.current?.settlementRef?.current?.validateFields().then(res => {
                                if (!isFinishCalibration) {
                                    // 校准数据之后才能结算
                                    message.error('请先校准数据')
                                    return
                                }

                                if (res) {
                                    handleCreateSettlementApplication()
                                }
                            })
                        }}
                    >
                        <Button loading={submitBtnLoading} type={'primary'}>确认结算</Button>
                    </Popconfirm>
                </div>}
            >
                <AfterSettlement parentRow={parentRow} dataRef={YearContentTableRef} onShow={showSettlementDrawer}
                    setIsFinishCalibration={setIsFinishCalibration} onRef={AfterSettlementRef} readonly={isDrawerReadOnly} />
            </Drawer>


            {/* 审核和驳回的悬浮框 */}
            <Modal
                title={
                    <div
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}
                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {toExamineType === 1 ? '审核' : '驳回'}
                    </div>
                }
                open={showToExamineModal}
                width={1550}
                confirmLoading={showModalLoading}
                destroyOnClose
                onOk={() => {
                    formDescRef.current.validateFields().then(res => {
                        if (res.desc) {
                            setShowModalLoading(true)
                            // setDescText(res.desc)
                            handleGetToExamine(res.desc, res.targetProinstState, res.nextPerson, res)
                        }
                    })
                }}
                onCancel={() => {
                    setToExamineType(0)
                    setShowToExamineModal(false)
                    setCurrentNowState(undefined)
                    setCurrentNextState(undefined)
                }}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <YearExamineTable examineDetail={parentRow} />

                <ReviewProcess compareCurrent={{
                    ...parentRow,
                    BusinessApprovalId: parentRow?.BUSINESSAPPROVAL_ID
                }} showReviewProcess={showToExamineModal} />

                <ProForm
                    formRef={formDescRef}
                    submitter={{
                        // 清空表单自带的按钮
                        render: (props, doms) => {
                            return []
                        }
                    }}
                    request={async () => {
                        await handleGetFile()
                        return {}
                    }}
                >
                    {/* 要驳回的状态 */}
                    {
                        toExamineType === 2 ?
                            <Row gutter={8}>
                                <Col span={6}>
                                    <ProFormSelect
                                        name="targetProinstState"
                                        label="回退状态"
                                        rules={[
                                            {
                                                required: handleHaveReject,
                                                message: '请输入备注说明'
                                            }
                                        ]}
                                        request={async () => {
                                            if (!parentRow?.BUSINESSAPPROVAL_ID) {
                                                return
                                            }
                                            const req: any = {
                                                BUSINESSAPPROVALId: parentRow?.BUSINESSAPPROVAL_ID
                                            }
                                            const data = await handleGetGetBUSINESSAPPROVALDetail(req)
                                            console.log('data.rejectList', data.rejectList);

                                            if (data.rejectList && data.rejectList.length > 0) {
                                                setHandleHaveReject(true)

                                                const list: any = []

                                                data.rejectList.forEach((item: any) => {
                                                    list.push({ label: item.APPROVALROUTE_NAME, value: JSON.stringify(item) })
                                                })
                                                return list
                                            }
                                            setHandleHaveReject(false)
                                            return []
                                        }}
                                    />
                                </Col>
                                {/* 是正常驳回 还是驳回后 下一个人审批之后直接回来 */}
                                <Col span={18}>
                                    <ProFormRadio.Group
                                        name="rejectType"
                                        label="驳回类型"
                                        rules={[
                                            {
                                                required: true,
                                                message: '请选择驳回类型'
                                            }
                                        ]}
                                        options={[
                                            { label: '正常驳回（指定人审批后，需重新按业务流程审批）', value: '1' },
                                            { label: '指定驳回（指定人可以跳过中间步骤，直接修改回到驳回人）', value: '2' },
                                        ]}
                                        initialValue={'2'}
                                    >
                                    </ProFormRadio.Group>

                                </Col>
                            </Row>
                            : ''
                    }

                    {
                        toExamineType === 1 && currentNextState?.NEXT_STATE !== 9000 ?
                            <Row>
                                <Col span={6}>
                                    <ProFormSelect
                                        name={"nextPerson"}
                                        label={"下一环节审批人"}
                                        disabled={rejectTypeDetail === 2}
                                        rules={[
                                            {
                                                required: true,
                                                message: '请输入备注说明'
                                            }
                                        ]}
                                        request={async () => {
                                            console.log('parentRowparentRowparentRowparentRow211', parentRow);

                                            // merchantState 判断哪几个状态是商户的 商户调用拿到 商户下面的全部人列表选择一个  不是商户的 就根据选择了的人去指定一个人
                                            // 接口直接返回就不用判断了
                                            if (toExamineType !== 1) {
                                                return
                                            }
                                            if (!parentRow?.BUSINESSAPPROVAL_ID) {
                                                return
                                            }
                                            const req: any = {
                                                BUSINESSAPPROVALId: parentRow?.BUSINESSAPPROVAL_ID
                                            }
                                            const data = await handleGetBUSINESSAPPROVALDetail(req)
                                            setRejectTypeDetail(data.REJECT_TYPE || undefined)
                                            if (data.REJECT_TYPE === 2) {
                                                const userList: any = data.approveList[data.approveList.length - 1]
                                                const list: any = [{ label: userList.REJECT_STAFF, value: userList.REJECT_ID }]
                                                if (list && list.length > 0 && list.length === 1) {
                                                    formDescRef.current?.setFieldsValue({ nextPerson: list[0].value })
                                                }
                                                setCurrentNowState(data.BUSINESSAPPROVAL_STATE)
                                                setCurrentNextState(userList.REJECT_TYPE)
                                                return list
                                            }
                                            setCurrentNowState(data.BUSINESSAPPROVAL_STATE)
                                            // 拿到下一环节
                                            const nextReq: any = {
                                                OperationType: parentRow?.SETTLEMENT_TYPE === '1' || parentRow?.SETTLEMENT_TYPE === 1 ? 11 : 12,
                                                CurState: data.BUSINESSAPPROVAL_STATE,
                                                IsValid: 1
                                            }
                                            console.log('nextReq', nextReq);

                                            const nextData = await handleGetAPPROVALROUTEDetail(nextReq)
                                            setCurrentNextState(nextData)
                                            console.log('nextDatanextDatanextDatanextData2', nextData);
                                            console.log('datadatadatadatadatadatadatadata2', data);

                                            let list: any = []
                                            if (data.UserList && data.UserList.length > 0) {
                                                data.UserList.forEach((item: any) => {
                                                    if (item.USER_STATUS === 1) {
                                                        list.push({ label: item.USER_NAME, value: item.USER_ID })
                                                    }
                                                })
                                            }
                                            if (list && list.length > 0 && list.length === 1) {
                                                if (list[0].value !== 827) {
                                                    formDescRef.current?.setFieldsValue({ nextPerson: list[0].value })
                                                }
                                            }


                                            // 剔除 结算时间在2025年4月1日 之后的数据 不给孙青
                                            if (parentRow?.PROJECT_ENDDATE && new Date(parentRow?.PROJECT_ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime()) {
                                                list = list.filter((item: any) => item.value !== 827);
                                            }


                                            if (currentUser?.ID === 2785) {
                                                list.push({ label: '严琅杰', value: 2785 })
                                            }

                                            console.log('listlistlistlist213231', list);


                                            return list


                                        }}
                                    />
                                </Col>
                            </Row>
                            : ''
                    }

                    <ProFormTextArea
                        name="desc"
                        label="审批意见"
                        rules={[
                            {
                                required: true,
                                message: '请输入审批意见'
                            }
                        ]}
                    />

                    <ProFormUploadButton
                        label={"年度结算单"}
                        name="files"
                        fileList={fileLists}
                        fieldProps={{
                            showUploadList: {
                                showRemoveIcon: false, // 禁用删除功能
                            },
                        }}
                        buttonProps={{
                            style: { display: 'none' }
                        }}
                    />
                </ProForm>


                {
                    isShowShopMonthTable ?
                        <MonthSettlement detail={parentRow} setIsShowShopMonthTable={setIsShowShopMonthTable} /> :
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <span style={{ fontWeight: 600, fontSize: '14px', color: '#1890ff' }}>经营商户应交费用明细表</span>
                            <Button icon={<PlusOutlined />} style={{ marginLeft: '8px' }} onClick={() => {
                                setIsShowShopMonthTable(true)
                            }}>
                            </Button>
                        </div>
                }
            </Modal>

        </div>
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(YearExamineProcess);
