/*
 * @Author: cclu 1106109051@qq.com
 * @Date: 2024-08-22 10:51:03
 * @LastEditors: cclu 1106109051@qq.com
 * @LastEditTime: 2024-08-22 18:38:19
 * @FilePath: \cloud-platform\src\pages\basicManage\businessMan\components\businessManDetailDrawer.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Col, Drawer, FormInstance, message, Popconfirm, Row } from "antd";
import ProForm, { ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect } from "@ant-design/pro-form";
import { useRef, useState } from "react";
import { handleDeleteAUTOTYPE, handleDeleteOWNERSERVERPART, handleDeleteOWNERSERVERPARTSHOP, handleGetBusinessManDetail, handleGetNestingOwnerUnitList } from "../service";
import { getFieldEnum } from "@/services/options";
import ProTable, { ActionType } from "@ant-design/pro-table";
import moment from 'moment'
import useRequest from "@ahooksjs/use-request";

type DetailProps = {
    showDetailDrawer: boolean
    currentRow: any
    setCurrentRow: any
    setShowDetailDrawer: any
    currentUser: any
    parentRef: any
}
const BusinessManDetailDrawer = ({ showDetailDrawer, currentRow, setCurrentRow, setShowDetailDrawer, currentUser, parentRef }: DetailProps) => {

    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();

    const { loading: treeLoading, data: treeViews } = useRequest(async () => {
        const data = await handleGetNestingOwnerUnitList({ ShowStatus: true })
        console.log('treeViews', data);

        return data
    })

    const [formDetail, setFormDetail] = useState<any>()
    // 上级类别的选择列表
    const [PIDSelectList, setPIDSelectList] = useState<any>()
    // 表格列表
    const [tableData, setTableData] = useState<any>()

    const columns: any = [
        {
            title: '经营范围',
            dataIndex: 'AUTOTYPE_NAME'
        },
        {
            title: '显示顺序',
            dataIndex: 'AUTOTYPE_INDEX'
        },
        {
            title: '所属公司',
            dataIndex: 'OWNERUNIT_NAME'
        },
        {
            title: '有效状态',
            dataIndex: 'AUTOTYPE_VALID',
            valueType: 'select',
            valueEnum: {
                1: "有效",
                0: "无效"
            }
        },
        {
            title: '操作',
            render: (_, record) => {
                return record?.ServerpartList && record?.ServerpartList.length > 0 ? '' : record?.AUTOTYPE_VALID === 0 ? '' : <Popconfirm title={`确认删除？`} onConfirm={async () => {
                    console.log('record', record);
                    const data = await handleDeleteAUTOTYPE({ AUTOTYPEId: record?.AUTOTYPE_ID })
                    if (data.Result_Code === 100) {
                        message.success(data.Result_Desc)
                        handleGetReload()
                    } else {
                        message.error(data.Result_Desc)
                    }
                }}
                >
                    <a>删除</a>
                </Popconfirm>
            }
        }
    ]

    const handleGetThirdColumns = (record?: any) => {
        const columns: any = [
            {
                title: '门店名称',
                dataIndex: 'SHOPNAME'
            },
            {
                title: '门店编码',
                dataIndex: 'SHOPCODE'
            },
            {
                title: '所属公司',
                dataIndex: 'OWNERUNIT_NAME'
            },
            {
                title: '操作',
                render: (_, record) => {
                    return <Popconfirm title={`确认删除？`} onConfirm={async () => {
                        console.log('record', record);
                        const data = await handleDeleteOWNERSERVERPARTSHOP({ OWNERSERVERPARTSHOPId: record?.OWNERSERVERPARTSHOP_ID })
                        if (data.Result_Code === 100) {
                            message.success(data.Result_Desc)
                            handleGetReload()
                        } else {
                            message.error(data.Result_Desc)
                        }
                    }}
                    >
                        <a>删除</a>
                    </Popconfirm>
                }
            }
        ]
        return <ProTable
            columns={columns}
            pagination={false}
            rowKey={(record) => {
                return `${record?.OWNERSERVERPARTSHOP_ID}`
            }}
            dataSource={record?.ShopList}
            bordered
            search={false}
            options={false}
        />
    }

    const handleGetSecondColumns = (record?: any) => {
        console.log('record', record);
        const columns: any = [
            {
                title: '服务区名称',
                dataIndex: 'SERVERPART_NAME'
            },
            {
                title: '服务区编码',
                dataIndex: 'SERVERPART_CODE'
            },
            {
                title: '所属公司',
                dataIndex: 'OWNERUNIT_NAME'
            },
            {
                title: '操作',
                render: (_, record) => {
                    return record?.ShopList && record?.ShopList.length > 0 ? '' : <Popconfirm title={`确认删除？`} onConfirm={async () => {
                        console.log('record', record);
                        const data = await handleDeleteOWNERSERVERPART({ OWNERSERVERPARTId: record?.OWNERSERVERPART_ID })
                        if (data.Result_Code === 100) {
                            message.success(data.Result_Desc)
                            handleGetReload()
                        } else {
                            message.error(data.Result_Desc)
                        }
                    }}
                    >
                        <a>删除</a>
                    </Popconfirm>
                }
            }
        ]

        return <ProTable
            columns={columns}
            pagination={false}
            rowKey={(record) => {
                return `${record?.OWNERSERVERPART_ID}`
            }}
            dataSource={record?.ServerpartList}
            bordered
            search={false}
            options={false}
            expandable={{
                expandedRowRender: handleGetThirdColumns
            }}
        />
    }


    // 重新刷新下面的嵌套表数据
    const handleGetReload = async () => {
        const data = await handleGetBusinessManDetail({ BusinessManId: currentRow?.OWNERUNIT_ID })
        let obj: any = data.Result_Data
        setTableData(obj.OrganizationList)
    }

    return (
        <div>
            <Drawer
                width={'60%'}
                visible={showDetailDrawer}
                onClose={() => {
                    setCurrentRow(undefined);
                    setShowDetailDrawer(false);
                }}
                title={<span style={{ fontWeight: 600 }}>编辑经营范围</span>}
                bodyStyle={{ backgroundColor: "#fff", padding: 16 }}
                closable={false}
                destroyOnClose
            >

                <ProForm
                    formRef={formRef}
                    submitter={false}
                    request={async () => {
                        if (currentRow?.OWNERUNIT_ID) {
                            const data = await handleGetBusinessManDetail({ BusinessManId: currentRow?.OWNERUNIT_ID })
                            console.log('data312312', data);
                            let obj: any = data.Result_Data
                            // 原数据
                            obj.PROVINCE_CODE = obj.PROVINCE_CODE.toString()
                            obj.OWNERUNIT_NATURE = obj.OWNERUNIT_NATURE.toString()
                            obj.OPERATE_DATE = moment(obj.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss')
                            obj.OWNERUNIT_PID = Number(obj.OWNERUNIT_PID)
                            obj.OWNERUNIT_ID = Number(obj.OWNERUNIT_ID)
                            let serverPartNumber: any = 0
                            let serverPartShopNumber: any = []
                            setFormDetail(data.Result_Data)
                            console.log('obj', obj);

                            if (obj.OrganizationList && obj.OrganizationList.length > 0) {
                                setTableData(obj.OrganizationList)
                                let res: any = []
                                obj.OrganizationList.forEach((item: any) => {
                                    res.push({ label: item.AUTOTYPE_NAME, value: item.AUTOTYPE_ID })
                                    if (item.ServerpartList && item.ServerpartList.length > 0) {
                                        serverPartNumber += item.ServerpartList.length
                                        item.ServerpartList.forEach((subItem: any) => {
                                            if (subItem.ShopList && subItem.ShopList.length > 0) {
                                                subItem.ShopList.forEach((thirdItem: any) => {
                                                    if (serverPartShopNumber.indexOf(thirdItem.SERVERPARTSHOP_ID) === -1) {
                                                        serverPartShopNumber.push(thirdItem.SERVERPARTSHOP_ID)
                                                    }
                                                })
                                            }
                                        })
                                    }
                                })
                                setPIDSelectList(res)
                            } else {
                                setPIDSelectList([])
                                setTableData([])
                            }
                            obj.serverPartNumber = serverPartNumber
                            obj.serverPartShopNumber = serverPartShopNumber && serverPartShopNumber.length > 0 ? serverPartShopNumber.length : ''
                            return obj
                        }
                    }}
                >
                    <Row gutter={16}>
                        <Col span={8}>
                            <ProFormTreeSelect
                                label={"运营单位"}
                                name={"OWNERUNIT_ID"}
                                readonly
                                request={async () => {
                                    const data = await handleGetNestingOwnerUnitList({ ShowStatus: true })
                                    return data
                                }}
                                fieldProps={{
                                    fieldNames: {
                                        label: 'OWNERUNIT_NAME',
                                        value: 'OWNERUNIT_ID',
                                        children: 'children'
                                    },
                                    allowClear: true,
                                    showSearch: true,
                                    // treeData: treeViews 
                                }}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormSelect
                                label={"上级类别"}
                                name={"OWNERUNIT_PID"}
                                readonly
                                fieldProps={{
                                    options: treeViews,
                                    fieldNames: {
                                        label: 'OWNERUNIT_NAME',
                                        value: 'OWNERUNIT_ID'
                                    }
                                }}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormTreeSelect
                                label={"单位性质"}
                                name={"OWNERUNIT_NATURE"}
                                readonly
                                request={async () => {
                                    return await getFieldEnum({
                                        // 这里要手动添加枚举字段（从下面这些字典中选择一个）：服务区内码[ServerpartIds]
                                        FieldExplainField: 'OWNERUNIT_NATURE',
                                        notformate: true,
                                    });
                                }}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormSelect
                                name="PROVINCE_CODE"
                                label="所属省份"
                                readonly
                                request={async () => {
                                    return await getFieldEnum({
                                        FieldExplainField: 'PROVINCE_CODE',
                                        notformate: true,
                                    });
                                }}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"客户单位"}
                                name={"OWNERUNIT_NAME"}
                                readonly
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"客户简称"}
                                name={"OWNERUNIT_EN"}
                                readonly
                            />
                        </Col>

                        <Col span={8}>
                            <ProFormText
                                label={"经营服务区"}
                                readonly
                                name={"serverPartNumber"}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"经营门店"}
                                readonly
                                name={"serverPartShopNumber"}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"配置时间"}
                                readonly
                                name={"OPERATE_DATE"}
                            />
                        </Col>

                    </Row>

                </ProForm>


                <ProTable
                    actionRef={actionRef}
                    columns={columns}
                    pagination={false}
                    options={false}
                    search={false}
                    dataSource={tableData}
                    bordered
                    rowKey={(record) => {
                        return `${record?.AUTOTYPE_ID}`
                    }}
                    expandable={{
                        expandedRowRender: handleGetSecondColumns
                    }}
                />

            </Drawer>
        </div>
    )
}

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