/*
 * @Author: your name
 * @Date: 2022-03-14 11:17:12
 * @LastEditTime: 2022-04-28 15:36:45
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/articleManagement/components/articleDetailModule/drawer/multi.tsx
 */

import { ProFormSelect } from "@ant-design/pro-form";
import { Button, Col, Empty } from "antd";
import { useEffect, useState } from "react";
import { getDepartmentList } from "../../../../server";


export type DataItemType = {
    id: number;
    responsibilityDepartment: { label: string; value: number };
    responsibilityUser: { label: string; value: number };
    selectableUsers: { label: string; value: number }[];   //供可选的下拉列表
    loading?: boolean;
    open?: boolean;
    [key: string]: any
}

type PayloadType = {
    key?: number;
    label: string;
    value: number;
}

export type MultiResponsibilitySelecterValueType = {
    responsibilityDepartment: { label: string; value: number };
    responsibilityUser: { label: string; value: number };

}



const SelectFormItem = ({
    itemData, editable, options, editDataItem, onFocusHandle, loading, setDepartmentUsers, delhandle
}: {
    itemData: DataItemType;
    editable: boolean;
    options: PayloadType[];
    loading?: boolean;
    setDepartmentUsers: (editItemId: number, payload: any, currentEditItem?: DataItemType) => void;
    onFocusHandle: (id: number) => void;
    editDataItem: (id: number, payload: PayloadType) => void;
    delhandle: (id: number) => void;

}) => {
  
    return (
        <div style={{ display: 'flex', flexDirection: 'row' }}>
            <Col className="gutter-row" span={12}>
                <ProFormSelect
                    width='sm'
                    showSearch
                    placeholder="选择单位"
                    options={options}
                    fieldProps={{
                        labelInValue: true,
                        defaultValue: itemData.responsibilityDepartment,
                        onChange: (item, option) => {
                            editDataItem(itemData.id, item)
                        }
                    }}
                    rules={[{ required: true, message: '请选择单位！' }]}
                />
            </Col>
            <Col className="gutter-row" span={editable ? 8 : 10}>
                <ProFormSelect
                    width='sm'
                    // disabled={true}
                    // params={{}}
                    // request={()=>getSelecterTwoList(itemData.responsibilityDepartment.value)}

                    options={itemData.selectableUsers}
                    placeholder="选择负责人"
                    fieldProps={{
                        // open: itemData.open,
                        labelInValue: true,
                        value: itemData.responsibilityUser,
                        onFocus: () =>{onFocusHandle(itemData.id)} ,
                        loading: loading,
                        onChange: (item, option) => {
                            setDepartmentUsers(itemData.id, item)
                        }
                    }}
                    rules={[{ required: true, message: '请选择负责人！' }]}
                />
            </Col>
            {editable && <Col><Button onClick={() => delhandle(itemData.id)} style={{ fontSize: 14 }}>-</Button></Col>}
        </div>
    )
}


//多级责任人及单位设置
const MultiResponsibilitySelecter = ({
    rows = 0, options = [], value, onChange, editable = false
}: {
    rows: number;
    options: any[],
    editable?: boolean;
    value?: MultiResponsibilitySelecterValueType[],
    onChange?: (val: DataItemType[]) => void
}) => {

    const [data, setdata] = useState<DataItemType[] | []>([]);

    const [loading, setloading] = useState(false);

    const setDepartmentUsers = async (editItemId: number, payload: any, currentEditItem?: DataItemType) => {
        // 获取责任单位对应的责任人

        const index = data.findIndex(t => t.id == editItemId);

        if (!payload && currentEditItem) {
            const resp = await getDepartmentList({ responsibilityDepartmentId: currentEditItem.responsibilityDepartment?.value });

            if (resp) {

                const { list = [] } = resp;

                if (list.length > 0) {
                    const tempPeople = list[0].sysEmployeeVOList.map((item) => ({
                        label: item ? item.name : '-',
                        value: item ? item.id : 0,
                    }));

                    currentEditItem['responsibilityUser'] = tempPeople[0];

                    if (index >= 0) {
                        const _data = data;
                        _data.splice(index, 1, currentEditItem);
                        setdata([..._data]);
                    }

                }
            }

        } else {
            let a = data.filter((v: DataItemType) => v.id == editItemId);

            if (a[0]) {
                a[0]['responsibilityUser'] = payload;
                a[0]['open'] = false;
                const _data = data;
                _data.splice(index, 1, a[0]);
                setdata([..._data]);
            }
        }

    };

    const getSelecterTwoList = async (id: number) => {
        const resp = await getDepartmentList({ responsibilityDepartmentId: id });
        if (resp) {
            const { list = [] } = resp;
            if (list.length > 0) {
                const tempList = list[0].sysEmployeeVOList.map((item) => ({
                    label: item ? item.name : '-',
                    value: item ? item.id : Math.random(),
                }));
                return tempList;
            }
        }
        return [];
    }

    const onFocusHandle = async (id: number) => {
        //传入data id
        const index = data.findIndex(t => t.id == id);
        const _data = data;
        setloading(true);
        
        const selectableList = await getSelecterTwoList(data[index].responsibilityDepartment.value);
        _data[index].selectableUsers = selectableList;
        _data[index].open = true;
        
        setloading(false);
        
        setdata([..._data]);
    }

    const editDataItem = (id: number, payload: PayloadType) => {

        let currentEditItem = data.filter((v: DataItemType) => v.id == id);

        if (currentEditItem[0]) {

            currentEditItem[0]['responsibilityDepartment'] = payload;
            setDepartmentUsers(id, undefined, currentEditItem[0]);

        }

    }

    const delhandle = (id: number) => {
        const index = data.findIndex(t => t.id == id);
        const _data = data;
        _data.splice(index, 1);
        setdata([..._data]);
    }


    useEffect(() => {
        if (rows > 0) {
            setdata([
                ...data, {
                    id: Math.random(), responsibilityDepartment: { label: '-', value: -1 },
                    responsibilityUser: { label: '-', value: -1 }, selectableUsers: []
                }
            ])
        }
    }, [rows]);

    useEffect(() => {
        onChange && onChange(data);
    }, [data]);

    useEffect(() => {

        const _value = value?.map(v => {

            return {
                id: Math.random(),
                selectableUsers: [],
                ...v
            }
        });

        if (_value) {
            setdata(_value);
        }

    }, []);


    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            {
                data.length > 0 ? (
                    [...data].map((v, k) => {
                        return (
                            <SelectFormItem

                                onFocusHandle={onFocusHandle}
                                delhandle={delhandle}
                                editDataItem={editDataItem}
                                loading={loading}
                                key={k}
                                setDepartmentUsers={setDepartmentUsers}
                                options={options}
                                editable={editable}
                                itemData={v}
                            />
                        )
                    })
                ) : (
                    <div style={{ border: '1px solid #eee', height: 100, width: '91%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    </div>
                )

            }
        </div>
    )
}

export default MultiResponsibilitySelecter;