import { connect } from "umi";
import moment from 'moment'
import './historyTable.less'
import { useImperativeHandle, useRef, useState } from "react";
import { ActionType, FormInstance, ProTable } from "@ant-design/pro-components";
import { message, Popconfirm } from "antd";
import { handleDeletePROPERTYSHOP, handleGetBusinessProjectList, handleGetPROPERTYSHOPList, handleGetServerpartShopList } from "../service";

type DetailProps = {
    currentRow: any
    onRef: any
    currentUser?: any
    defaultId?: any // 可能存在的外部默认绑定的门店
}
const HistoryTable = ({ currentRow, onRef, currentUser, defaultId }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();

    const columns: any = [
        {
            title: '门店名称',
            dataIndex: 'SHOPNAME',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '项目名称',
            dataIndex: 'BUSINESSPROJECT_NAME',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '项目开始时间',
            dataIndex: 'PROJECT_STARTDATE',
            hideInSearch: true,
            render: (_, record) => {
                return record?.PROJECT_STARTDATE ? moment(record?.PROJECT_STARTDATE).format('YYYY-MM-DD') : ''
            }
        },
        {
            title: '项目结束时间',
            dataIndex: 'PROJECT_STARTDATE',
            hideInSearch: true,
            render: (_, record) => {
                return record?.PROJECT_ENDDATE ? moment(record?.PROJECT_ENDDATE).format('YYYY-MM-DD') : ''
            }
        },
        {
            title: '门店状态',
            dataIndex: 'BUSINESS_STATE',
            valueType: 'select',
            hideInSearch: true,
            valueEnum: {
                1000: { text: '运营中', status: 'processing' },
                2000: { text: '已暂停', status: 'warning' },
                3000: { text: '已关闭', status: 'error' },
                1010: { text: '待运营', status: 'default' }
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            hideInSearch: true,
            render: (_, record) => {
                return record?.showDelete ? <Popconfirm
                    title={'确认删除关联？'}
                    onConfirm={() => {
                        console.log('record', record);
                        deleteAssociation(record)
                    }}
                >
                    <a >删除关联</a>
                </Popconfirm> : ''
            }
        }
    ]

    const deleteAssociation = async (obj: any) => {
        const req: any = {
            Id: obj?.PROPERTYASSETS_ID,
            RelatedId: obj?.PROPERTYSHOP_ID,
            OperateId: currentUser?.ID,
            OperateName: currentUser?.Name
        }
        console.log('req', req);

        const data = await handleDeletePROPERTYSHOP(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 选中的行
    const [selectedModalOrderRowKeys, setSelectedModalOrderRowKeys] = useState<any>()
    // 选中的行数据
    const [selectModalRowList, setSelectModalRowList] = useState<any>()
    const modalRowSelection: any = {
        defaultSelectedRowKeys: selectedModalOrderRowKeys,
        selectedRowKeys: selectedModalOrderRowKeys,
        preserveSelectedRowKeys: true,
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            console.log('selectedRowKeys', selectedRowKeys);
            console.log('selectedRows', selectedRows);
            setSelectModalRowList(selectedRows)
            setSelectedModalOrderRowKeys(selectedRowKeys)
        },
        getCheckboxProps: (record: any) => ({
            disabled: record.disable,
        }),
    };


    useImperativeHandle(onRef, () => ({
        selectModalRowList,
        setSelectedModalOrderRowKeys
    }));



    return (
        <div>
            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                className="historyTable"
                rowKey={(record) => {
                    return `${record?.SERVERPARTSHOP_ID}`
                }}
                scroll={{ y: 'calc(100vh - 320px)' }}
                pagination={false}
                request={async () => {
                    console.log('defaultId', defaultId);

                    console.log('currentRow', currentRow);

                    let req: any = {
                        SearchParameter: {
                            SERVERPART_IDS: currentRow?.SERVERPART_ID,
                            SHOPREGION: currentRow?.PROPERTYASSETS_REGION,
                            ISVALID: 1
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    }
                    const data = await handleGetServerpartShopList(req)
                    console.log('shopData', data);

                    let projectReq: any = {
                        SearchParameter: {
                            SERVERPART_IDS: currentRow?.SERVERPART_ID,
                            PROJECT_VALID: 1
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    }
                    const projectData = await handleGetBusinessProjectList(projectReq)

                    // 拿到之前的勾选数据
                    const historySelect = await handleGetPROPERTYSHOPList({
                        SearchParameter: {
                            PROPERTYASSETS_ID: currentRow?.PROPERTYASSETS_ID
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    })
                    let select: any = []
                    let selectDetail: any = []
                    // 当前绑定的门店
                    let nowSelect: any = ''


                    if (historySelect && historySelect.length > 0) {
                        historySelect.forEach((item: any) => {
                            // 这里只默认勾选历史的 当前的勾选
                            if (item.PROPERTYSHOP_STATE !== 1) {
                                select.push(item.SERVERPARTSHOP_ID.toString())
                                selectDetail.push(item)
                            } else {
                                nowSelect = item.SERVERPARTSHOP_ID.toString()
                            }
                        })
                        console.log('select', select);
                        setSelectedModalOrderRowKeys(select)
                    }



                    console.log('projectData', projectData);
                    if (data && data.length > 0 && projectData && projectData.length > 0) {
                        let newData = JSON.parse(JSON.stringify(data))
                        newData.forEach((item: any) => {
                            projectData.forEach((subItem: any) => {
                                if (subItem.SERVERPARTSHOP_ID.indexOf(item.SERVERPARTSHOP_ID.toString()) !== -1) {
                                    item.BUSINESSPROJECT_NAME = subItem.BUSINESSPROJECT_NAME
                                    item.PROJECT_ENDDATE = subItem.PROJECT_ENDDATE
                                    item.PROJECT_STARTDATE = subItem.PROJECT_STARTDATE
                                    item.BUSINESSPROJECT_ID = subItem.BUSINESSPROJECT_ID
                                }
                            })
                        })
                        console.log('res', newData);
                        console.log('selectDetail', selectDetail);

                        if (newData && newData.length > 0) {
                            let rowList: any = []
                            newData.forEach((item: any) => {
                                if (select && select.length > 0) {
                                    if (select.indexOf(item.SERVERPARTSHOP_ID.toString()) !== -1) {
                                        let index: number = select.indexOf(item.SERVERPARTSHOP_ID.toString())
                                        console.log('index', index);

                                        item.PROPERTYASSETS_ID = selectDetail[index].PROPERTYASSETS_ID
                                        item.PROPERTYSHOP_ID = selectDetail[index].PROPERTYSHOP_ID
                                        rowList.push(item)
                                        item.showDelete = true
                                    }
                                }
                            })
                            console.log('rowList', rowList);
                            setSelectModalRowList(rowList)
                        }
                        newData = newData.filter((item: any) => item.SERVERPARTSHOP_ID.toString().indexOf(nowSelect) === -1)
                        console.log('res', newData);

                        return { data: newData, success: true }
                    }
                    return { data: [], success: true }
                }}
                rowSelection={{
                    type: 'checkbox',
                    ...modalRowSelection,
                }}
            />

        </div>
    )
}

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