/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-03-18 15:52:26
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-16 15:54:53
 * @FilePath: /CostAccountingSys/src/pages/monthlyInfoCollection/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import KCIMPagecontainer from "@/components/KCIMPageContainer"
import { DatePicker, message, Input, Modal, Table } from 'antd';
import { Key, useEffect, useRef, useState } from "react";


import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import './style.less';
import { KCIMLeftList } from "@/components/KCIMLeftList";
import { formatMoneyNumber } from "@/utils/format";
import { createFromIconfontCN } from "@ant-design/icons";
import { KCIMTable } from "@/components/KCIMTable";
import { ActionType, ProColumns } from "@ant-design/pro-components";
import { getResponsibilityCenterList } from "../baseSetting/responsibilityCenterSet/responsibilityCenter/service";
import { getIncomeCollectionReq, getTableDataReq } from "./service";
import { cancelIncomeCollection, getAfterIncomeCollectionTableData, startIncomeCollection } from "../costAccounting/calcPageTemplate/service";
import { useModel } from "@umijs/max";

const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

const tableColumn: ProColumns[] = [
    {
        title: '科室代码',
        ellipsis: true,
        dataIndex: 'departmentCode',
    },
    {
        title: '科室名称',
        ellipsis: true,
        dataIndex: 'departmentName',
    },
    {
        title: '会计科目',
        ellipsis: true,
        dataIndex: 'accountingName',
    },
    {
        title: '收入项目',
        ellipsis: true,
        dataIndex: 'productName',
    },
    {
        title: '金额',
        ellipsis: true,
        dataIndex: 'amount',
    },
];


