var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { Modal, Form } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import { useState } from 'react';
import { dateFormatter, getStorage, useRoutes } from '@component/utils';
import { isEmpty, map, compact, isFunction, omit, reject, concat, find, } from 'lodash';
import { getPolicyList } from '../action';
import { useRequest } from 'ahooks';
import { getPolicyDetail } from '../action';
import { getIndustryList } from '../action';
import { getServiceApply } from '../action';
const POLICYSTATUS = [
    { key: 2, value: '已生效' },
    { key: 262, value: '录入中' },
    { key: 263, value: '待核保' },
    { key: 264, value: '核保中' },
    { key: 265, value: '核保退回' },
    { key: 266, value: '待缴费' },
    { key: 268, value: '放弃' },
    { key: 269, value: '作废' },
    { key: 270, value: '拒保' },
    { key: 275, value: '已注销' },
    { key: 280, value: '已缴费保单生成中' },
    { key: 281, value: '已锁定' },
    { key: 3, value: '批改临时删除' },
    { key: 4, value: '核保通过' },
    { key: 5, value: '已注销' },
];
const columns = [
    {
        title: '保单号',
        dataIndex: 'policyNumber',
        fieldProps: {
            placeholder: '保单号/被保人',
        },
        formItemProps: { label: '关键字', name: 'keyword' },
    },
    {
        title: '被保人',
        dataIndex: 'customerName',
        search: false,
    },
    {
        title: '管理分类',
        dataIndex: 'typePname',
        fieldProps: {
            placeholder: '',
        },
        request: getIndustryList,
        formItemProps: {
            name: 'typePid',
        },
        render: (_, record) => _jsx("span", { children: record.typePname }),
    },
    {
        title: '保单状态',
        dataIndex: 'policyStatus',
        valueType: 'select',
        valueEnum: {
            2: '已生效',
            4: '核保通过',
        },
        render: (_, { policyStatus }) => {
            for (const item of POLICYSTATUS) {
                if (item.key == policyStatus) {
                    return item.value;
                }
            }
            return '-';
        },
    },
    {
        title: '起保日期',
        dataIndex: 'startDate',
        renderText: dateFormatter,
        search: false,
    },
    {
        title: '终保日期',
        dataIndex: 'doneDate',
        renderText: dateFormatter,
        search: false,
    },
    {
        title: '归属经办人',
        dataIndex: 'belongToHandlerUserName',
        search: false,
        render: (_, record) => compact([
            record.belongToHandlerCode,
            record.belongToHandlerUserName,
        ]).join(','),
    },
    {
        title: '归属机构',
        dataIndex: 'insuranceName',
        search: false,
    },
    {
        title: '共保机构',
        dataIndex: 'coInsureName',
        fieldProps: { placeholder: '请输入共保机构名称' },
        hideInTable: true,
    },
];
export default function SelectedPolicy({ children, name = 'serviceObject', onConfirm, rowSelectionType = 'radio', serviceClassifyType, disabled, }) {
    const { paramsParse } = useRoutes();
    const form = Form.useFormInstance();
    const selectedRef = useRef([]);
    const [visible, setVisible] = useState(false);
    const [selectedRowOptions, setSelectedRowOptions] = useState([]);
    function f({ array = [] }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (isEmpty(array)) {
                return [];
            }
            return Promise.all(array.map((item) => getPolicyDetail({ policyId: item })));
        });
    }
    useRequest(f, {
        manual: !(paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.policyId),
        defaultParams: {
            array: (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.policyId) ? paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.policyId.split(',') : [],
        },
        onSuccess(data) {
            if (!isEmpty(data)) {
                if (serviceClassifyType == 'jizhongfuwu') {
                    selectedRef.current = data;
                }
                else {
                    setSelectedRowOptions(data);
                }
                onConfirm && onConfirm(data);
            }
            else {
                return null;
            }
        },
    });
    useRequest(getServiceApply, {
        manual: !(paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.id),
        defaultParams: {
            serviceApplyId: paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.id,
        },
        onSuccess(result) {
            if (!isEmpty(result === null || result === void 0 ? void 0 : result.data)) {
                if (serviceClassifyType == 'jizhongfuwu') {
                    selectedRef.current = result.data;
                }
                else {
                    setSelectedRowOptions(result.data);
                }
                onConfirm && onConfirm(result.data);
            }
            else {
                return null;
            }
        },
    });
    //重新提交
    const { run } = useRequest(getServiceApply, {
        manual: true,
        onSuccess({ data }) {
            if (data) {
                data = data.map((item) => (Object.assign(Object.assign({}, item), { contactsPhone: item === null || item === void 0 ? void 0 : item.phone, customerName: item === null || item === void 0 ? void 0 : item.serviceObjectName })));
                if (serviceClassifyType == 'jizhongfuwu') {
                    selectedRef.current = data;
                }
                else {
                    setSelectedRowOptions(data);
                }
                onConfirm && onConfirm(data);
            }
            return [];
        },
    });
    useEffect(() => {
        var _a;
        if (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.reSubmit)
            run({
                serviceApplyId: (_a = JSON.parse(paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.reSubmit)) === null || _a === void 0 ? void 0 : _a.serviceApplyId,
            });
    }, []);
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRowOptions) => {
            setSelectedRowOptions(selectedRowOptions);
        },
        selectedRowKeys: map(selectedRowOptions, 'policyId'),
        preserveSelectedRowKeys: true,
    };
    function onCancel() {
        if (serviceClassifyType == 'jizhongfuwu') {
            setSelectedRowOptions([]);
        }
        else {
            setSelectedRowOptions(form.getFieldValue(name));
        }
        setVisible(false);
    }
    function onOpen() {
        setVisible(true);
    }
    function onOk() {
        if (!isEmpty(selectedRowOptions)) {
            if (serviceClassifyType == 'jizhongfuwu') {
                selectedRef.current = concat(selectedRef.current, selectedRowOptions);
                onConfirm && onConfirm(selectedRef.current);
            }
            else {
                onConfirm && onConfirm(selectedRowOptions);
            }
        }
        onCancel();
    }
    function handleSelectedCallback(selectedRowOptions) {
        if (serviceClassifyType == 'jizhongfuwu') {
            selectedRef.current = selectedRowOptions;
        }
        else {
            setSelectedRowOptions(selectedRowOptions);
        }
    }
    useEffect(() => {
        if (!disabled) {
            setSelectedRowOptions([]);
            form.setFieldValue(name, []);
            selectedRef.current = [];
        }
    }, [serviceClassifyType]);
    function getAllPolicyList(params) {
        const selectedRowOptions = selectedRef.current;
        return getPolicyList(omit(params, ['selectedRowOptions'])).then((data) => {
            if (isEmpty(selectedRowOptions) || serviceClassifyType != 'jizhongfuwu') {
                return data;
            }
            else {
                const result = reject(data.data, (item) => find(selectedRowOptions, ['policyId', item.policyId]));
                return {
                    success: true,
                    data: result,
                    total: (result === null || result === void 0 ? void 0 : result.length) || 0,
                };
            }
        });
    }
    return (_jsxs(_Fragment, { children: [isFunction(children)
                ? children({
                    handleOpen: onOpen,
                    setSelectedRowOptions: handleSelectedCallback,
                })
                : children, visible && (_jsx(Modal, Object.assign({ onCancel: onCancel, onOk: onOk, width: "70%", title: "\u9009\u62E9\u4FDD\u5355", open: visible, bodyStyle: {
                    padding: 16,
                } }, { children: _jsx(ProTable, { cardProps: {
                        bodyStyle: {
                            padding: '10px 0',
                        },
                    }, rowKey: "policyId", options: false, columns: columns, request: (params) => getAllPolicyList(Object.assign(Object.assign({ selectedRowOptions: selectedRowOptions }, params), { insuranceId: getStorage('organId') })), rowSelection: Object.assign({ type: rowSelectionType }, rowSelection), size: "small", pagination: {
                        pageSize: 5,
                        showSizeChanger: false,
                    } }) })))] }));
}