/*
 * @Author: cclu
 * @Date: 2022-04-28 10:47:35
 * @LastEditTime: 2023-08-30 15:10:35
 * @LastEditors: zzy 411037547@qq.com
 * @Description: 商户欠款详情
 * @FilePath: \cloud-platform\src\pages\busniess\PaymentConfirm\detail.tsx
 */
import { connect, history } from "umi";
import useRequest from '@ahooksjs/use-request';
import { useEffect, useRef, useState } from "react";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable from "@ant-design/pro-table";
import { PictureTwoTone, PlusOutlined } from "@ant-design/icons";
import { Button, Card, Col, Descriptions, Empty, message, Row, Space, Statistic, Tag, Typography, Image, Drawer, List, Avatar, Result } from "antd";
import { ModalForm, ProFormDatePicker, ProFormDigit, ProFormSelect, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import ProjectDetail from "@/pages/BussinessProject/detail";
import IconFont from "@/components/IconFont";
import ProjectItem from "./components/ProjectItem";

import type { ConnectState } from "@/models/connect";
import type { ProFormInstance } from '@ant-design/pro-form'
import type { ProColumns, ActionType } from "@ant-design/pro-table";
import type { AccountReceivablesModel, PaymentConfirmModel, RemarksModel } from "./data";

import { getFieldEnum } from "@/services/options";
import {
    getPaymentConfirmList, getMerchantsReceivables, updatePaymentConfirm, uploadFile,
    savePaymentRecord, getRemarksList, updateSynchroRemarks, delPaymentConfirm,
    uploadAHYDFile
} from "./service";

import EditPaymentTable from "./components/EditPaymentTable";
import PaymentRecord from "@/pages/BussinessProject/components/PaymentRecord";
import numeral from "numeral";
import moment from "moment";
import { transferImg } from "@/utils/format";
import './style.less';

const { Title, Text } = Typography

// 更新回款信息
const handleAddUpdate = async (fields: PaymentConfirmModel, remark?: RemarksModel) => {

    const hide = message.loading('正在提交...');

    const result = await updatePaymentConfirm(fields);
    hide();

    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
        return false;
    }
    if (remark) await updateSynchroRemarks({ ...remark, TABLE_ID: fields?.PAYMENTCONFIRM_ID || result.Result_Data.PAYMENTCONFIRM_ID })
    message.success("提交成功！")
    return result.Result_Data;
};

// 删除回款信息
const handleDelete = async (id: number) => {

    const hide = message.loading('正在删除...');
    const result = await delPaymentConfirm(id)
    hide();
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        return false;
    }

    message.success("删除成功！")
    return true;
};

//  保存拆分记录
const handleSavePament = async (fields: PaymentConfirmModel[]) => {
    const hide = message.loading('正在提交...');
    const result = await savePaymentRecord(fields);
    hide();

    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
        return false;
    }
    message.success("提交成功！")
    return true;
};

// 校验图片大小
const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

