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, Fragment as _Fragment } from "react/jsx-runtime";
import { ProForm, ProFormDatePicker, ProFormItem, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import React, { useRef, useState, useEffect } from "react";
import { Button, Col, Divider, message, Modal } from "antd";
import { useRequest } from "ahooks";
import { getAqServiceStandard, getPriceListByOrgan, getServiceType, onCreate, getDetail, editServiceApply, saveServiceApply } from "./action";
import { jsonString, logoutOut, setToken } from "@component/utils";
import SelectedPolicy from "./selected.policy";
import SelectedAddress from "./selected.address";
import { compact, isEmpty, pick, pickBy } from "lodash";
import moment from "moment";
import { CardForm, FormUpload, GridForm, ReactRouterPrompt } from "@component/ui";
import { getUploadList, themeMessage, useRoutes, setStorage } from "@component/utils";
import { getUserInfo } from 'userContext';
import Multiplex from "./multiplex";
export default function Form({ disabled }) {
    const formRef = useRef(null);
    const { paramsParse, historyBack } = useRoutes();
    const [isLeave, setLeave] = useState(true);
    let [flag, setFlag] = useState(true);
    const { runAsync } = useRequest(onCreate, {
        manual: true,
        onSuccess(result) {
            themeMessage(result, historyBack);
        },
        onError(result) {
            message.error(result.message);
        }
    });
    const { run, runAsync: editRun } = useRequest(editServiceApply, {
        manual: true,
        onSuccess(result) {
            themeMessage(result, historyBack);
        },
        onError(result) {
            message.error(result.message);
        },
    });
    const { runAsync: saveRun } = useRequest(saveServiceApply, {
        manual: true,
        onSuccess(result) {
            themeMessage(result, historyBack);
        },
        onError(result) {
            message.error(result.message);
        },
    });
    useEffect(() => {
        if (paramsParse.token) {
            setToken(paramsParse.token);
        }
    }, [paramsParse]);
    useRequest(getUserInfo, {
        onSuccess({ userInfo, menu }) {
            if (userInfo) {
                setStorage(userInfo);
            }
        },
        onError(ERROR) {
            console.log(ERROR, 'ERROR');
            logoutOut(navigate, 'logoutOut');
        },
    });
    function getValues(values) {
        var _a, _b;
        const params = pick(values, ['form']);
        if (values.serviceId) {
            params.serviceId = values.serviceId;
        }
        if (values.remark) {
            params.remark = values.remark;
        }
        if (values.servicePrice) {
            params.servicePrice = values.servicePrice;
        }
        if (values.serviceSchemeId) {
            params.serviceSchemeId = values.serviceSchemeId.value;
            params.serviceSchemeName = values.serviceSchemeId.label;
        }
        if (values.serviceName) {
            params.serviceName =
                (values === null || values === void 0 ? void 0 : values.serviceName) && (values === null || values === void 0 ? void 0 : values.serviceName.replace(/[\<\>]/g, ''));
        }
        if (values.address) {
            params.geoLng = (_a = values.address) === null || _a === void 0 ? void 0 : _a.geoLng;
            params.geoLat = (_b = values.address) === null || _b === void 0 ? void 0 : _b.geoLat;
            params.address =
                values.address.address || values.address.label || values.address;
        }
        if (values.executedAt) {
            params.executedAt = moment(values.executedAt).format('YYYY-MM-DD HH:mm:ss');
            //params.executedAt = moment(values.executedAt).format('YYYY-MM-DD') + ' 00:00:00';
        }
        if (values.serviceTypeId) {
            params.serviceTypeId = values.serviceTypeId.value;
        }
        if (values.attachmentPath) {
            params.attachmentPath = JSON.stringify(getUploadList(values.attachmentPath));
        }
        if (values.serviceObject && !isEmpty(values.serviceObject)) {
            params.serviceObject = JSON.stringify(values.serviceObject.map((item) => {
                var _a, _b;
                return (Object.assign(Object.assign({}, pick(item, [
                    'policyId',
                    'policyNumber',
                    'contactsName',
                    'contactsPhone',
                    'belongToHandlerCode',
                    'belongToHandlerUserName',
                    'belongToHandlerNumber',
                    'email',
                ])), { belongToHandlerOrganId: item.insuranceId, belongToHandlerOrganName: item.insuranceName, typePid: (_a = item.type) === null || _a === void 0 ? void 0 : _a.value, typePname: (_b = item.type) === null || _b === void 0 ? void 0 : _b.label, serviceObjectId: item.customerId || (item === null || item === void 0 ? void 0 : item.serviceObjectId), serviceObjectName: item.customerName || (item === null || item === void 0 ? void 0 : item.serviceObjectName) }));
            }));
        }
        return params;
    }
    function onFinish(values) {
        return __awaiter(this, void 0, void 0, function* () {
            const params = getValues(values);
            Modal.confirm({
                content: '请确认是否提交?',
                onOk() {
                    return __awaiter(this, void 0, void 0, function* () {
                        setLeave(false);
                        return (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.applyStatus) == '2' ||
                            (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.applyStatus) == '-1'
                            ? editRun(Object.assign(Object.assign({}, params), { serviceApplyId: paramsParse.id }))
                            : runAsync(params);
                    });
                },
            });
        });
    }
    function onSave() {
        var _a;
        const values = formRef.current.getFieldsValue();
        const keys = Object.keys(pickBy(values, (item) => !isEmpty(item)));
        if (!formRef.current.isFieldsTouched(keys)) {
            message.warning('不能直接进行暂存操作', 3);
            return;
        }
        const params = getValues(values);
        if (values.aqServiceStandardCategory) {
            params.aqServiceId =
                (_a = values.aqServiceStandardCategory) === null || _a === void 0 ? void 0 : _a.value;
        }
        Modal.confirm({
            content: '请确认是否暂存?',
            onOk() {
                return __awaiter(this, void 0, void 0, function* () {
                    setLeave(false);
                    return (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.applyStatus) == '2' ||
                        (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.applyStatus) == '-1'
                        ? saveRun(Object.assign(Object.assign({}, params), { serviceApplyId: paramsParse.id }))
                        : saveRun(params);
                });
            },
        });
    }
    function handleChangeServiceType(option, form) {
        var _a;
        if ((option === null || option === void 0 ? void 0 : option.serviceClassifyType) !== "jizhongfuwu") {
            const customerName = ((_a = form.getFieldValue("serviceObject")[0]) === null || _a === void 0 ? void 0 : _a.customerName) || "";
            form.setFieldsValue({
                serviceName: (option === null || option === void 0 ? void 0 : option.label)
                    ? `${customerName}${(option === null || option === void 0 ? void 0 : option.label) || ""}`
                    : "",
                serviceObjectType: "1"
            });
        }
        else {
            form.setFieldsValue({
                serviceName: option === null || option === void 0 ? void 0 : option.label,
                serviceObjectType: "2"
            });
        }
    }
    const disabledDate = (current) => {
        return current && current.unix() < moment().unix();
    };
    function request() {
        return __awaiter(this, void 0, void 0, function* () {
            if (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.id) {
                return getDetail({ id: paramsParse.id }).then((data) => __awaiter(this, void 0, void 0, function* () {
                    return {
                        serviceId: data.serviceProjectId,
                        attachmentPath: data.attachmentPath
                            ? yield jsonString(data.attachmentPath)
                            : null,
                        executedAt: data.estimatedServiceAt
                            ? moment(data.estimatedServiceAt)
                            : undefined,
                        remark: data.remark,
                        servicePrice: data.servicePrice,
                        serviceName: data.serviceProjectName,
                        form: data.form ? String(data.form) : '2',
                        aqServiceStandardCategory: {
                            value: data.aqServiceId,
                            label: data.aqServiceName,
                        },
                        serviceTypeId: !isEmpty(compact([
                            data === null || data === void 0 ? void 0 : data.serviceTypeId,
                            data === null || data === void 0 ? void 0 : data.serviceTypeName,
                            data === null || data === void 0 ? void 0 : data.serviceClassifyType,
                        ]))
                            ? {
                                value: data === null || data === void 0 ? void 0 : data.serviceTypeId,
                                label: data === null || data === void 0 ? void 0 : data.serviceTypeName,
                                serviceClassifyType: data === null || data === void 0 ? void 0 : data.serviceClassifyType,
                            }
                            : null,
                        serviceSchemeId: !isEmpty(compact([data === null || data === void 0 ? void 0 : data.serviceSchemeId, data === null || data === void 0 ? void 0 : data.serviceSchemeName]))
                            ? {
                                value: data === null || data === void 0 ? void 0 : data.serviceSchemeId,
                                label: data === null || data === void 0 ? void 0 : data.serviceSchemeName,
                            }
                            : null,
                        address: !isEmpty(data === null || data === void 0 ? void 0 : data.address) || !isEmpty(data === null || data === void 0 ? void 0 : data.serviceAddress)
                            ? {
                                value: data === null || data === void 0 ? void 0 : data.serviceAddress,
                                label: data === null || data === void 0 ? void 0 : data.serviceAddress,
                                address: data === null || data === void 0 ? void 0 : data.address,
                                geoLat: data === null || data === void 0 ? void 0 : data.serviceAddressLat,
                                geoLng: data === null || data === void 0 ? void 0 : data.serviceAddressLng,
                            }
                            : null,
                    };
                }));
            }
            const data = {
                form: '2',
            };
            if (!isEmpty(compact([
                paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.aqServiceId,
                paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.aqServiceName,
            ]))) {
                data.aqServiceStandardCategory = {
                    value: paramsParse.aqServiceId,
                    label: paramsParse.aqServiceName,
                };
            }
            if (!isEmpty(compact([
                paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceTypeId,
                paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceTypeName,
                paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceClassifyType,
            ]))) {
                data.serviceTypeId = {
                    value: paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceTypeId,
                    label: paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceTypeName,
                    serviceClassifyType: paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceClassifyType,
                };
            }
            if (!isEmpty(compact([paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceName, paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceObjectType]))) {
                data.serviceName = paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.serviceName;
                data.serviceObjectType = paramsParse.serviceObjectType;
            }
            return data;
        });
    }
    return (_jsx("div", { children: _jsxs(GridForm, Object.assign({ request: request, formRef: formRef, onFinish: onFinish, renderAction: () => {
                return (_jsxs(_Fragment, { children: [_jsx(Multiplex, { form: formRef }), _jsx(Button, Object.assign({ type: "primary", ghost: true, onClick: onSave }, { children: "\u6682\u5B58" }))] }));
            }, submitter: {
                searchConfig: {
                    submitText: (paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.applyStatus) == '2' ? '重新提交' : '提交',
                },
            } }, { children: [_jsx(ReactRouterPrompt, { when: isLeave }), _jsxs(CardForm, { children: [_jsx(ProFormItem, { name: "serviceId", hidden: true }), _jsx(ProForm.Item, Object.assign({ noStyle: true, shouldUpdate: true }, { children: (form) => {
                                return (_jsx(ProFormSelect, { name: "aqServiceStandardCategory", label: "\u6807\u51C6\u5206\u7C7B", request: getAqServiceStandard, placeholder: "\u8BF7\u9009\u62E9\u6807\u51C6\u5206\u7C7B", rules: [{ required: true }], fieldProps: {
                                        labelInValue: true,
                                        onChange: (_, o) => {
                                            form.setFieldsValue({
                                                serviceTypeId: undefined
                                            });
                                            handleChangeServiceType(o, form);
                                        }
                                    } }));
                            } })), _jsx(ProForm.Item, Object.assign({ noStyle: true, shouldUpdate: true }, { children: (form) => {
                                var _a;
                                return (_jsx(ProFormSelect, { name: "serviceTypeId", label: "\u670D\u52A1\u6D3B\u52A8", params: {
                                        aqServiceId: (_a = form.getFieldValue("aqServiceStandardCategory")) === null || _a === void 0 ? void 0 : _a.value
                                    }, request: getServiceType, placeholder: "\u8BF7\u9009\u62E9\u670D\u52A1\u6D3B\u52A8", rules: [{ required: true }], fieldProps: {
                                        labelInValue: true
                                    } }));
                            } })), _jsx(Col, Object.assign({ span: 24 }, { children: _jsx(SelectedPolicy, { disabled: disabled, flag: flag, setFlag: setFlag }) })), _jsx(ProFormText, { name: "serviceName", label: "\u9879\u76EE\u540D\u79F0", rules: [{ required: true }], placeholder: "\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0" }), _jsx(SelectedAddress, {}), _jsx(ProForm.Item, Object.assign({ noStyle: true, shouldUpdate: true }, { children: (form) => {
                                var _a, _b;
                                return (_jsx(ProFormSelect, { name: "serviceSchemeId", label: "\u4EF7\u683C\u65B9\u6848", params: {
                                        serviceTypeId: (_a = form.getFieldValue("serviceTypeId")) === null || _a === void 0 ? void 0 : _a.value,
                                        aqServiceId: (_b = form.getFieldValue("aqServiceStandardCategory")) === null || _b === void 0 ? void 0 : _b.value
                                    }, request: getPriceListByOrgan, placeholder: "\u8BF7\u9009\u62E9\u670D\u52A1\u8BA1\u8D39\u65B9\u6848", fieldProps: {
                                        labelInValue: true,
                                        onChange: (value, options) => {
                                            form.setFieldValue("servicePrice", options.servicePrice);
                                        }
                                    } }));
                            } })), _jsx(ProFormText, { name: "servicePrice", label: "\u670D\u52A1\u4EF7\u683C(\u5143)", rules: [{ required: true }], placeholder: "\u8BF7\u8F93\u5165\u9879\u670D\u52A1\u4EF7\u683C" }), _jsx(ProFormRadio.Group, { label: "\u670D\u52A1\u6A21\u5F0F", name: "form", rules: [{ required: true }], options: [
                                {
                                    value: "1",
                                    label: "线上"
                                },
                                {
                                    value: "2",
                                    label: "线下"
                                }
                            ] }), _jsx(ProFormDatePicker, { label: "\u671F\u671B\u670D\u52A1\u65F6\u95F4", name: "executedAt", fieldProps: {
                                // format: (value) => value.format('YYYY-MM-DD'),
                                style: {
                                    width: "100%"
                                },
                                disabledDate: disabledDate
                            }, placeholder: "\u8BF7\u9009\u62E9\u671F\u671B\u670D\u52A1\u65F6\u95F4", rules: [{ required: true }] }), _jsx(ProFormTextArea, { labelCol: {
                                span: 3
                            }, colProps: {
                                span: 24
                            }, name: "remark", label: "\u5907\u6CE8", placeholder: "\u8BF7\u8F93\u5165\u5907\u6CE8", fieldProps: {
                                maxLength: 500,
                                showCount: true
                            } })] }), _jsx(Divider, { className: "self-pro-divider-form" }), _jsx(CardForm, Object.assign({ title: "\u76F8\u5173\u9644\u4EF6" }, { children: _jsx(FormUpload, { max: 20, label: "\u9644\u4EF6", name: "attachmentPath", formItemProps: {
                            extra: "最多上传20个附件,(支持格式:jpg,png,jpeg,pdf,word,Excel)"
                        }, params: {
                            type: "7",
                            bizNo: paramsParse === null || paramsParse === void 0 ? void 0 : paramsParse.id
                        }, fieldProps: {
                            accept: "image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                        } }) }))] })) }));
}