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

type DetailProps = {
    currentRow: any;
    detailFormRef?: any;
    onRef?: any;
    show: boolean;
    defaultId?: any
    currentUser?: any
    parentRef?: any
}
const relatedShop = ({ currentRow, detailFormRef, onRef, show, defaultId, currentUser, parentRef }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [noSelect, setNoSelect] = useState<boolean>(false)

    const columns: any = [
        {
            title: '门店名称',
            width: 120,
            ellipsis: true,
            dataIndex: 'SHOPNAME',
            render: (_, record) => {
                return <div style={{ display: 'flex', alignItems: 'center' }}>
                    <span className={record?.BUSINESS_STATE === 1000 ? "ant-badge-status-dot ant-badge-status-processing" :
                        record?.BUSINESS_STATE === 1010 ? "ant-badge-status-dot ant-badge-status-default" : record?.BUSINESS_STATE === 2000 ? "ant-badge-status-dot ant-badge-status-warning" :
                            record?.BUSINESS_STATE === 3000 ? "ant-badge-status-dot ant-badge-status-error" : ""}></span>
                    <span style={{ marginLeft: '4px' }}>{record?.SHOPNAME || ''}</span>
                </div>
            }
        },
        {
            title: '资产编码',
            width: 120,
            ellipsis: true,
            dataIndex: 'PROPERTYASSETS_CODE',
        },
        {
            title: '操作',
            width: 60,
            render: (_, record) => {
                return record?.isShowDelete ?
                    <Popconfirm
                        title={'确认删除关联？'}
                        onConfirm={() => {
                            console.log('record', record);
                            setNoSelect(true)
                            deleteAssociation(record)
                        }}
                    >
                        <a >删除关联</a>
                    </Popconfirm> : ''
            }
        }
        // {
        //     title: '服务区',
        //     dataIndex: 'SERVERPART_NAME',
        //     hideInSearch: true
        // },
        // {
        //     title: '经营状态',
        //     dataIndex: 'BUSINESS_STATE',
        //     valueType: 'select',
        //     hideInSearch: false,
        //     valueEnum: {
        //         3000: { text: '关闭', status: 'error' },
        //         2000: { text: '暂停', status: 'warning' },
        //         1000: { text: '运营中', status: 'processing' },
        //         1010: { text: '待运营', status: 'default' }
        //     }
        // },
    ]
    // 选中的行
    const [selectedModalOrderRowKeys, setSelectedModalOrderRowKeys] = useState<any>()
    // 选中的行数据
    const [selectModalRowList, setSelectModalRowList] = useState<any>()
    // 表格的状态
    const [tableStatue, setTableStateue] = useState<any>(0)

    const modalRowSelection: any = {
        defaultSelectedRowKeys: noSelect ? [] : defaultId ? [`${defaultId}`] : [],
        selectedRowKeys: selectedModalOrderRowKeys,
        preserveSelectedRowKeys: true,
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            console.log('defaultId', defaultId);
            console.log('selectedRowKeys', selectedRowKeys);
            console.log('selectedRows', selectedRows);
            if (selectedRows && selectedRows.length > 0) {
                // 门店状态不是正常的
                let shopStateNoNormalList: any = []
                let shopStateNoNormalRowList: any = []
                // 门店状态是正常的
                let shopIsNormalList: any = []
                let shopIsNormalRowList: any = []

                selectedRows.forEach((item: any) => {
                    if (item.BUSINESS_STATE === 1000) {
                        shopIsNormalList.push(item)
                        shopIsNormalRowList.push(`${item?.PROPERTYASSETS_CODE}-${item?.SERVERPARTSHOP_ID}`)
                    } else {
                        shopStateNoNormalList.push(item)
                        shopStateNoNormalRowList.push(`${item?.PROPERTYASSETS_CODE}-${item?.SERVERPARTSHOP_ID}`)
                    }
                })

                // 实际保留的这一次点击的新的 1000的数据
                let realNormalList: any = []
                let realNormalRowList: any = []

                // 如果当前的点击行里面 1000的数量大于1 那么就要去掉之前的 留下新点击的
                if (shopIsNormalList && shopIsNormalList.length > 1) {
                    shopIsNormalList.forEach((item: any) => {
                        if (`${item?.PROPERTYASSETS_CODE}-${item?.SERVERPARTSHOP_ID}` === selectedRowKeys[selectedRowKeys.length - 1]) {
                            realNormalList.push(item)
                            realNormalRowList.push(`${item?.PROPERTYASSETS_CODE}-${item?.SERVERPARTSHOP_ID}`)
                        }
                    })
                } else {
                    realNormalList = shopIsNormalList
                    realNormalRowList = shopIsNormalRowList
                }

                setSelectModalRowList([...realNormalList, ...shopStateNoNormalList])
                setSelectedModalOrderRowKeys([...realNormalRowList, ...shopStateNoNormalRowList])
            } else {
                setSelectModalRowList(selectedRows)
                setSelectedModalOrderRowKeys(selectedRowKeys)
            }
        },
        getCheckboxProps: (record: any) => ({
            disabled: record.disable,
        }),
    };

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

    const handleReloadTable = () => {
        actionRef.current?.reload()
    }


    const deleteAssociation = async (obj: any) => {
        const req: any = {
            Id: obj?.PROPERTYASSETS_ID,
            ShopId: obj?.SERVERPARTSHOP_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)
            setSelectModalRowList([])
            setSelectedModalOrderRowKeys([])
            actionRef.current?.reload()
            if (parentRef) {
                parentRef.current?.reload()
            }
        } else {
            message.error(data.Result_Desc)
        }
    }



    return (
        <div>
            <div style={{ width: '100%', boxSizing: 'border-box', paddingLeft: '24px', marginBottom: '16px' }}>
                <Radio.Group onChange={(e: any) => {
                    setTableStateue(Number(e.target.value))
                    actionRef.current?.reload()
                }} value={tableStatue}>
                    <Radio value={0}>全部</Radio>
                    <Radio value={1000}>
                        <span style={{ margin: '0 4px' }} className="ant-badge-status-dot ant-badge-status-processing"></span>
                        正常
                    </Radio>
                    <Radio value={1010}>
                        <span style={{ margin: '0 4px' }} className="ant-badge-status-dot ant-badge-status-default"></span>
                        待运营
                    </Radio>
                    <Radio value={2000}>
                        <span style={{ margin: '0 4px' }} className="ant-badge-status-dot ant-badge-status-warning"></span>
                        暂停
                    </Radio>
                    <Radio value={3000}>
                        <span style={{ margin: '0 4px' }} className="ant-badge-status-dot ant-badge-status-error"></span>
                        关闭
                    </Radio>
                </Radio.Group>
            </div>


            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                className="relateShopTable"
                search={false}
                style={{ marginTop: '4px' }}
                rowKey={(record) => {
                    return `${record?.PROPERTYASSETS_CODE}-${record?.SERVERPARTSHOP_ID}`
                }}
                options={false}
                scroll={{ y: 630 }}
                pagination={false}
                request={async (params: any) => {
                    let req: any = {}
                    let formRes = detailFormRef.current?.getFieldsValue()
                    let nowShopRegion: any = '' // 当前的方位
                    // 先判断是新增还是编辑 这样取数据不同的
                    if (currentRow?.PROPERTYASSETS_ID) {
                        req = {
                            SearchParameter: {
                                SERVERPART_IDS: currentRow?.SERVERPART_ID,
                                ISVALID: 1,
                                BUSINESS_STATE: tableStatue ? tableStatue : '',
                                SHOPREGION: currentRow?.PROPERTYASSETS_REGION
                            },
                            SortStr: 'BUSINESS_STATE,SHOPTRADE,SHOPSHORTNAME,SHOPREGION',
                            PageIndex: 1,
                            PageSize: 999999
                        }
                        nowShopRegion = currentRow?.PROPERTYASSETS_REGION
                    } else {
                        // 没有服务区就不查了
                        if (!formRes?.SERVERPART_ID) {
                            return { data: [], success: true }
                        }
                        req = {
                            SearchParameter: {
                                SERVERPART_IDS: formRes?.SERVERPART_ID,
                                ISVALID: 1,
                                BUSINESS_STATE: tableStatue ? tableStatue : '',
                                SHOPREGION: formRes?.PROPERTYASSETS_REGION,
                            },
                            SortStr: 'BUSINESS_STATE,SHOPTRADE,SHOPSHORTNAME,SHOPREGION',
                            PageIndex: 1,
                            PageSize: 999999
                        }
                        nowShopRegion = formRes?.PROPERTYASSETS_REGION
                    }
                    // 现在要门店拼上资产内码
                    let data = await handleGetServerpartShopList(req)
                    const secondReq: any = {
                        SearchParameter: {
                            SERVERPART_IDS: formRes?.SERVERPART_ID,
                            // PROPERTYASSETS_REGION: formRes?.PROPERTYASSETS_REGION,
                            PROPERTYASSETS_STATE: 1
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    }
                    const secondData = await handleGetProvinceVehicleDetail(secondReq)
                    console.log('门店数据', data);

                    console.log('资产数据', secondData);

                    // 拿到相同方位 且有资产的门店
                    // 和其他方位 的全部资产数据
                    let sameShopList: any = []
                    let otherShopList: any = []
                    // 拿到同方位 有资产 但没门店的数据
                    let sameNoShopList: any = []

                    console.log('nowShopRegion', nowShopRegion);
                    if (secondData && secondData.length > 0) {
                        secondData.forEach((item: any) => {
                            if (item.BUSINESS_STATE === tableStatue || !tableStatue) {
                                if (nowShopRegion === item.PROPERTYASSETS_REGION) {
                                    sameShopList.push(item)
                                } else {
                                    otherShopList.push(item)
                                }

                                if (item.PROPERTYASSETS_CODE && !item.SERVERPARTSHOP_ID) {
                                    item.disable = true
                                    sameNoShopList.push(item)
                                }
                            }
                        })

                    }
                    console.log('sameShopList', sameShopList);
                    console.log('otherShopList', otherShopList);

                    // 相同方位没有匹配上的数据
                    let sameOther: any = []

                    // 相同方位 且有资产的门店 把门店资产全部拼在 对应区的门店上面
                    // 给已经找到了门店的 做个标记 没有找到的全部列出来拼在后面
                    if (sameShopList && sameShopList.length > 0 && data && data.length > 0) {
                        sameShopList.forEach((item: any) => {
                            data.forEach((subItem: any) => {
                                if (Number(item.SERVERPARTSHOP_ID || 0) === Number(subItem.SERVERPARTSHOP_ID)) {
                                    subItem.PROPERTYASSETS_CODE = item.PROPERTYASSETS_CODE
                                    subItem.PROPERTYASSETS_ID = item.PROPERTYASSETS_ID
                                    item.haveCode = true
                                }
                            })
                        })
                        console.log('sameShopList2222', sameShopList);
                        console.log('data222', data);


                        sameShopList.forEach((item: any) => {
                            if (item.haveCode) {

                            } else {
                                item.disable = true
                                sameOther.push(item)
                            }
                        })
                    }

                    // 其他方位的内容不可选
                    if (otherShopList && otherShopList.length > 0) {
                        otherShopList.forEach((item: any) => {
                            item.disable = true
                        })
                    }

                    console.log('当前方位拼上的数据', data);
                    console.log('想通方位的其他数据', sameOther);
                    console.log('有资产 没门店 同方位', sameNoShopList);


                    console.log('其他方位的资产数据', otherShopList);

                    let res = [...data, ...sameOther]
                    // , ...otherShopList
                    // 编辑的时候可以出现可以出现删除关联
                    let result: any = []
                    let firstObj: any = {}

                    const historySelect = await handleGetPROPERTYSHOPList({
                        SearchParameter: {
                            PROPERTYASSETS_ID: currentRow?.PROPERTYASSETS_ID
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    })
                    // 外部绑定的
                    let outId: any = ''
                    if (historySelect && historySelect.length > 0) {
                        historySelect.forEach((item: any) => {
                            if (item.PROPERTYSHOP_STATE === 1) {
                                outId = item.SERVERPARTSHOP_ID
                            }
                        })
                    }

                    if (res && res.length > 0) {
                        res.forEach((item: any) => {
                            if (item.PROPERTYASSETS_CODE === currentRow?.PROPERTYASSETS_CODE && item.SERVERPARTSHOP_ID && item.SERVERPARTSHOP_ID === outId && currentRow?.PROPERTYASSETS_CODE) {
                                item.isShowDelete = true
                                firstObj = item
                            } else {
                                result.push(item)
                            }
                        })
                    }
                    if (firstObj && firstObj.PROPERTYASSETS_CODE) {
                        result.unshift(firstObj)
                    }
                    console.log('result', result);

                    return { data: result, success: true }
                }}
                rowSelection={{
                    type: 'radio',
                    ...modalRowSelection,
                }}
            />
        </div>
    )
}

export default connect(({ user, }: ConnectState) => ({
}))(relatedShop);
