import {TableProMaxProps, TableProMaxSlots} from "@/types/components/table";
import {
    EnterprisesUnitPagerQueryParams,
    EnterprisesUnitPagerVo, EnterprisesUnitSaveOrUpdateParams,
    PoliceUnitPagerVo
} from "@/types/views/unitManage/police/policeUnit.ts";
import {ref} from "vue";
import {FormExpose} from "ant-design-vue/es/form/Form";
import {ComponentExposed} from "vue-component-type-helpers";
import MapContainer from "@/components/aMap/MapContainer.vue";
import {FormProMaxItemOptions} from "@/types/components/form";
import {dictSelectNodes} from "@/config/dict.ts";
import {AutoComplete, Button, Input, message, Modal, Space} from "ant-design-vue";
import api from "@/axios";
import TableProMax from "@/components/table/TableProMax.vue";
import {deleteDataModal} from "@/components/tsx/ModalPro.tsx";
import {PageParams} from "@/types/hooks/useTableProMax.ts";
import FormProMax from "@/components/form/FormProMax.vue";
import {debounce} from "lodash-es";

type _TableProps = TableProMaxProps<EnterprisesUnitPagerVo, EnterprisesUnitPagerQueryParams>;
type _FormType = EnterprisesUnitSaveOrUpdateParams & {
    contactPersonInfoName?: string;
    contactPersonInfoTelephone?: string
}
const saveOrUpdateEnterprisesUnit = (params: _FormType, callback: Function) => {
    const _formRef = ref<FormExpose>(null)
    const _mapRef = ref<ComponentExposed<typeof MapContainer>>(null)
    const _formParams = ref<_FormType>({...params})

    let city = '';
    const initMarker = (map: AMap.Map) => {
        //添加maker点 设置point
        const maker = new AMap.Marker({
            position: _formParams.value.point,
            draggable: true
        })
        maker.on("dragend", ({lnglat}) => {
            _formParams.value.point = lnglat
        })
        map.clearMap()
        map.add(maker)
        map.setFitView()
    }
    const autoAddress = ref<SelectNodeVo<string>[]>([])

    const _formOptions = ref<FormProMaxItemOptions<_FormType>>({
        name: {
            type: 'custom',
            label: '单位名称',
            required: true,
            customRender: () => {
                return <AutoComplete
                    v-model:value={_formParams.value.name}
                    options={autoAddress.value}
                    onSelect={(_, options: SelectNodeVo<string>) => {
                        _formParams.value.point = options.extData?.location;
                        _formParams.value.address = options.extData?.address;
                        initMarker(_mapRef.value?.mapInstance)
                    }}
                    onSearch={debounce((val: string) => {
                        //@ts-ignore
                        const auto = new AMap.AutoComplete({
                            city: city,
                            input: "tipinput",
                            citylimit: true
                        });
                        auto.search(val, (status, result) => {
                            if (status === 'complete') {
                                autoAddress.value = result.tips?.map(e => {
                                    return {
                                        value: e.name,
                                        label: e.name,
                                        extData: {
                                            district: e.district,
                                            address: e.address,
                                            location: e.location
                                        }
                                    } as SelectNodeVo<string>
                                })
                            } else {
                                autoAddress.value = [];
                            }
                        })
                    }, 300)}
                    v-slots={{
                        option: (item: SelectNodeVo<string>) => {
                            return <div>
                                <p>{item.label}</p>
                                <p style={{color: '#9a9c9d'}}>{item.extData?.district} {item.extData?.address}</p>
                            </div>
                        }
                    }}
                >
                    <Input
                        placeholder="请输入单位名称"
                    />
                </AutoComplete>
            }
        },
        type: {
            type: 'select',
            label: '单位类型',
            required: true,
            options: dictSelectNodes('EnterprisesUnitType')
        },
        administrativeDivisionCodes: {
            type: 'administrativeDivisionTree',
            label: '行政区划',
            required: true,
            componentsProps: {
                displayRender: ({labels}): string => {
                    city = labels[1]
                    return labels.join(' / ');
                }
            }
        },
        address: {
            type: 'inputTextArea',
            label: '详细地址',
        },
        map: {
            type: 'custom',
            label: '经纬度',
            customRender: () => <MapContainer
                ref={_mapRef}
                plugins={['AMap.AutoComplete']}
                style={{width: '100%', height: '300px', position: 'relative'}}
                initCallback={(map) => {
                    const contextMenu = new AMap.ContextMenu();
                    contextMenu.addItem('标记', () => {
                        const {lng, lat} = contextMenu.getPosition()
                        _formParams.value.point = [lng, lat]
                        initMarker(map)
                    }, 0)
                    map.on('rightclick', ({lnglat}) => {
                        contextMenu.open(map, lnglat)
                    })
                    if (_formParams.value.point) {
                        initMarker(map)
                    }
                }}
            >
            </MapContainer>
        },
        contactPersonInfoName: {
            type: 'input',
            label: '联系人名称'
        },
        contactPersonInfoTelephone: {
            type: 'input',
            label: '联系人电话'
        },
        remark: {
            type: 'inputTextArea',
            label: '备注'
        }
    })
    Modal.confirm({
        title: params.snowFlakeId ? `【${params.name}】 信息编辑` : '新增企事业单位',
        width: 600,
        icon: ' ',
        centered: true,
        content: () => <FormProMax
            ref={_formRef}
            v-model:value={_formParams.value}
            formItemOptions={_formOptions.value}/>,
        onOk: async () => {
            await _formRef.value?.validate()
            const resp = await api.post('/enterprisesUnit/saveOrUpdate', {
                ..._formParams.value,
                contactPersonInfo: {
                    name: _formParams.value.contactPersonInfoName,
                    telephone: _formParams.value.contactPersonInfoTelephone
                }
            })
            message.success(resp.message)
            callback && callback()
        }
    })
}