const IncomeCollectionAction = () => {
    const tableRef = useRef<ActionType>();

    const { initialState,setInitialState } = useModel('@@initialState');
    const [computeDate, set_computeDate] = useState<string>(initialState?initialState.computeDate:'');
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>({ computeDate });
    const [incomeCollectionData,set_incomeCollectionData] = useState<any>(undefined);
    const [loading, set_loading] = useState(false);

    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
    const [leftTreeData, set_leftTreeData] = useState<any[]>([]);
    const [currentResp, set_currentResp] = useState<any>(undefined);
    const [currentSelectedLeftObj, set_currentSelectedLeftObj] = useState<any>(undefined);


    const onLeftChange = (item: any) => {
        set_currentSelectedLeftObj(item);
        // _currentSelectedLeftObj = item;
    }

    const getIncomeCollection = async ()=>{
          const resp = await getIncomeCollectionReq({computeDate,current:1,pageSize:100});
 
          if(resp&&resp.list.length>0){

            set_incomeCollectionData(resp.list[0])
          }else{
            set_incomeCollectionData(undefined)
          }
    }

    const getTableData = async (params: any) => {
        const { computeDate, responsibilityCode } = params;
        if (!computeDate && !responsibilityCode) return [];
        const resp = await getTableDataReq({ ...params, ...tableDataFilterParams });
        if (resp) {
            set_currentResp(resp);
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return {
            data: [],
            success: true
        }
    }

    const tableDataSearchHandle = (paramName: string) => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })
    }

    const getTreeData = async () => {
        let totalData: any[] = [];
        let page = 1;
        const pageSize = 500;

        const fetchPage = async (page: number) => {
            const resp = await getResponsibilityCenterList({ pageSize, current: page });
            if (resp && resp.list.length > 0) {
                totalData = totalData.concat(resp.list);
                // 如果返回的数据量等于每页的大小，说明可能还有下一页
                if (resp.list.length === pageSize) {
                    await fetchPage(page + 1);
                }
            }
        };

        await fetchPage(page);
        set_leftTreeData([...totalData]);
        return totalData;
    };

    const openDataTable = async () => {
        set_loading(true);
        try {
            const { responsibilityCode = null } = tableDataFilterParams;

            const resp = await getAfterIncomeCollectionTableData(
                { date: `${computeDate.replace(/-/g, '')}` }
            );

            if (resp) {
                const { titleMap = {}, realData = [], totalMap = {} } = resp;
                const titleMapToArr = Object.entries(titleMap);
                const totalMapToArr = Object.entries(totalMap);
                const columns = [...titleMapToArr].map((item, index) => {
                    if (index == 0 || index == [...titleMapToArr].length - 1) {
                        return {
                            title: item[1],
                            key: item[0],
                            dataIndex: item[0],
                            fixed: index == 0 ? 'left' : 'right',
                            width: 150,
                        }
                    }
                    return {
                        title: item[1],
                        dataIndex: item[0],
                        key: item[0],
                        width: 150,
                    }
                });
                set_loading(false);
                Modal.info({
                    title: '报表数据',
                    icon: '',
                    okText: '确定',
                    width: 800,
                    content: (
                        <KCIMTable
                            rowKey='id'
                            scroll={{ x: (columns.length) * 150, y: 450 }}
                            columns={columns as ProColumns[]}
                            dataSource={[...realData]}
                            pagination={false}
                            summary={() => (
                                <Table.Summary fixed >
                                    <Table.Summary.Row className="rowCell">
                                        {/* <Table.Summary.Cell className="firstCell" index={0}>合计</Table.Summary.Cell> */}
                                        {
                                            totalMapToArr.map((item, index) => {
                                                return (
                                                    <Table.Summary.Cell key={index} className={index == totalMapToArr.length - 1 ? 'ant-table-cell ant-table-cell-fix-right ant-table-cell-fix-right-last' : 'cell'} index={index}>{item[1] as any}</Table.Summary.Cell>
                                                )
                                            })
                                        }
                                    </Table.Summary.Row>
                                </Table.Summary>
                            )}
                        />
                    )
                })

            }
        } catch (err) {
            console.log({ err });
        }


    }

    const optionBtnGroupshandle = async () => {
        const { year, month } = incomeCollectionData?incomeCollectionData:{year:(computeDate.split('-'))[0],month:(computeDate.split('-'))[1]};
          if (incomeCollectionData&&incomeCollectionData.isCollection) {
            const resp = await cancelIncomeCollection({ year, month });
            if (resp) {
              message.success('操作成功！');
              getIncomeCollection();
              tableRef.current?.reload();
            }
          } else {
            Modal.confirm({
              title: '注意',
              content: '收入归集操作会覆盖已有的归集后数据，确定要继续操作？',
              okText: '确定',
              cancelText: '取消',
              onOk: async (...args) => {
                set_loading(true);
                const resp = await startIncomeCollection({ year, month });
                if (resp) {
    
                  set_loading(false);
                  message.success('操作成功！');
                  tableRef?.current?.reload();
                  getIncomeCollection();
                } else {
                  set_loading(false);
                }
              },
            })
          }
    }

    useEffect(() => {
        if (currentSelectedLeftObj) {
            set_tableDataFilterParams({ ...tableDataFilterParams, responsibilityCode: currentSelectedLeftObj.responsibilityCode,accountFilter:'' })
            set_tableDataSearchKeywords('');
        }
    }, [currentSelectedLeftObj]);


    useEffect(()=>{
        getIncomeCollection();
    },[computeDate])

    useEffect(() => {
        getTreeData();
        getIncomeCollection();
    }, [])


    return (
        <KCIMPagecontainer className="IncomeCollectionAction" title={false}>

            <div className="header">
                <div className="search">
                    <span>核算年月：</span>
                    <DatePicker
                        onChange={(data, dateString) => {
                            set_computeDate(dateString);
                            set_tableDataFilterParams({
                                ...tableDataFilterParams,
                                computeDate: dateString,
                                accountFilter:''
                            });
                            setInitialState((s:any)=>({...s,computeDate: dateString,}));
                            set_tableDataSearchKeywords('');
                        }}
                        picker="month"
                        locale={locale}
                        defaultValue={moment(computeDate, 'YYYY-MM')}
                        format="YYYY-MM"
                        placeholder="选择年月"
                    />
                </div>
                <div className="btnGroup">
                    <span className="check" onClick={() => openDataTable()}>报表数据</span>
                    <span className="oneKeyGet" onClick={() => optionBtnGroupshandle()}>{(incomeCollectionData&&incomeCollectionData.isCollection) ? '撤销归集' : '开始归集'}</span>
                </div>
            </div>
            <div className="pageContent">
                <div className="line">
                    <div className="info">
                        <img src={require('../../../static/multiblock.png')} alt="" />
                        全部科室合计：
                        <span>{currentResp ? formatMoneyNumber(currentResp.totalAmount) : '0.00'}元</span>
                    </div>
                </div>
                <div className="contentWrapper">

                    <div className="left">
                        <KCIMLeftList
                            fieldNames={{ title: 'responsibilityName', key: 'responsibilityCode', children: 'child' }}
                            rowKey={'responsibilityCode'}
                            contentH={`calc(100vh - 270px)`}
                            dataSource={leftTreeData} searchKey={'responsibilityName'} onChange={onLeftChange}
                            placeholder={'责任中心'} listType={'tree'}
                            icon={undefined}
                        />
                    </div>
                    <div className="right">
                        <div className="toolBar" style={{ display: 'flex' }}>
                            <div className="leftTool">当前科室合计：<span>{currentResp ? formatMoneyNumber(currentResp.departmentAmount) ? currentResp.departmentAmount : '0.00' : '0.00'}元</span></div>
                            <div className="rightTool">
                                <div className='filterItem' style={{ marginLeft: 16, width: 233 }}>
                                    <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                                    <Input placeholder={'会计科目代码/名称'} allowClear value={tableDataSearchKeywords}
                                        suffix={
                                            <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle(`accountFilter`)} />
                                        }
                                        onChange={(e) => {
                                            set_tableDataSearchKeywords(e.target.value);
                                            if (e.target.value.length == 0) {
                                                set_tableDataFilterParams({
                                                    ...tableDataFilterParams,
                                                    'accountFilter': ''
                                                });
                                            }
                                        }}
                                        onPressEnter={(e) => {
                                            set_tableDataFilterParams({
                                                ...tableDataFilterParams,
                                                'accountFilter': ((e.target) as HTMLInputElement).value
                                            });
                                        }}

                                    />
                                </div>
                            </div>
                        </div>
                        <KCIMTable actionRef={tableRef} columns={tableColumn}
                            rowKey='id'
                            request={(params) => getTableData(params)}
                            tableAlertRender={false}
                            scroll={{ x: scrollX,y:`calc(100vh - 322px)` }}
                            params={tableDataFilterParams}
                        />
                    </div>
                </div>
            </div>

        </KCIMPagecontainer>
    )

}

export default IncomeCollectionAction