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, jsxs as _jsxs } from "react/jsx-runtime";
import { PageContainer } from '@ant-design/pro-components';
import React, { useRef, useState } from 'react';
import { Button, Divider, message, Modal } from 'antd';
import { useRequest } from 'ahooks';
import { getStorage, getUploadList, jsonString, themeMessage, useRoutes, } from '@component/utils';
import { saveReport, submitReport, getServiceDetail } from './action';
import { omit, map, isEmpty } from 'lodash';
import moment from 'moment';
import { CardForm, FormUpload, GridForm, ReactRouterPrompt, } from '@component/ui';
import Base from './base.form';
import HiddenInformation from './hidden.information';
import RiskControl from './risk.control';
import { Context } from './context';
export default function (props) {
    return (_jsx(PageContainer, Object.assign({ header: {
            title: null,
        } }, { children: _jsx("div", Object.assign({ className: "page-content-detail" }, { children: _jsx(ExpertReportForm, Object.assign({}, props)) })) })));
}
export function ExpertReportForm({ type, poltform, reSubmit }) {
    const { paramsParse, historyBack } = useRoutes();
    const { serviceId = null } = paramsParse;
    const formRef = useRef(null);
    const [isLeave, setLeave] = useState(serviceId ? false : true);
    const [riskIds, setRiskIds] = useState([]);
    const [hiddenIds, setHiddenIds] = useState([]);
    const readonly = serviceId && type == 'detail';
    const { runAsync: runSubmit } = useRequest(submitReport, {
        manual: true,
        onSuccess(result) {
            themeMessage(result, historyBack);
        },
        onError(result) {
            message.error(result.message);
        },
    });
    const { runAsync: runSave } = useRequest(saveReport, {
        manual: true,
        onSuccess(result) {
            themeMessage(result, historyBack, '补录报告保存成功!');
        },
        onError(result) {
            message.error(result.message);
        },
    });
    function onSave() {
        return __awaiter(this, void 0, void 0, function* () {
            const values = formRef.current.getFieldsValue();
            if (Object.values(values).every(item => isEmpty(item))) {
                return message.error('请先填写信息!');
            }
            const params = formatParams(values);
            params.serviceId = serviceId;
            Modal.confirm({
                content: '确认是否保存?',
                onOk() {
                    return __awaiter(this, void 0, void 0, function* () {
                        setLeave(false);
                        return runSave(params);
                    });
                },
            });
        });
    }
    // 驳回后重新提交
    function onFinish(values) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = formatParams(values);
            params.serviceId = serviceId;
            Modal.confirm({
                content: '确认是否提交?',
                onOk() {
                    return __awaiter(this, void 0, void 0, function* () {
                        setLeave(false);
                        return runSubmit(params);
                    });
                },
            });
        });
    }
    function formatParams(values) {
        const params = Object.assign({}, values);
        if (poltform == 'expert') {
            params.userName = getStorage('userName');
            params.userId = getStorage('userId');
        }
        if (params === null || params === void 0 ? void 0 : params.aqServiceStandardCategory) {
            params.aqServiceId =
                params.aqServiceStandardCategory.value;
            params.aqServiceName =
                params.aqServiceStandardCategory.label;
        }
        params.riskIds = map(riskIds, (item) => item === null || item === void 0 ? void 0 : item.riskId).join(',');
        params.hiddenDangerIds = map(hiddenIds, (item) => item === null || item === void 0 ? void 0 : item.hiddenDangerId).join(',');
        if (values.organ && poltform == 'insure') {
            params.organId = values.organ.value;
            params.organName = values.organ.label;
        }
        if (values.serviceReportUrl) {
            params.serviceReportUrl = JSON.stringify(getUploadList(values.serviceReportUrl));
        }
        if (values.serviceResultsAtts) {
            params.serviceResultsAtts = JSON.stringify(getUploadList(values.serviceResultsAtts));
        }
        if (params.user) {
            params.userName = params.user.name || params.user.label;
            params.userId = params.user.value;
        }
        if (params.serviceStartAt) {
            params.serviceStartAt = moment(params.serviceStartAt).format('YYYY-MM-DD HH:mm:ss');
        }
        return omit(params, ['user', 'aqServiceStandardCategory', 'organ', 'serviceType']);
    }
    function request() {
        return getServiceDetail({ serviceId }).then((res) => __awaiter(this, void 0, void 0, function* () {
            return {
                policyNumber: res === null || res === void 0 ? void 0 : res.policyNumber,
                aqServiceStandardCategory: {
                    label: res === null || res === void 0 ? void 0 : res.aqServiceName,
                    value: res === null || res === void 0 ? void 0 : res.aqServiceId,
                },
                user: {
                    label: res === null || res === void 0 ? void 0 : res.userName,
                    value: res === null || res === void 0 ? void 0 : res.userId,
                },
                organ: {
                    label: res === null || res === void 0 ? void 0 : res.executedOrganName,
                    value: res === null || res === void 0 ? void 0 : res.executedOrganId
                },
                customerName: res === null || res === void 0 ? void 0 : res.customerName,
                address: res === null || res === void 0 ? void 0 : res.address,
                serviceStartAt: res === null || res === void 0 ? void 0 : res.serviceStartAt,
                remark: res === null || res === void 0 ? void 0 : res.remark,
                serviceContent: res === null || res === void 0 ? void 0 : res.serviceContent,
                serviceReportUrl: (yield jsonString(res === null || res === void 0 ? void 0 : res.serviceReportUrl)) || [],
                serviceResultsAtts: (yield jsonString(res === null || res === void 0 ? void 0 : res.serviceResultsAtts)) || [],
                actualServiceCost: res === null || res === void 0 ? void 0 : res.actualServiceCost
            };
        }));
    }
    return (_jsx(Context.Provider, Object.assign({ value: { poltform, type } }, { children: _jsxs(GridForm, Object.assign({ formRef: formRef, isExit: false, 
            /* 驳回后提交报告*/
            onFinish: onFinish, readonly: readonly, request: serviceId && request, initialValues: {
                form: '2',
            }, submitter: !readonly
                ? {
                    searchConfig: {
                        submitText: '提交报告',
                    },
                }
                : {
                    render() {
                        return null;
                    },
                }, renderAction: () => {
                // 驳回后提交报告
                if (reSubmit)
                    return null;
                return (!readonly && (_jsx(Button, Object.assign({ type: "primary", onClick: onSave }, { children: "\u4FDD\u5B58" }))));
            } }, { children: [_jsx(ReactRouterPrompt, { when: isLeave }), _jsx(Base, {}), _jsx(Divider, { className: "self-pro-divider-form" }), _jsx(RiskControl, { title: "\u98CE\u9669\u8BC4\u4F30\u53CA\u7BA1\u63A7", serviceId: serviceId, setRiskIds: setRiskIds, readonly: readonly, type: type }), _jsx(Divider, { className: "self-pro-divider-form" }), _jsx(HiddenInformation, { title: "\u73B0\u573A\u4E8B\u6545\u9690\u60A3\u4FE1\u606F", serviceId: serviceId, setHiddenIds: setHiddenIds, readonly: readonly, type: type }), _jsxs(CardForm, Object.assign({ title: "\u76F8\u5173\u9644\u4EF6" }, { children: [_jsx(FormUpload, { rules: [{ required: true }], name: "serviceReportUrl", label: "\u62A5\u544A\u5185\u5BB9\u6587\u4EF6", max: 1, fieldProps: {
                                accept: 'image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
                                multiple: false,
                            }, params: {
                                bizNo: serviceId ? serviceId : '',
                                type: '18',
                            } }), _jsx(FormUpload, { name: "serviceResultsAtts", label: "\u670D\u52A1\u76F8\u5173\u9644\u4EF6", max: 20, fieldProps: {
                                accept: 'image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
                            }, extra: '培训人员清单、设备安装清单', params: {
                                bizNo: serviceId ? serviceId : '',
                                type: '14',
                            } })] }))] })) })));
}