import { request, downloadFile } from '@vtx/utils';
import moment from 'moment';
import { useRequest } from 'ahooks';
const baseInfoField = [
    {
        label: '所属单位',
        key: 'belongUnitName',
    },
    {
        label: '使用单位',
        key: 'useUnitName',
    },
    {
        label: '所属标段',
        key: 'bidSectionName',
    },
    {
        label: '行政区划',
        key: 'divisionName',
    },
    {
        label: '责任人',
        key: 'manageStaffName',
    },
    {
        label: '联系人',
        key: 'contact',
    },
    {
        label: '联系方式',
        key: 'contactWay',
    },
];
const jxhInfoField = [
    {
        label: '车辆品牌',
        key: 'carBrand',
    },
    {
        label: '车辆型号',
        key: 'carType',
    },
    {
        label: '购置时间',
        key: 'procurementDate',
    },
    {
        label: '购置金额',
        key: 'procurementAmt',
    },
    {
        label: '发票编号',
        key: 'invoiceCode',
    },
    {
        label: '证书编号',
        key: 'certificateCode',
    },
    {
        label: '证书保管人',
        key: 'certificateKeeper',
    },
    {
        label: '车辆识别代号',
        key: 'identifyCode',
    },
    {
        label: '发动机号',
        key: 'engineCode',
    },
    {
        label: '车辆厂牌',
        key: 'carLabel',
    },
    {
        label: '出厂日期',
        key: 'productionDate',
    },
    {
        label: '出厂地',
        key: 'productionPlace',
    },
    {
        label: '自有重量',
        key: 'ownWeight',
    },
    {
        label: '整备质量',
        key: 'curbWeight',
    },
    {
        label: '核定载质量',
        key: 'regulationWeight',
    },
    {
        label: '车辆用途',
        key: 'carUseWay',
    },
    {
        label: '车辆性质',
        key: 'carProperty',
    },
    {
        label: '车辆属性',
        key: 'carAttrOne',
    },
    {
        label: '核定载员',
        key: 'regulationPerson',
    },
    {
        label: '作业宽度',
        key: 'carWorkingWidth',
    },
    {
        label: '行驶证照片',
        type: 'img',
        key: 'driveLicensePhotoIds',
    },
];
const BaseData = {
    useBaseInfo: (id, start, end) => {
        const { data: baseInfoRes } = useRequest(
            () =>
                request.get('/cloud/gps-reborn/sdk/car/getCarInfoByProductType', {
                    data: { carId: id, coordType: 'bd09' },
                }),
            { refreshDeps: [id] },
        );
        const baseInfo = baseInfoRes?.data;
        const realTimeInfo = {
            time: baseInfo?.equipmentTime,
            location: baseInfo?.address,
            status: baseInfo?.carStatusStr,
            speed: baseInfo?.gpsSpeed,
            mile: baseInfo?.accuMileage,
            percent: baseInfo?.completePercent,
        };

        const { data: carTempInfo } = useRequest(
            () =>
                request.get('/cloud/gps-reborn/car/np/getCarDetailById', {
                    data: { id, coordType: 'bd09' },
                }),
            { refreshDeps: [id] },
        );
        const carInfo = carTempInfo?.data;
        const jxhInfo = jxhInfoField.map(item => {
            let value = carInfo?.[item.key];
            if (item.type === 'img') {
                value = JSON.parse(value || '[]');
            }
            return {
                ...item,
                value,
            };
        });

        const info = baseInfoField.map(item => ({
            ...item,
            value: carInfo?.[item.key],
        }));
        const { data: permissionRes } = useRequest(
            () =>
                request.post('/cloud/sjzt-reborn/api/v101/dataSet/execute', {
                    data: JSON.stringify({
                        code: 'JSSJZLJ_CAR_ROAD_PERMIT',
                        parameters: { carId: id },
                    }),
                }),
            { refreshDeps: [id] },
        );
        /** 基础信息 */
        const permissionData = permissionRes?.data || [];
        const permissionInfo = permissionData.map(item => [
            {
                label: '通行证编号',
                key: 'code',
                value: item?.code,
            },
            {
                label: '有效期',
                key: 'effect',
                value: item?.effect,
            },
            {
                label: '运输路线',
                key: 'roadNames',
                value: item?.roadNames,
            },
            {
                label: '垃圾类型',
                key: 'rubbishType',
                value: item?.rubbishType,
            },
        ]);

        const { data: workSummaryRes } = useRequest(
            () =>
                request.post('/cloud/sjzt-reborn/api/v101/dataSet/execute', {
                    data: JSON.stringify({
                        code: 'ZYQS_CAR_WORK_SUMMARY',
                        parameters: {
                            carId: id,
                            startDate: moment(start).format('YYYY-MM-DD'),
                            endDate: moment(end).format('YYYY-MM-DD'),
                        },
                    }),
                }),
            { refreshDeps: [id, start, end] },
        );

        const workSummary = workSummaryRes?.data || {};

        if (workSummary.work_duration) {
            let seconds = workSummary.work_duration / 1000;
            workSummary.duration = {
                hour: Math.floor(seconds / 3600),
                minute: Math.floor((seconds % 3600) / 60),
                second: Math.floor(seconds % 60),
            };
        }

        // 作业分析
        const { data: workChartRes } = useRequest(
            () =>
                request.post('/cloud/sjzt-reborn/api/v101/dataSet/execute', {
                    data: JSON.stringify({
                        code: 'ZYQS_CAR_WORK_STATISTICS',
                        parameters: {
                            carId: id,
                            startDate: moment(start).format('YYYY-MM-DD'),
                            endDate: moment(end).format('YYYY-MM-DD'),
                        },
                    }),
                }),
            { refreshDeps: [id, start, end] },
        );
        let workChart = workChartRes?.data || [];
        const days = moment(end).diff(moment(start), 'd') + 1;
        workChart = [...new Array(days)].map((_, index) => {
            const date = moment(start)
                .add(index, 'd')
                .format('YYYY-MM-DD');
            const data = workChart.find(e => e.work_date === date);
            if (data) {
                return data;
            } else {
                return {
                    work_date: date,
                };
            }
        });
        return { info, jxhInfo, permissionInfo, realTimeInfo, workSummary, workChart };
    },
    useAlarmStat: (id, start, end) => {
        const { data: res } = useRequest(
            () =>
                request.get('/cloud/gps-reborn/car/detail/alarmSumWithDetail', {
                    data: {
                        carId: id,
                        beginTime: moment(start)
                            .startOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        endTime: moment(end)
                            .endOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                    },
                }),
            {
                refreshDeps: [id, start, end],
            },
        );
        const data = res?.data;
        const totalSeconds = data?.alarmSum.totalSeconds || 0;
        const statInfo = {
            times: data?.alarmSum.total,
            days: data?.alarmSum.totalDays,
            hour: Math.floor(totalSeconds / 3600),
            minute: Math.floor((totalSeconds % 3600) / 60),
            second: Math.floor(totalSeconds % 60),
        };
        const statChartInfo = data?.alarmGroupByType.items || [];
        const statLineInfo = data?.alarmGroupByDayType.items || [];
        return { statInfo, statChartInfo, statLineInfo };
    },
    getTodayWorkMile: id => {
        const { data } = useRequest(
            () =>
                request.get('/cloud/zyqs-reborn/api/noshift/realtime/getWorkMileage', {
                    data: {
                        carId: id,
                        startTime: moment()
                            .startOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        endTime: moment()
                            .endOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        onlyOnShift: true,
                    },
                }),
            {
                refreshDeps: [id],
            },
        );
        return data?.data || 0;
    },
};