export const showEnterprisesUnit = (policeUnitPagerVo: PoliceUnitPagerVo) => {
    const _tableRef = ref<ComponentExposed<typeof TableProMax>>(null)
    const _columns: _TableProps['columns'] = [
        {
            dataIndex: 'name',
            title: '名称'
        }, {
            dataIndex: 'type',
            title: '类型',
            customRender: ({text}) => text?.label
        }, {
            dataIndex: 'contactPersonInfo',
            title: '联系人',
            ellipsis: true,
            customRender: ({text}) => text?.name + "/" + text.telephone
        }, {
            dataIndex: 'province',
            title: '行政区划',
            ellipsis: true,
            customRender: ({record}) => [record.provinceName, record.cityName, record.districtsName, record.streetName].filter(Boolean).join("/")
        }, {
            dataIndex: 'address',
            title: '详细地址',
            ellipsis: true
        }, {
            dataIndex: 'remark',
            title: '备注'
        }, {
            dataIndex: 'createTime',
            title: '创建时间'
        }, {
            dataIndex: 'opt',
            title: '操作',
            customRender: ({record}) => <Space>
                <Button
                    class="btn-warn"
                    onClick={() => saveOrUpdateEnterprisesUnit({
                        snowFlakeId: record.snowFlakeId,
                        policeUnitId: record.policeUnitId,
                        name: record.name,
                        type: record.type.value,
                        administrativeDivisionCodes: [record.province, record.city, record.districts, record.street].filter(Boolean),
                        address: record.address,
                        point: record.point,
                        contactPersonInfoName: record.contactPersonInfo?.name,
                        contactPersonInfoTelephone: record.contactPersonInfo?.telephone,
                        remark: record.remark
                    }, _tableRef.value?.requestGetTableData)}
                >编辑
                </Button>
                <Button class="btn-danger" onClick={() => deleteDataModal(record.name, async () => {
                    const resp = await api.delete('/enterprisesUnit/deleteById', {
                        enterprisesUnitId: record.snowFlakeId
                    })
                    message.success(resp.message)
                    await _tableRef.value?.requestGetTableData()
                })}>删除
                </Button>
            </Space>
        }
    ]
    const _reqApi: _TableProps["requestApi"] = (params) => {
        (params as PageParams<EnterprisesUnitPagerQueryParams>).params.policeUnitId = policeUnitPagerVo.snowFlakeId
        return api.post('/enterprisesUnit/pager', params)
    }
    Modal.info({
        title: `【${policeUnitPagerVo.name}】 管辖企事业单位`,
        width: '80%',
        centered: true,
        maskClosable: true,
        content: () => <TableProMax
            ref={_tableRef}
            size="small"
            columns={_columns}
            requestApi={_reqApi}
            searchFormOptions={{
                name: {
                    type: 'input',
                    label: '单位名称'
                }, address: {
                    type: 'input',
                    label: '地址'
                }, remark: {
                    type: 'input',
                    label: '备注'
                }
            }}
            v-slots={{
                tableHeader: (_) => {
                    return <Space>
                        <Button
                            class="btn-success"
                            onClick={() => saveOrUpdateEnterprisesUnit({
                                name: undefined,
                                type: 'party_government',
                                policeUnitId: policeUnitPagerVo.snowFlakeId,
                                administrativeDivisionCodes: [policeUnitPagerVo.province, policeUnitPagerVo.city, policeUnitPagerVo.districts, policeUnitPagerVo.street].filter(Boolean)
                            }, _tableRef.value?.requestGetTableData)}
                        >新增
                        </Button>
                        <Button disabled>导入</Button>
                    </Space>
                }
            } as TableProMaxSlots<PoliceUnitPagerVo>}
        />
    })
}