const MerchartsPayment: React.FC = (props: any) => {
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [tabActiveIndex, setTabActiveIndex] = useState<string>('1')
    const [currentProject, setProject] = useState<any>(undefined)

    const [fileList, setFileList] = useState<any[]>([])
    const [fieldEnumIcon, setFieldEnumIcon] = useState<any>() // 款项类型图标

    const [myRemark, setMyRemark] = useState<RemarksModel>({}) // 备注
    const [step, setStep] = useState<number>(1) // 步骤 1 填写回款信息 2.拆分回款金额到不同项目
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片

    const [currentRow, setCurrentRow] = useState<any>()
    const [editFilds, setEditFilds] = useState<any>()
    const [paymentList, setPaymentList] = useState<PaymentConfirmModel[]>() // 欠款项目
    const [brandImages, setBrandImages] = useState<string[]>() // 品牌图片
    const [accountReceivablesList, setAccountReceivablesList] = useState<[]>() // 应收款项目

    const [modalVisible, handleModalVisible] = useState<boolean>(false)

    const pageid = props.match.params.id
    const currentUser = props?.currentUser

    // 根据用户的类型 拼接请求参数 商户访问则使用门店ids 业主访问则直接查询商户id
    const userDataParams = currentUser && currentUser.UserPattern === 1000 ?
        { MerchantsId: pageid, MERCHANTS_ID: pageid, ShowRevenueSplit: false } :
        { ServerpartShopIds: currentUser.ServerpartShopIds, ShowRevenueSplit: false }

    // 欠款商户
    const { run: refreshPage, loading: merchartsLoading, data: merchartsData } = useRequest(() => { return getMerchantsReceivables(userDataParams) })

    const { run: getRemark, loading: remarkLoading, data: remarkList = [] } = useRequest((params) => {
        return getRemarksList({ ...params, TABLE_NAME: 'T_PAYMENTCONFIRM' })
    }, { manual: true })

    // 生成账款类型状态枚举
    const { loading: fieldLoading, data: FieldEnum } = useRequest(async () => {
        const data = await getFieldEnum({ FieldExplainField: "ACCOUNT_TYPE" })
        const opt = {}
        const iconOpt = {}

        data?.forEach(n => {
            iconOpt[`${n.value}`] = {
                text: <IconFont name={`icon-payment-${n.value}`} size="18" style={{ fontSize: 18, verticalAlign: "middle" }}></IconFont>,
                status: n.value === 9000 ? 'Processing' : 'error'
            }
            opt[n.value] = {
                text: n.label,
                // status: n.value === "9000" ? 'Processing' : 'error'
            }
        })
        setFieldEnumIcon(iconOpt)
        return opt
    })

    useEffect(() => {
        if (!merchartsLoading && merchartsData && !brandImages) {
            if (merchartsData?.AccountReceivablesList) {
                // 生成品牌图列表
                const brandImage = merchartsData?.AccountReceivablesList.filter((n: AccountReceivablesModel) =>
                    n.BUSINESSPROJECT_ICO
                ).map((item: AccountReceivablesModel) => item.BUSINESSPROJECT_ICO)

                setBrandImages(Array.from(new Set(brandImage)))
                // 生成应收款项目列表数据 按照时间排序
                setAccountReceivablesList(merchartsData?.AccountReceivablesList.sort(
                    (a: { ACCOUNT_DATE: string | number | Date; }, b: { ACCOUNT_DATE: string | number | Date; }) => new Date(a.ACCOUNT_DATE).getTime() - new Date(b.ACCOUNT_DATE).getTime()))
                return
            }
            setBrandImages([])
            setAccountReceivablesList([])
        }
    }, [merchartsLoading, merchartsData, brandImages])

    /* 校验回款数据拆分数据并提交 */
    const checkAmountAndUpdate = async () => {
        // 回款拆分
        if (editFilds.length === 0) {
            message.warning("请选择需要返款的数据")
            return false
        }
        const endPayments = editFilds.map((n: PaymentConfirmModel) => {
            return {
                ...n, PAYMENTCONFIRM_PID: currentRow.PAYMENTCONFIRM_ID,
                PAYMENTDATE: currentRow.PAYMENTDATE,
                ACTUAL_PAYMENT: numeral(n.ACTUAL_PAYMENT).multiply(10000).value(),
                STAFF_ID: currentUser?.ID, // 操作人内码
                STAFF_NAME: currentUser?.Name, // 操作人员
            }
        })
        const paymentPrice = endPayments.reduce((pre: any, item: any) => pre + item.ACTUAL_PAYMENT, 0,)
        if (paymentPrice <= numeral(currentRow.CURRENTBALANCE).multiply(10000).value()) {
            return await handleSavePament(endPayments)
        }

        message.warning("返款金额应小于总回款金额")
        return false
    }
    /*   页面头部信息描述 */
    const descirption = (
        <>
            <Title level={3} >
                {merchartsData?.COOPMERCHANTS_NAME}
            </Title>
            <Row>
                <Col span={6} style={{ marginTop: 10 }}>

                    <Descriptions
                        labelStyle={{ color: '#000' }}
                        contentStyle={{ color: '#595959' }}
                        column={1}>
                        <Descriptions.Item label="法人">
                            {merchartsData?.COOPMERCHANTS_LEGALPERSON && <Tag color="#DFEBF7" className="header-tag">{merchartsData?.COOPMERCHANTS_LEGALPERSON}</Tag>}
                            {merchartsData?.COOPMERCHANTS_LEGALMOBILE || "-"}
                        </Descriptions.Item>
                        <Descriptions.Item label="联系人">
                            {merchartsData?.COOPMERCHANTS_LINKMAN && <Tag color="#DFEBF7" className="header-tag">{merchartsData?.COOPMERCHANTS_LINKMAN}</Tag>}
                            {merchartsData?.COOPMERCHANTS_MOBILEPHONE || "-"}
                        </Descriptions.Item>

                    </Descriptions>
                </Col>
                <Col span={18} style={{ display: "flex", justifyContent: "flex-start" }}>
                    {!merchartsLoading && brandImages && brandImages.map(img =>
                        <div style={{
                            width: 78, height: 70, borderRadius: 3,
                            boxShadow: "0px 2px 10px 0px rgba(241,241,241,0.84)", overflow: "hidden", marginLeft: 10, display: "flex", alignItems: "center"
                        }} key={img}>

                            <Avatar shape="square" size={78} src={img} ></Avatar>
                        </div>
                    )
                    }
                </Col>
            </Row>
        </>
    )
    // 标题金额拆分小数点前后显示大小
    const amountDom = (value: any) => {
        const stringValue = `${value}`
        const [intValue, floatValue] = stringValue.split(".")
        return floatValue ?
            <><Text type="warning">{numeral(intValue).format("0,0")}</Text>
                <Text type="warning" style={{ fontSize: 22 }}>.{floatValue}</Text>
                <Text type="warning" style={{ fontSize: 14 }}>(万元)</Text></> : <>
                <Text type="warning">{intValue}</Text><Text type="warning" style={{ fontSize: 14 }}>(万元)</Text></>
    }
    // 往来款表格头部设置
    const columns: ProColumns<PaymentConfirmModel>[] = [
        {
            title: "",
            width: 68,
            dataIndex: 'ACCOUNT_TYPE',
            hideInSearch: true,
            valueType: "select",
            valueEnum: !fieldLoading ? fieldEnumIcon : {},
        },
        {

            title: "款项类型",
            dataIndex: 'ACCOUNT_TYPE',
            width: 120,
            // align: "center",
            hideInSearch: true,
            valueType: "select",
            valueEnum: !fieldLoading ? FieldEnum : {},
            filters: true,
            onFilter: true,
            // request: async ()=>{
            //     return await getFieldEnum({ FieldExplainField: "ACCOUNT_TYPE" })
            // },

        },
        {
            title: () => <div style={{ textAlign: "center" }}>项目</div>,
            dataIndex: 'BUSINESSPROJECT_NAME',
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => (a.BUSINESSPROJECT_NAME || "").localeCompare((b.BUSINESSPROJECT_NAME || "")),
            render: (_, record) => {

                if (record.CURRENTBALANCE === 0) {
                    return <Text style={{ paddingRight: 16 }} type="secondary">{record.BUSINESSPROJECT_NAME}</Text>
                }
                return _
            }
        },
        {
            dataIndex: 'PAYMENTCONFIRM_DESC',
            title: () => <div style={{ textAlign: "center" }}>款项说明</div>,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                if (record.CURRENTBALANCE === 0) {
                    return <Text style={{ paddingRight: 16 }} type="secondary">{record.PAYMENTCONFIRM_DESC}</Text>
                }
                return _
            }
        },
        {
            dataIndex: 'ACCOUNT_DATE',
            title: '应缴日期',
            valueType: "date",
            align: 'center',
            hideInSearch: true,
            width: 120,
            sorter: (a, b) => new Date(a.ACCOUNT_DATE || '').getTime() - new Date(b.ACCOUNT_DATE || '').getTime(),
            render: (_, record) => {
                if (record.CURRENTBALANCE === 0) {
                    return <Text type="secondary">{record?.ACCOUNT_DATE}</Text>
                }
                return _
            }
        },
        {
            dataIndex: 'ACCOUNT_AMOUNT',
            title: '应缴金额',
            align: 'right',
            hideInSearch: true,
            width: 120,
            sorter: (a, b) => a.ACCOUNT_AMOUNT - b.ACCOUNT_AMOUNT,
            render: (_, record) => {
                if (record.CURRENTBALANCE === 0) {
                    return <Text style={{ paddingRight: 16 }} type="secondary">{record.ACCOUNT_AMOUNT || 0}</Text>
                }
                return <Text style={{ paddingRight: 16 }} type={record.ACCOUNT_TYPE === "9000" ? "success" : undefined}>{record?.ACCOUNT_AMOUNT || '-'}</Text>
            }
        },
        {
            dataIndex: 'ACTUAL_PAYMENT',
            title: '已缴金额',
            hideInSearch: true,
            align: 'right',
            width: 120,
            sorter: (a, b) => a.ACTUAL_PAYMENT - b.ACTUAL_PAYMENT,
            render: (_, record) => {
                if (record.CURRENTBALANCE === 0) {
                    return <Text style={{ paddingRight: 16 }} type="secondary">{record.ACTUAL_PAYMENT}</Text>
                }
                return <Text style={{ paddingRight: 16 }} type={record.ACCOUNT_TYPE === "9000" ? "success" : undefined}>{record?.ACTUAL_PAYMENT || '-'}</Text>
            }
        },
        {
            dataIndex: 'CURRENTBALANCE',
            title: '剩余未缴',
            hideInSearch: true,
            align: 'right',
            width: 120,
            sorter: (a, b) => a.CURRENTBALANCE - b.CURRENTBALANCE,
            render: (_, record) => {
                if (record.CURRENTBALANCE === 0) {
                    return <Text style={{ paddingRight: 16 }} type="secondary">{record.CURRENTBALANCE || 0}</Text>
                }
                return <Text style={{ paddingRight: 16 }} type={record.ACCOUNT_TYPE === "9000" ? "danger" : undefined}>{record?.CURRENTBALANCE || '-'}</Text>
            },
            filters: [
                {
                    text: '未清缴',
                    value: 0
                }
            ],
            onFilter: (value, record) => record.CURRENTBALANCE !== value,
            // onFilter: true,
        },
        {
            dataIndex: 'option',
            title: '操作',
            valueType: 'option',
            width: "10%",
            align: 'center',
            hideInSearch: true,
            hideInTable: currentUser?.UserPattern === 2000,
            render: (_, record) => {
                return <Space>
                    {
                        (record.ACCOUNT_TYPE !== "9000" || (record.ACCOUNT_TYPE === "9000" && !record.ACTUAL_PAYMENT)) &&
                        <a
                            onClick={() => {
                                getRemark({ TABLE_ID: record.PAYMENTCONFIRM_ID }).then(res => {

                                    if (res) {
                                        const mine = res.find((n: any) => n.STAFF_ID === currentUser.ID)
                                        if (mine) {
                                            setMyRemark(mine)
                                            formRef.current?.setFieldsValue({ userDesc: mine.REMARKS_CONTENT || "" })
                                        }
                                    }
                                })
                                // console.log(data)
                                const imagesPath = record.ATTACHMENT_FILES
                                const images = transferImg(imagesPath ? imagesPath.split(',') : [])
                                setFileList(images)
                                setCurrentRow({ ...record });
                                setStep(1)
                                // setModelType(record.ACCOUNT_TYPE === "9000" && record.ACTUAL_PAYMENT === 0 ? 3 : 2)

                                handleModalVisible(true);
                            }}
                        >编辑</a>
                    }
                    {!record.ACTUAL_PAYMENT && <a onClick={async () => {
                        const suceess = await handleDelete(record?.PAYMENTCONFIRM_ID)
                        if (suceess) {
                            actionRef.current?.reload()
                        }
                    }}>删除</a>}
                    {record.ACCOUNT_TYPE === "9000" && record.CURRENTBALANCE !== 0 &&
                        <a onClick={() => {
                            setCurrentRow({ ...record });
                            setStep(2)
                            handleModalVisible(true);
                        }}>
                            返款
                        </a>
                    }
                    {
                        record.ATTACHMENT_FILES && <a onClick={() => {
                            const imagesPath = record.ATTACHMENT_FILES
                            const images = transferImg(imagesPath ? imagesPath.split(',') : [])
                            setFileList(images)
                            setImagePreviewVisible(true)
                        }}><PictureTwoTone /></a>
                    }
                </Space>;
            },
        },

    ];
    // 删除图片
    const handleChange = async (info: any) => {
        if (info.file.status === 'removed') {
            const deleteLoading = message.loading('正在删除...')

            try {
                const deleteIndex = fileList?.findIndex((n: any) => n.uid === info.file.uid)
                if (deleteIndex !== -1) {
                    const files = [...fileList]
                    files.splice(deleteIndex, 1)
                    setFileList(files)
                }

                deleteLoading()
                return true
            } catch (error) {
                deleteLoading()
                message.error("删除失败")
                return false
            }
        }
        return true
    };
    // 预览上传后的图片
    const handlePreview = async () => {

        setFileList(fileList)
        setImagePreviewVisible(true)

    };
    // 弹出框标题
    const getModelTitle = () => {
        const type = currentRow ? '修改' : '新建'
        const name = currentRow && currentRow.ACCOUNT_TYPE !== "9000" ? '欠款记录' : '回款记录'
        return step === 2 ? '租金拆分日志' : type + name
    }

    return (
        <PageContainer header={{ title: "" }}
            loading={merchartsLoading}
            content={
                merchartsData && merchartsData.COOPMERCHANTS_ID && <Row align="middle">
                    <Col span={17}>
                        {descirption}
                    </Col>
                    <Col span={4}>
                        <Statistic className="payment-amount-card" title={merchartsData?.CURRENTBALANCE ? amountDom(merchartsData?.CURRENTBALANCE) : ""}
                            valueStyle={{ color: "#00000075", fontSize: 14 }}
                            value={"本期欠款"}
                        />
                    </Col>
                    <Col span={3}>
                        <Statistic className="payment-amount-card" title={<span style={{ fontSize: 30, color: "#595959" }}>{moment().format('YYYY/MM/DD')}</span>}
                            valueStyle={{ color: "#00000075", fontSize: 14 }}
                            value={'应缴日期'}
                        // merchartsData?.ACCOUNT_DATE
                        />
                    </Col>
                </Row>
            }
        >
            {merchartsData && merchartsData.COOPMERCHANTS_ID ?
                <>
                    {/* 应收款项目 */}
                    <Card
                        loading={merchartsLoading}
                        tabList={[{ key: "1", tab: '应收款项目' }, { key: "2", tab: '商家往来款' }, { key: "3", tab: '租金拆分日志' }]}
                        activeTabKey={tabActiveIndex}
                        onTabChange={(value) => {
                            setTabActiveIndex(value)
                        }}

                        bordered={false}
                        tabBarExtraContent={
                            <Space>
                                {/* <Text>查询时间：{moment().format('YYYY/MM/DD hh:mm:ss')}</Text> */}
                                {merchartsData?.UNDISTRIBUTED_AMOUNT && merchartsData?.UNDISTRIBUTED_AMOUNT !== 0 ?
                                    <Text style={{ color: "#faad14", textAlign: "left" }}>未分配金额：{merchartsData?.UNDISTRIBUTED_AMOUNT}</Text> : ''}
                                <Text type="secondary">单位：万元</Text>
                                {/* 商户不能进行还款操作 */}
                                {currentUser.UserPattern === 1000 &&
                                    <Button
                                        key="new"
                                        icon={<PlusOutlined />}
                                        type="primary"
                                        onClick={() => {
                                            setStep(1)
                                            // setModelType(3)
                                            handleModalVisible(true);
                                        }}
                                    >
                                        商家来款
                                    </Button>
                                }
                            </Space>
                        }
                    >
                        {tabActiveIndex === '1' && (accountReceivablesList ?
                            accountReceivablesList.map((n: AccountReceivablesModel) =>
                                <div key={n.BUSINESSPROJECT_ID}>
                                    <ProjectItem project={n} selectProject={(item: any) => {
                                        setProject(item)
                                    }} />
                                </div>
                            )
                            : <Empty />)
                        }
                        {/* 商家往来款 */}
                        {tabActiveIndex === '2' && <>
                            <ProTable
                                rowKey="PAYMENTCONFIRM_ID"
                                actionRef={actionRef}
                                request={async (pramas) => {
                                    const data = await getPaymentConfirmList({ ...pramas, ...userDataParams, AccountDate: moment().format("YYYYMMDD"), })

                                    const list = data.data.map((n: any) => {
                                        return {
                                            ...n,
                                            ACCOUNT_AMOUNT: n.ACCOUNT_AMOUNT ? numeral(n.ACCOUNT_AMOUNT).divide(10000).value() : n.ACCOUNT_AMOUNT,
                                            ACTUAL_PAYMENT: n.ACTUAL_PAYMENT ? numeral(n.ACTUAL_PAYMENT).divide(10000).value() : n.ACTUAL_PAYMENT,
                                            CURRENTBALANCE: n.CURRENTBALANCE ? numeral(n.CURRENTBALANCE).divide(10000).value() : n.CURRENTBALANCE
                                        }
                                    });
                                    setPaymentList([...list].reverse())

                                    return { ...data, data: list }
                                }}
                                columns={columns}
                                search={false}
                                pagination={{ defaultPageSize: 10 }}
                                toolBarRender={false}
                            />
                        </>
                        }
                        {/* 租金拆分日志 */}
                        {tabActiveIndex === '3' && <PaymentRecord MERCHANTS_ID={merchartsData?.COOPMERCHANTS_ID_Encrypted} />}
                    </Card>
                    {/* 编辑回款数据弹出 */}
                    <ModalForm<PaymentConfirmModel | any>
                        title={<span>{getModelTitle()}</span>}
                        width={1024}

                        layout={'horizontal'}
                        wrapperCol={{ span: 16 }}
                        labelCol={{ span: 6 }}
                        formRef={formRef}
                        visible={modalVisible}
                        autoFocusFirstInput
                        modalProps={{
                            onCancel: () => {
                            },
                        }}
                        onVisibleChange={(value) => {
                            handleModalVisible(value);
                            if (value) {
                                formRef.current?.setFieldsValue(currentRow)
                            } else {
                                formRef.current?.resetFields();
                                setCurrentRow(undefined);
                                setFileList([])
                                setEditFilds([])

                            }
                        }}
                        onFinish={async (values) => {
                            let success: boolean | PaymentConfirmModel = false

                            if (step === 1) { // 更新回款/欠款记录
                                let newValue: PaymentConfirmModel = { ...values, MERCHANTS_ID: merchartsData?.COOPMERCHANTS_ID };

                                if (currentRow) {
                                    // 编辑数据
                                    newValue = {
                                        ...currentRow,
                                        ...newValue,
                                        ACCOUNT_AMOUNT: numeral(newValue.ACCOUNT_AMOUNT).multiply(10000).value(),
                                        ACTUAL_PAYMENT: numeral(newValue.ACTUAL_PAYMENT).multiply(10000).value(),
                                        CURRENTBALANCE: numeral(currentRow.ACCOUNT_TYPE === "9000" ? newValue.ACCOUNT_AMOUNT : newValue.CURRENTBALANCE).multiply(10000).value(),
                                        ACCOUNT_DATE: currentRow.ACCOUNT_TYPE === "9000" ? newValue.PAYMENTDATE : newValue.ACCOUNT_DATE
                                    };
                                } else {
                                    newValue = {
                                        ...newValue,
                                        ACCOUNT_TYPE: "9000",
                                        MERCHANTS_NAME: merchartsData?.COOPMERCHANTS_NAME,
                                        ACCOUNT_AMOUNT: numeral(newValue.ACCOUNT_AMOUNT).multiply(10000).value()
                                    }

                                }
                                newValue.ATTACHMENT_FILES = fileList.map(n => n.url).toString()
                                const remark = { ...myRemark, TABLE_NAME: 'T_PAYMENTCONFIRM', REMARKS_CONTENT: values.userDesc }

                                success = await handleAddUpdate({ ...newValue }, (myRemark?.REMARKS_ID || values.userDesc) ? remark : undefined);


                            } else {
                                success = await checkAmountAndUpdate() // 校验及提交拆分数据
                            }

                            if (success) {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                    refreshPage()
                                }
                                return true;
                            }
                            return false;
                        }}

                    >
                        {step === 1 && <div style={{ height: 500 }}>
                            <Title level={4} style={{ textAlign: "center", marginBottom: 40 }}>{currentRow?.BUSINESSPROJECT_NAME || merchartsData?.COOPMERCHANTS_NAME}</Title>
                            {
                                currentRow && currentRow?.ACCOUNT_TYPE !== "9000"
                                    ?
                                    <>
                                        <Row>
                                            <Col span={8}>
                                                <ProFormSelect
                                                    name="ACCOUNT_TYPE"
                                                    label="款项类型"
                                                    // width="md"
                                                    readonly
                                                    request={async () => {
                                                        return await getFieldEnum({ FieldExplainField: "ACCOUNT_TYPE" })
                                                    }}
                                                    labelCol={{ span: 12 }}
                                                />
                                            </Col>
                                            <Col span={10}>
                                                <ProFormDatePicker
                                                    readonly
                                                    name="PAYMENTDATE"
                                                    label="回款日期"

                                                    labelCol={{ span: 10 }}
                                                />
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>

                                                <ProFormDigit
                                                    readonly
                                                    name="ACTUAL_PAYMENT"
                                                    label="回款金额"
                                                    fieldProps={{
                                                        formatter: value => `${value}万元`
                                                    }}
                                                    labelCol={{ span: 12 }}

                                                />
                                            </Col>
                                            <Col span={10}>
                                                <ProFormDigit
                                                    name="ACCOUNT_AMOUNT"
                                                    label="应缴金额"
                                                    labelCol={{ span: 10 }}
                                                    fieldProps={{
                                                        formatter: value => `${value}万元`
                                                    }}
                                                    readonly
                                                /></Col>
                                            <Col span={6}>

                                                <ProFormDigit
                                                    name="CURRENTBALANCE"
                                                    label="本期差额"
                                                    fieldProps={{
                                                        formatter: value => `${value}万元`
                                                    }}
                                                    labelCol={{ span: 10 }}
                                                    readonly
                                                />
                                            </Col>
                                            <Col span={24}>
                                                <ProFormTextArea
                                                    name="userDesc"
                                                    label="备注说明"
                                                    wrapperCol={{ span: 18 }}
                                                    labelCol={{ span: 4 }}

                                                />
                                                {!remarkLoading && remarkList.length > 0 &&

                                                    <List
                                                        itemLayout="horizontal"
                                                        dataSource={remarkList.filter((item: any) => item.STAFF_ID !== currentUser.ID)}
                                                        style={{ paddingLeft: 115.22, paddingRight: 85 }}
                                                        renderItem={(item: RemarksModel) => (
                                                            <List.Item>
                                                                <List.Item.Meta
                                                                    avatar={<IconFont name="icon-touxiang" size="36"></IconFont>}
                                                                    title={<div style={{ display: "flex", justifyContent: "space-between", width: "100%" }}><Typography.Text>{item.STAFF_NAME}:</Typography.Text> <Typography.Text style={{ color: "#BBBFC7", fontWeight: 400 }}>{item.OPERATE_DATE}</Typography.Text></div>}
                                                                    description={<Typography.Text type="secondary">{item.REMARKS_CONTENT}</Typography.Text>}
                                                                />

                                                            </List.Item>
                                                        )}
                                                    />
                                                }
                                            </Col>
                                        </Row>
                                    </> :
                                    <>
                                        <Row>
                                            <Col span={12}>
                                                <ProFormDigit
                                                    name="ACCOUNT_AMOUNT"
                                                    label="回款金额"

                                                    width="md"
                                                    fieldProps={{
                                                        formatter: value => value ? `${value}万元` : ''
                                                    }}

                                                    rules={[

                                                        {
                                                            validator: (_, value) => {
                                                                if (!value) {
                                                                    return Promise.reject(new Error('请输入回款金额'))
                                                                }
                                                                if (value && value > 0) {
                                                                    return Promise.resolve()
                                                                }
                                                                return Promise.reject(new Error('回款金额需大于0'))
                                                            },

                                                        },
                                                    ]}
                                                />
                                            </Col>
                                            <Col span={12}>
                                                <ProFormDatePicker

                                                    name="PAYMENTDATE"
                                                    label="回款日期"
                                                    width="md"
                                                    rules={[
                                                        {
                                                            required: true,
                                                            message: '请选择回款日期',
                                                        },
                                                    ]}
                                                    fieldProps={{
                                                        disabledDate: (current) => current && current > moment().endOf('day')
                                                    }}
                                                />
                                            </Col>


                                            <Col span={24}>
                                                <ProFormUploadButton
                                                    labelCol={{ span: 3 }}
                                                    wrapperCol={{ span: 20 }}
                                                    name="files"
                                                    label="回款凭证"
                                                    fileList={fileList}
                                                    onChange={handleChange}
                                                    listType="picture-card"

                                                    fieldProps={{
                                                        beforeUpload,
                                                        onPreview: handlePreview,
                                                        customRequest: async (info) => {
                                                            const formData = new FormData();
                                                            formData.append('files', info.file);
                                                            formData.append('TableName', 'PAYMENTCONFIRM');
                                                            formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
                                                            if (info.filename) {
                                                                // const success = await uploadFile(formData)
                                                                const success = await uploadAHYDFile(formData)

                                                                if (success) {

                                                                    const list = [...fileList, {
                                                                        uid: `${success.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                                                                        name: success.ImageName,
                                                                        status: 'done',
                                                                        url: success.ImageUrl, // url 是展示在页面上的绝对链接
                                                                        imgUrl: success.ImagePath  // + success.ImageUrl,
                                                                    }]
                                                                    setFileList(list)

                                                                }
                                                            } else {

                                                                message.error("您上传的图片不存在.")
                                                            }

                                                        }
                                                    }}

                                                />
                                            </Col>
                                            <Col span={24}>
                                                <ProFormTextArea
                                                    disabled={currentRow?.ACTUAL_PAYMENT}
                                                    name="userDesc"
                                                    label="备注说明"
                                                    // width="md"
                                                    labelCol={{ span: 3 }}
                                                    wrapperCol={{ span: 20 }}
                                                />
                                            </Col>
                                        </Row>
                                        {currentRow && !remarkLoading && remarkList.length > 0 &&

                                            <List
                                                itemLayout="horizontal"
                                                dataSource={remarkList.filter((item: any) => item.STAFF_ID !== currentUser.ID)}
                                                style={{ paddingLeft: 115.22, paddingRight: 85 }}
                                                renderItem={(item: RemarksModel) => (
                                                    <List.Item>
                                                        <List.Item.Meta
                                                            avatar={<IconFont name="icon-touxiang" size="36"></IconFont>}
                                                            title={<div style={{ display: "flex", justifyContent: "space-between", width: "100%" }}><Typography.Text>{item.STAFF_NAME}:</Typography.Text> <Typography.Text style={{ color: "#BBBFC7" }}>{item.OPERATE_DATE}</Typography.Text></div>}
                                                            description={<Typography.Text type="secondary">{item.REMARKS_CONTENT}</Typography.Text>}
                                                        />

                                                    </List.Item>
                                                )}
                                            />
                                        }
                                    </>

                            }
                        </div>}
                        {step === 2 && paymentList &&

                            <EditPaymentTable
                                list={paymentList.filter((n: any) => n.ACCOUNT_TYPE !== "9000" && n.CURRENTBALANCE)}
                                paymentInfo={currentRow}
                                FieldEnum={FieldEnum}
                                amount={currentRow?.CURRENTBALANCE || 0}
                                onChange={setEditFilds}
                            />

                        }

                    </ModalForm>
                    {/* 图片预览组件 */}
                    {fileList.length > 0 && <div style={{ display: 'none' }}>

                        <Image.PreviewGroup

                            preview={{
                                visible: imagePreviewVisible,
                                onVisibleChange: vis => {
                                    if (!vis) {
                                        setFileList([])
                                    }
                                    setImagePreviewVisible(vis)
                                }

                            }}>
                            {
                                fileList.map((n) =>
                                    <Image src={n.url} key={n.url} />
                                )
                            }

                        </Image.PreviewGroup>
                    </div>}
                    {/* 抽屉弹出：欠款的项目详情 */}
                    <Drawer
                        visible={currentProject !== undefined}
                        width={"73%"}
                        onClose={() => {
                            setProject(undefined)
                        }}
                        closable={false}
                        className="project-drawer"
                        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
                    >
                        {currentProject !== undefined &&
                            <ProjectDetail {...{
                                id: currentProject?.BUSINESSPROJECT_ID, showTabs: [2, 1, 3],
                                tabActive: "2", isPayment: true, price: currentProject.PAYABLE_AMOUNT || 0, date: currentProject.ACCOUNT_DATE
                            }}></ProjectDetail>}
                    </Drawer>
                </> : <Card>
                    <Result title="查询失败"
                        subTitle="没有合同信息,无法查询到相关的租金情况。"
                        extra={[
                            <Button type="primary" key="console" onClick={() => history.push('/merchantManagement/workplace')}>
                                返回工作台
                            </Button>]}
                    />
                </Card>}
        </PageContainer >
    );
}

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