package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.entity.dto.AppDiagLogDTO;
import com.om.entity.dto.DiaLogQueryPageDTO;
import com.om.entity.dto.DiagnoseLogVehicleInfo;
import com.om.entity.dto.GuidDTO;
import com.om.entity.po.*;
import com.om.entity.vo.DiaLogQueryPageVO;
import com.om.entity.vo.DiaLogQueryVO;
import com.om.exception.BadReqException;
import com.om.mapper.DiagnosticLogMapper;
import com.om.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.utils.AesUtil;
import com.om.utils.HuaweiObsUtil;
import com.om.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.om.constant.UploadConstant.DIAGNOSTIC_LOG_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-02-27
 */
@Service
public class DiagnosticLogServiceImpl extends ServiceImpl<DiagnosticLogMapper, DiagnosticLog> implements IDiagnosticLogService {

    @Resource
    private IUserService userService;

    @Resource
    private IBrandService brandService;

    @Resource
    private IClientService clientService;

    @Resource
    private HuaweiObsUtil obsUtil;

    @Resource
    private IVciInfoService vciInfoService;

    @Override
    public Result<DiaLogQueryPageVO> getPageList(DiaLogQueryPageDTO dto) {
        //从dto中获取数据
        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();
        LocalDateTime beginTime = dto.getBeginTime();
        LocalDateTime endTime = dto.getEndTime();
        String vciSn = dto.getVciSn();
        String account = dto.getAccount();


        Page<DiagnosticLog> page = this.lambdaQuery()
                .like(StringUtils.isNotBlank(account), DiagnosticLog::getUsername, account)
                .like(StringUtils.isNotBlank(vciSn), DiagnosticLog::getVciSn, vciSn)
                .ge(beginTime != null, DiagnosticLog::getCreateTime, beginTime)
                .le(endTime != null, DiagnosticLog::getCreateTime, endTime)
                .orderByDesc(DiagnosticLog::getCreateTime)
                .page(new Page<>(pageIndex, pageSize));

        DiaLogQueryPageVO vo = new DiaLogQueryPageVO();
        vo.setCurrent((int) page.getCurrent());
        vo.setSize((int) page.getSize());
        vo.setPages((int) page.getPages());
        vo.setTotal((int) page.getTotal());

        if (dto.getAccount() != null || dto.getVciSn() != null || beginTime != null || endTime != null) {
            vo.setSearchCount(true);
        }

        List<DiagnosticLog> records = page.getRecords();
        List<DiaLogQueryVO> diaLogQueryVOS = new ArrayList<>();
        for (DiagnosticLog record : records) {
            DiaLogQueryVO diaLogQueryVO = BeanUtil.copyProperties(record, DiaLogQueryVO.class);
            diaLogQueryVO.setAccount(record.getUsername());
            diaLogQueryVO.setBrand(record.getBrandName());

            Client client = clientService
                    .lambdaQuery()
                    .eq(Client::getNumber,record.getClientNum())
                    .one();
            if (client != null) {
                diaLogQueryVO.setClientNum(client.getNumber());
            }
            diaLogQueryVO.setVciSn(record.getVciSn());

            //todo 车型id vehicleId 查询车型

            diaLogQueryVOS.add(diaLogQueryVO);
        }

        vo.setRecords(diaLogQueryVOS);
        return Result.ok(vo);
    }

    @Override
    public Result batchDownload(List<Integer> ids) {
        //根据id集合查询
        List<DiagnosticLog> diagnosticLogs = this.listByIds(ids);

        if (CollectionUtil.isEmpty(diagnosticLogs)) {
            throw new BadReqException("本页诊断文件异常");
        }


        List<String> downloadUrls = new ArrayList<>();
        String prefix = DIAGNOSTIC_LOG_PREFIX;
        for (DiagnosticLog diagnosticLog : diagnosticLogs) {
            String nameLog = diagnosticLog.getNameLog();
            int lastIndexOf = nameLog.lastIndexOf("/");
            if (lastIndexOf != -1) {
                nameLog = nameLog.substring(lastIndexOf + 1);
            }
            //获取下载链接
            String downloadUrl = obsUtil.getUploadUrl(nameLog, prefix);
            downloadUrls.add(downloadUrl);
        }
        return Result.ok(downloadUrls);
    }

    @Override
    public Result downloadFile(Integer id) {
        //根据id进行查询
        DiagnosticLog diagnosticLog = this.getById(id);

        if (BeanUtil.isEmpty(diagnosticLog)) {
            throw new BadReqException("该诊断日志不存在");
        }

        //获取文件名称
        String nameLog = diagnosticLog.getNameLog();
        int lastIndexOf = nameLog.lastIndexOf("/");
        if (lastIndexOf != -1) {
            nameLog = nameLog.substring(lastIndexOf + 1);
        }
        String prefix = DIAGNOSTIC_LOG_PREFIX;
        //获取下载链接
        String downloadUrl = obsUtil.getUploadUrl(nameLog, prefix);
        return Result.ok(downloadUrl);
    }

    @Override
    @Transactional
    public Result updateDiagLog(AppDiagLogDTO dto) {
        if (BeanUtil.isEmpty(dto)) {
            throw new BadReqException("参数为空！！");
        }
        String username = dto.getUsername();
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        String clientNum = guidDTO.getClientNum();
        List<DiagnoseLogVehicleInfo> vehicleInfo = dto.getVehicleInfo();

        for (DiagnoseLogVehicleInfo diagnoseLogVehicleInfo : vehicleInfo) {
            DiagnosticLog diagnosticLog = BeanUtil.copyProperties(diagnoseLogVehicleInfo, DiagnosticLog.class);
            /*
           VciInfo vciInfo = vciInfoService.lambdaQuery()
                    .eq(VciInfo::getVciNum, diagnoseLogVehicleInfo.getVciSn())
                    .one();
            if (BeanUtil.isEmpty(vciInfo)){
                throw new BadReqException("该vci设备不存在！！！");
            }
             */

            diagnosticLog.setVciSn(diagnoseLogVehicleInfo.getVciSn());
            diagnosticLog.setClientNum(clientNum);
            diagnosticLog.setBrandName(diagnoseLogVehicleInfo.getBrand());
            diagnosticLog.setCreateTime(LocalDateTime.now());
            diagnosticLog.setUpdateTime(LocalDateTime.now());
            diagnosticLog.setUsername(username);
            this.save(diagnosticLog);
        }

        return Result.ok();
    }

    @Override
    public Result delete(Integer id) {
        DiagnosticLog diagnosticLog = this.getById(id);
        if (BeanUtil.isEmpty(diagnosticLog)) {
            throw new BadReqException("该诊断日志不存在");
        }

        return Result.ok(this.removeById(diagnosticLog.getId()));
    }
}
