/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-09-18 09:40:02
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-12-16 11:10:33
 * @FilePath: \cloud-platform\src\pages\DataVerification\additionalRecord\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import { Button, FormInstance, message, Modal, Select, Typography } from "antd";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import useRequest from "@ahooksjs/use-request";
import { handleGetServerpartTree } from "@/pages/basicManage/serverpartAssets/service";
import { handleGetServerpartShopList, handleGetServiceShopList, handleGetSuppEndaccountList } from "../service";
import moment from 'moment'
import DetailForm from "./components/detailForm";
import { handleSynchroENDACCOUNT } from "../list/service";
import PageTitleBox from "@/components/PageTitleBox";


const additionalRecord: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const detailFormRef = useRef<any>();
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 服务区列表
    const [serverPartList, setServerPartList] = useState<any>()
    // 当前选择服务区所对应的门店列表
    const [shopList, setShopList] = useState<any>()
    // 当前选择的服务区
    const [selectServerPart, setSelectServerPart] = useState<any>()
    // 当前选择的门店
    const [selectShop, setSelectShop] = useState<any>()
    // 显示详情的悬浮框
    const [showDetail, setShowDetail] = useState<boolean>(false)
    // 行数据
    const [currentRow, setCurrentRow] = useState<any>()


    const { loading: treeLoading, data: treeView = [] } = useRequest(async () => {
        const req: any = {
            ProvinceCode: currentUser?.ProvinceCode,
            ServerpartType: 1000,
            ShowWholePower: false,
            ShowSPRegion: false,
            ShowRoyalty: false,
            ShowCompactCount: false,
        }
        const data = await handleGetServerpartTree(req)
        let list: any = []
        // 测试服务区放最后
        let testObj: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                if (item.value !== 424) {
                    if (item.value === 586) {
                        testObj = item
                    } else {
                        list.push(item)
                    }
                }
            })
        }
        if (testObj.value) {
            list.push(testObj)
        }
        // list.push({ label: '全部', value: '' })
        list.unshift({ label: '全部', value: '' })
        setServerPartList(list)
    })

    const columns: any = [
        {
            title: '序号',
            width: 50,
            dataIndex: 'index',
            valueType: 'index',
            align: 'center',
            hideInSearch: true
        },
        {
            title: '服务区',
            width: 180,
            dataIndex: 'SERVERPART_NAME',
            renderFormItem: () => {
                return <Select
                    options={serverPartList}
                    onChange={(e: any) => {
                        console.log('e', e);
                        if (e) {
                            handleGetShopList(e)
                            setSelectServerPart(e)
                        } else {
                            setShopList([])
                            setSelectServerPart(undefined)
                        }
                    }}
                    allowClear
                    showSearch={true}
                    optionFilterProp="label"
                />
            },
        },
        {
            title: '门店名称',
            width: 180,
            dataIndex: 'SHOPNAME',
            ellipsis: true,
            renderFormItem: () => {
                return <Select
                    options={shopList}
                    onChange={(e: any) => {
                        console.log('e', e);
                        if (e) {
                            handleGetShopList(e)
                            setSelectShop(e)
                        } else {
                            setShopList([])
                            setSelectShop(undefined)
                        }
                    }}
                    allowClear
                    showSearch={true}
                    optionFilterProp="label"
                />
            },
            render: (_, record) => {
                return <a onClick={() => {
                    console.log('record', record);
                    setCurrentRow(record)
                    setShowDetail(true)
                }}>
                    {record?.SHOPNAME || ''}
                </a>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>实收金额</div>,
            width: 120,
            dataIndex: 'CASHPAY',
            valueType: "digit",
            align: 'right',
            hideInSearch: true,
        },
        {
            title: '结账日期',
            width: 180,
            dataIndex: 'ENDACCOUNT_DATE',
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            initialValue: [moment().subtract(1, 'd').format('YYYY-MM-DD'), moment().subtract(1, 'd').format('YYYY-MM-DD')],
            search: {
                transform: (value) => {
                    return {
                        StartDate: value[0],
                        EndDate: value[1],
                    };
                },
            },
            fieldProps: {
                disabledDate: (current: any) => current && current > moment()
            }
        },
        {
            title: '上传人员',
            width: 120,
            dataIndex: 'DESCRIPTION_STAFF',
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '有效状态',
            width: 80,
            dataIndex: 'VALID',
            align: 'center',
            valueType: 'select',
            valueEnum: {
                0: { text: '无效', status: 'Default' },
                1: { text: '有效', status: 'Processing' },
            }
        }
    ]

    // 拿到当前服务区的门店列表
    const handleGetShopList = async (id: any) => {
        const req = {
            SearchParameter: {
                SERVERPART_IDS: id,
                ISVALID: 1
            },
            PageIndex: 1,
            PageSize: 999999,
            SortStr: "SHOPREGION,SHOPTRADE,SHOPSHORTNAME,SHOPCODE"
        }
        const data = await handleGetServerpartShopList(req)
        console.log('shop', data);
        let list: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                list.push({ label: item.SHOPNAME, value: item.SHOPCODE })
            })
        }
        setShopList(list)
    }

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <div style={{
                    width: "100%",
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        headerTitle={<PageTitleBox props={props} />}
                        search={{ span: 6 }}
                        request={async (params) => {
                            setSearchParams(params)

                            const req: any = {
                                ServerpartIds: selectServerPart || '',
                                ServerpartShopCode: selectShop || '',
                                StartDate: params?.StartDate ? moment(params?.StartDate).format('YYYY-MM-DD') : '',
                                EndDate: params?.EndDate ? moment(params?.EndDate).format('YYYY-MM-DD') : '',
                                EndaccountState: params?.VALID || '',
                                PageIndex: 1,
                                PageSize: 999999,
                                SortStr: 'ENDACCOUNT_DATE desc'
                            }
                            const data = await handleGetSuppEndaccountList(req)
                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: data, success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Typography.Text type="secondary">注：上传人员含【补】指该笔账单为历史结账数据批量补入</Typography.Text>,
                                <Button type="primary" onClick={() => {
                                    setShowDetail(true)
                                }}>
                                    添加
                                </Button>
                            ]
                        }}
                    />
                </div>
            </div>
            <Modal
                width={800}
                open={showDetail}
                title={currentRow ? '数据补录详情' : '新增数据补录'}
                footer={
                    <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
                        <Button onClick={() => {
                            setShowDetail(false)
                            setCurrentRow(undefined)
                        }}>取消</Button>
                        {
                            currentRow?.ENDACCOUNT_ID ? '' :
                                <Button type="primary" style={{ marginLeft: '8px' }} onClick={() => {
                                    detailFormRef?.current?.formRef?.current?.validateFields().then(async (res: any) => {
                                        let [SERVERPART_Name, SERVERPART_ID] = res?.SERVERPART_ID.split('-')
                                        let [shopName, shopCode] = res?.SHOPCODE.split('-')
                                        const req: any = {
                                            ...res,
                                            OPERATE_TYPE: 1010,
                                            ENDACCOUNT_STARTDATE: res?.ENDACCOUNT_STARTDATE ? moment(res?.ENDACCOUNT_STARTDATE).format('YYYY-MM-DD') : '',
                                            ENDACCOUNT_DATE: res?.ENDACCOUNT_DATE ? moment(res?.ENDACCOUNT_DATE).format('YYYY-MM-DD') : '',
                                            SERVERPART_NAME: SERVERPART_Name,
                                            SERVERPART_ID: SERVERPART_ID,
                                            SHOPNAME: shopName,
                                            SHOPCODE: shopCode,
                                            DIFFERENT_PRICE: res?.CASHPAY_DOWNLORD - res?.CASH,
                                            TREATMENT_MARK: 1,
                                            DWONLOAD_DATE: moment().format('YYYY-MM-DD'),
                                            VALID: 1
                                        }
                                        console.log('req', req);
                                        const data = await handleSynchroENDACCOUNT(req)
                                        if (data.Result_Code === 100) {
                                            message.success(data.Result_Desc)
                                            setShowDetail(false)
                                            setCurrentRow(undefined)
                                            actionRef.current?.reload()
                                        } else {
                                            message.error(data.Result_Desc)
                                        }

                                    })
                                }}>确认</Button>
                        }
                    </div>
                }
                destroyOnClose
                onCancel={() => {
                    setShowDetail(false)
                    setCurrentRow(undefined)
                }}
            >
                <DetailForm parentRow={currentRow} onRef={detailFormRef} />
            </Modal>
        </div>
    )
}

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