/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-11-20 15:29:57
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

import { createFromIconfontCN } from '@ant-design/icons';


import { ActionType, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect, ProFormTextArea, ProFormTreeSelect } from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Tag, Tabs } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';



import { addData, copyParamsList, delData, editData, getCostshareparamConnectList, getResponsibilityCenterSelecterList, saveParamsList } from './service';

import './style.less';
import { getAccountingSubjectList } from '../../accountingAccountSet/accountingSubMana/service';
import { getChilds } from '@/utils/tooljs';
import EditTableModal from './editTableModal';
import TableSelecter from './tableSelector';


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



export default function AllocationParamsMap() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>(undefined);
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);
    const [selectableLevelList, setSelectableLevelList] = useState([]);//可选的分摊层级列表
    const [tabs, set_tabs] = useState<any[]>([]);
    const [accountType, set_accountType] = useState<Key>(1);

    const [selectedResponsibilityId, setSelectedResponsibilityId] = useState(null);
    const [selectedResponsibility, setSelectedResponsibility] = useState(null);

    const [editTableVisible, set_editTableVisible] = useState(false);
    const [tableSelecterVisible,set_tableSelecterVisible] = useState(false);


    const columns: ProColumns[] = [

        {
            title: '分摊级别',
            ellipsis:true,
            dataIndex: 'shareLevel',
        },
        {
            title: '责任中心编码',
            ellipsis:true,
            dataIndex: 'responsibilityCode',
        },
        {
            title: '责任中心名',
            ellipsis:true,
            dataIndex: 'responsibilityName',
        },
        {
            title: '会计科目名称',
            ellipsis:true,
            dataIndex: 'accountingNames',
        },
        {
            title: '会计科目编码',
            ellipsis:true,
            dataIndex: 'accountingCodes',
        },
        {
            title: '别名',
            ellipsis:true,
            dataIndex: 'alias',
        },
        {
            title: '备注',
            ellipsis:true,
            dataIndex: 'costNode',
        },
        {
            title: '操作',
            key: 'option',
            width:200,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    
                    <a key='copy' onClick={()=>{set_tableSelecterVisible(true);setCurrentRow(record);}}>复制</a>,
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>,
                    <a key='share' onClick={()=>{set_editTableVisible(true);setCurrentRow(record)}}>分摊参数</a>

                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const resp = await getCostshareparamConnectList({ ...params });
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }


    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })

    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            message.success('操作成功！');
            tableRef.current?.reload();
            // message.success('操作成功!');
        }
    }

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        const result = {
            responsibilityId: formVal.responsibilityId,
            accountingIds: formVal.accountingIds.join(','),
            isShareCost: formVal.isShareCost,
            alias: formVal.alias,
            costNode: formVal.costNode,
            responsibilityName: formVal.responsibility.responsibilityName,
            shareLevel: formVal.responsibility.shareLevel,
            responsibilityCode: formVal.responsibility.responsibilityCode
        };

        if (type == 'ADD') {
            const resp = await addData(result);
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

            try {
                const resp = await editData({ ...formVal, isBaseCost: formVal.isBaseCost, isIncomeGroutSetSelect: false, isShareParamSelect: false, accountType });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            } catch (error) {
                console.log({ error });
            }

        }
        return true;

    }


    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' }) => {

        const [ifDisable, setIfDisable] = useState(false);
        let needDisableIds: any[] = [];
        let accountingIds:Key[] = [];

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}成本分摊参数对应`}
                width={350}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val,accountingIds } : { ...val,accountingIds }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText name="responsibility" hidden />
                <ProFormSelect
                    rules={[
                        {
                            required: true,
                            message: '请选择责任中心',
                        },
                    ]}
                    fieldProps={{
                        onChange: async (val, option: any) => {
                            const { } = option;
                            const resp = await getResponsibilityCenterSelecterList();
                            // const resp = [
                            //     {
                            //         calcType: 1,
                            //         id: 401,
                            //         responsibilityCode: "B0100",
                            //         responsibilityId: 401,
                            //         responsibilityName: "公共费用",
                            //         shareId: 59,
                            //         shareLevel: 1,
                            //         shareName: "公共费用",
                            //     }
                            // ]
                            if (resp) {
                                const selected = resp.filter((item: any) => item.id == val);
                                if (selected[0]) {
                                    formRef.current?.setFieldValue('responsibility', selected[0]);
                                }
                            }


                            if (needDisableIds.includes(val)) {
                                setIfDisable(false);
                            } else {
                                setIfDisable(true);
                            }
                        },
                    }}
                    request={async () => {
                        const resp = await getResponsibilityCenterSelecterList();
                        // const resp = [
                        //     {
                        //         calcType: 1,
                        //         id: 401,
                        //         responsibilityCode: "B0100",
                        //         responsibilityId: 401,
                        //         responsibilityName: "公共费用",
                        //         shareId: 59,
                        //         shareLevel: 1,
                        //         shareName: "公共费用",
                        //     }
                        // ]
                        if (resp) {
                            return resp.map((item: any) => {
                                if (item.calcType == 1) {
                                    needDisableIds.push(item.id);
                                }
                                return ({
                                    label: item.responsibilityName,
                                    value: item.id,
                                })
                            })
                        }
                        return []
                    }}
                    name="responsibilityId"
                    label="请选择责任中心"
                />
                <ProFormTreeSelect
                    disabled={ifDisable}
                    allowClear
                    rules={[
                        {
                            required: ifDisable ? false : true,
                            message: '请选择会计科目',
                        },
                    ]}
                    request={async () => {
                        const resp = await getAccountingSubjectList({ accountType, pageSize: 500, current: 1 });

                        // const resp = {
                        //     list: [
                        //         {
                        //             accountingCode: "C0160",
                        //             accountingName: "其他支出",
                        //             id: 259,
                        //             isBaseCost: 0,
                        //             isIncomeGroutSetSelect: false,
                        //             isShareParamSelect: false,
                        //             children: [
                        //                 {
                        //                     accountingCode: "C0164",
                        //                     accountingName: "社会服务辅助",
                        //                     id: 263,
                        //                     isBaseCost: 0,
                        //                     isIncomeGroutSetSelect: false,
                        //                     isShareParamSelect: false,
                        //                 }
                        //             ]
                        //         }
                        //     ]
                        // };
                        if (resp) {
                            return resp.list
                        }
                        return []
                    }}
                    fieldProps={{
                        showSearch: true,
                        multiple: true,
                        treeCheckable:true,
                        treeNodeFilterProp: 'accountingName',
                        showCheckedStrategy:'SHOW_CHILD',
                        fieldNames: {
                            label: 'accountingName',
                            value: 'id'
                        },
                        onSelect: (value, opt) => {
                            // console.log({ value, opt });
                            // console.log(getChilds(opt,'children'));
                            if(opt.children&&opt.children.length>0){
                                  const childs = getChilds(opt,'children');
                                  const ids = childs.map((a)=>a.id);
                                  accountingIds = accountingIds.concat(ids);
                            }else{
                                accountingIds.push(value);
                            }
                        }
                    }}
                    name="accountings"
                    label="选择会计科目"
                />
                <ProFormSelect
                    disabled={ifDisable}
                    rules={[
                        {
                            required: ifDisable ? false : true,
                            message: '请选择',
                        },
                    ]}
                    request={async () => [
                        { label: '不包含分摊成本', value: 0 },
                        { label: '包含分摊成本', value: 1 }
                    ]}
                    name="isShareCost"
                    label="是否包含分摊成本"
                />
                <ProFormText
                    name="alias"
                    label="别名"
                />
                <ProFormTextArea
                    name="costNode"
                    label="备注"
                    placeholder="请输入备注"
                />
            </ModalForm>
        )
    }

    const shareParamsSetCommit = async (rows:any[])=>{
          const resp = await saveParamsList({id:currentRow.id,shareParamProportionVOList:rows});
          if(resp){
               set_editTableVisible(false);
               message.success('操作成功！');
               tableRef.current?.reload();
          }
    }

    const tableSelecterCommit = async (keys:Key[],rows:any) => {
        const { id } = currentRow;
        const resp = await copyParamsList({ id, responsibilityIds: keys });
        if(resp){
            set_tableSelecterVisible(false);
            message.success('操作成功！');
            tableRef.current?.reload();
        }
    }

    return (
        <KCIMPagecontainer className='AllocationParamsMap' title={false}>
            <EditTableModal
                onVisibleChange={(bool) => set_editTableVisible(bool)}
                title='分摊参数设置'
                rowKey={'id'}
                record={currentRow}
                open={editTableVisible}
                onFinish={(rows) => shareParamsSetCommit(rows)}
            />
            <TableSelecter
                onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
                title='选择复制目标'
                rowKey={'id'}
                defaultSelectedKeys={[]}
                record={currentRow}
                open={tableSelecterVisible}
                onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
            />
            <div className='toolBar' >
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'责任中心名称'} allowClear
                            suffix={
                                <IconFont type="iconsousuo" style={{color:'#99A6BF'}} onClick={() => tableDataSearchHandle('name')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        name: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    name: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>

            <div>
                <KCIMTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </KCIMPagecontainer>
    )
}