const WarningData = {
    useStatList: (id, start, end, carType) => {
        if (carType === 'jxh') {
            return [
                { key: 'all', count: 0, label: '全部' },
                { key: 'CarOverSpeed', count: 0, label: '超速' },
            ];
        }
        const { data: res } = useRequest(
            () =>
                request.get('/cloud/gps-reborn/alarm/record/statisticsPage', {
                    data: {
                        carIds: id,
                        startTime: moment(start)
                            .startOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                        endTime: moment(end)
                            .endOf('day')
                            .format('YYYY-MM-DD HH:mm:ss'),
                    },
                }),
            {
                refreshDeps: [id, start, end],
            },
        );
        const data = [{ key: 'all', count: 0, label: '全部' }];
        if (res && res.data) {
            data[0] = { key: 'all', count: res.data.totalCount, label: '全部' };
            const ext = res.data.summary.map(i => ({
                key: i.alarmType,
                count: i.totalCount,
                label: i.alarmTypeName,
            }));
            data.push(...ext);
        }
        return data;
    },
    getWarningList: (page, size, id, start, end, tab) => {
        return request
            .get('/cloud/gps-reborn/alarm/record/pageList', {
                data: {
                    page,
                    rows: size,
                    carIds: id,
                    startTime: moment(start)
                        .startOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    endTime: moment(end)
                        .endOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    alarmStrategyName: tab,
                },
            })
            .then(res => {
                if (res.result === 0) {
                    res.data.list = res.data.rows;
                }
                return res.data;
            });
    },
    getJxhWarningList: (page, size, id, start, end, tab) => {
        return request
            .get('/cloud/zyqs-reborn/api/noshift/event/page', {
                data: {
                    pageNo: page - 1,
                    pageSize: size,
                    carIds: id,
                    startDate: moment(start)
                        .startOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    endDate: moment(end)
                        .endOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    subCategoryCode: tab,
                    categoryCode: 'Alarm',
                },
            })
            .then(res => {
                if (res.result === 0) {
                    res.data.list = res.data.rows;
                }
                return res.data;
            });
    },

    exportData: params => {
        return downloadFile(
            '/cloud/gps-reborn/alarm/record/export',
            {
                data: {
                    ...params,
                    startTime: moment(params.startTime)
                        .startOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    endTime: moment(params.endTime)
                        .endOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                },
            },
            'blob',
        );
    },
    exportJxhData: params => {
        return downloadFile(
            '/cloud/zyqs-reborn/api/noshift/event/excel',
            {
                data: {
                    ...params,
                    startDate: moment(params.startDate)
                        .startOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                    endDate: moment(params.endDate)
                        .endOf('day')
                        .format('YYYY-MM-DD HH:mm:ss'),
                },
            },
            'blob',
        );
    },
};
export { BaseData, WarningData };
