import { apiQueryShips } from '@/services/slave/sgw/ShipController'; import { apiCreateTrip, apiQueryLastTrips, } from '@/services/slave/sgw/TripController'; import { PlusOutlined } from '@ant-design/icons'; import type { ProFormInstance, SubmitterProps, } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormDatePicker, ProFormList, ProFormSelect, ProFormText, StepsForm, } from '@ant-design/pro-components'; import { FormattedMessage, useModel } from '@umijs/max'; import { Button, message, Table, Typography } from 'antd'; import dayjs from 'dayjs'; import utc from 'dayjs/plugin/utc'; import { useEffect, useRef, useState } from 'react'; dayjs.extend(utc); interface CreateTripProps { onSuccess?: (ok: boolean) => void; ship_id?: string; thing_id?: string; } interface TripFormValues { name: string; departure_time: any; // dayjs object or string departure_port_id: number; arrival_time?: any; // dayjs object or string arrival_port_id?: number; fishing_ground_codes?: number[]; fishing_gear?: SgwModel.FishingGear[]; trip_cost?: SgwModel.TripCost[]; ship_id?: string; } const CreateTrip: React.FC = ({ onSuccess, thing_id }) => { const [visible, setVisible] = useState(false); const [selectedThing, setSelectedThing] = useState(); const [ships, setShips] = useState([]); const [selectedShip, setSelectedShip] = useState( null, ); const [loading, setLoading] = useState(false); const [lastTrip, setLastTrip] = useState(null); const [initialFormValues, setInitialFormValues] = useState< Partial >({}); const formRef = useRef>(null); const { homeports, getHomeportsByProvinceCode } = useModel( 'slave.sgw.useHomePorts', ); useEffect(() => { getHomeportsByProvinceCode(); }, [getHomeportsByProvinceCode]); useEffect(() => { setSelectedThing(thing_id); }, [thing_id]); // Load danh sách tàu const loadShips = async () => { setLoading(true); try { const resp = await apiQueryShips({ offset: 0, limit: 100 }); setShips(resp.ships || []); } catch (error) { message.error('Không thể tải danh sách tàu'); } finally { setLoading(false); } }; useEffect(() => { if (visible) { loadShips(); } }, [visible]); // Auto-fill form when initialFormValues changes useEffect(() => { if (formRef.current && Object.keys(initialFormValues).length > 0) { console.log('� InitialFormValues:', initialFormValues); // Fill form after a short delay to ensure all steps are ready setTimeout(() => { if (formRef.current) { console.log('� Filling form with values...'); formRef.current.setFieldsValue(initialFormValues); } }, 100); } }, [initialFormValues]); // Load last trip when ship is selected const loadLastTrip = async (thingId: string) => { try { setLoading(true); const trip = await apiQueryLastTrips(thingId); setLastTrip(trip); // Prepare form values with last trip data if (trip) { console.log('📦 Raw trip data:', trip); const formValues = { name: trip.name, departure_time: dayjs(trip.departure_time), arrival_time: dayjs(trip.arrival_time), departure_port_id: trip.departure_port_id, arrival_port_id: trip.arrival_port_id, fishing_ground_codes: trip.fishing_ground_codes || [], fishing_gear: trip.fishing_gears || [], trip_cost: trip.trip_cost || [], }; console.log('📋 Prepared form values:', formValues); setInitialFormValues(formValues); message.success( `Đã tải ${trip.fishing_gears?.length || 0} ngư cụ và ${ trip.trip_cost?.length || 0 } chi phí từ chuyến trước`, ); } } catch (error) { console.error('Error loading last trip:', error); setLastTrip(null); } finally { setLoading(false); } }; const handleSubmit = async (values: TripFormValues) => { try { if (!selectedShip) { message.error('Vui lòng chọn tàu!'); return false; } if (!values.departure_port_id) { message.error('Vui lòng chọn cảng khởi hành!'); return false; } if (!values.arrival_port_id) { message.error('Vui lòng chọn cảng cập bến!'); return false; } const params: SgwModel.TripCreateParams = { name: values.name, departure_time: dayjs(values.departure_time as string | Date) .utc() .format(), departure_port_id: values.departure_port_id, arrival_time: dayjs(values.arrival_time as string | Date) .utc() .format(), arrival_port_id: values.arrival_port_id, fishing_ground_codes: Array.isArray(values.fishing_ground_codes) ? (values.fishing_ground_codes as (string | number)[]) .map((code: string | number) => Number(code)) .filter((n: number) => !isNaN(n)) : [], fishing_gears: values.fishing_gear, trip_cost: values.trip_cost || [], }; const thingIdToUse = selectedShip.thing_id || selectedThing; if (!thingIdToUse) { message.error('Không tìm thấy thiết bị của tàu!'); return false; } const resp = await apiCreateTrip(thingIdToUse, params); console.log('createTrip resp', resp); if (resp && !resp?.trip_status) { message.success('Tạo chuyến đi thành công!'); onSuccess?.(true); setVisible(false); setSelectedShip(null); return true; } else { message.error(`Tạo chuyến đi thất bại!`); return false; } } catch (err) { console.error('Lỗi khi tạo chuyến đi:', err); message.error('Tạo chuyến đi thất bại!'); return false; } }; return ( <> { setVisible(open); if (!open) { setSelectedShip(null); } }} onFinish={handleSubmit} modalProps={{ width: 900, }} layout="horizontal" submitter={false} > stepsProps={{ size: 'small' }} onFinish={(values) => handleSubmit(values as TripFormValues)} submitter={{ render: (_: SubmitterProps, dom) => dom, }} formProps={{ layout: 'horizontal', }} formRef={formRef} onCurrentChange={(current) => { if (!lastTrip || !formRef.current) return; if (current === 1) { formRef.current.setFieldsValue({ name: lastTrip.name, departure_time: dayjs(lastTrip.departure_time), arrival_time: dayjs(lastTrip.arrival_time), departure_port_id: lastTrip.departure_port_id, arrival_port_id: lastTrip.arrival_port_id, fishing_ground_codes: lastTrip.fishing_ground_codes || [], }); } if (current === 2) { formRef.current.setFieldsValue({ fishing_gear: lastTrip.fishing_gears || [], }); } if (current === 3) { formRef.current.setFieldsValue({ trip_cost: lastTrip.trip_cost || [], }); } }} > {/* Step 1: Chọn tàu */} { if (!selectedShip) { message.error('Vui lòng chọn một tàu!'); return false; } // Load last trip after selecting ship const thingIdToUse = selectedShip.thing_id || selectedThing; if (thingIdToUse) { await loadLastTrip(thingIdToUse); } return true; }} > Danh sách tàu { setSelectedShip(selectedRows[0] || null); }, }} columns={[ { title: 'Số đăng ký', dataIndex: 'reg_number', key: 'reg_number', }, { title: 'Tên tàu', dataIndex: 'name', key: 'name' }, { title: 'Loại tàu', dataIndex: 'ship_type', key: 'ship_type' }, { title: 'Cảng nhà', dataIndex: 'home_port', key: 'home_port' }, ]} /> {/* Step 2: Thông tin chuyến đi */} { if (!value) return Promise.resolve(); const todayDate = dayjs().startOf('day'); const selectedDate = dayjs(value as string).startOf( 'day', ); return selectedDate.isBefore(todayDate) ? Promise.reject( new Error('Ngày bắt đầu không được trước hôm nay'), ) : Promise.resolve(); }, }, ]} /> ({ label: p.name, value: p.id })) : [] } rules={[ { required: true, message: 'Vui lòng chọn cảng khởi hành' }, ]} showSearch /> ({ label: p.name, value: p.id })) : [] } rules={[ { required: true, message: 'Vui lòng chọn cảng cập bến' }, ]} showSearch /> {/* Step 3: Danh sách ngư cụ */}
Tên ngư cụ Số lượng
{/* Step 4: Chi phí nguyên liệu */}
Loại Số lượng Đơn vị Chi phí/đơn vị Tổng chi phí
); }; export default CreateTrip;