package com.seer.teach.mp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.utils.AESUtils;
import com.seer.teach.mp.entity.MpDealerApplicationsEntity;
import com.seer.teach.mp.mapper.MpDealerApplicationsMapper;
import com.seer.teach.mp.request.DealerApplyReq;
import com.seer.teach.mp.service.IMpDealerApplicationsService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.Objects;

/**
 * <p>
 * 经销商申请表 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-08-04 13:45:07
 */
@Service
public class MpDealerApplicationsServiceImpl extends ServiceImpl<MpDealerApplicationsMapper, MpDealerApplicationsEntity> implements IMpDealerApplicationsService {

    @Override
    public void decryptDealerApplication(MpDealerApplicationsEntity application) {
        if (Objects.isNull(application)) {
            return;
        }
        application.setBusinessLicenseNumber(AESUtils.decrypt(application.getBusinessLicenseNumber()));
        application.setIdCardNumber(AESUtils.decrypt(application.getIdCardNumber()));
        application.setBusinessLicenseImage(AESUtils.decrypt(application.getBusinessLicenseImage()));
        application.setIdCardFrontImage(AESUtils.decrypt(application.getIdCardFrontImage()));
        application.setIdCardBackImage(AESUtils.decrypt(application.getIdCardBackImage()));

    }

    @Override
    public boolean apply(DealerApplyReq request, Integer userId) {
        MpDealerApplicationsEntity application = buildApplication(request, userId);
        return super.save(application);
    }

    @Override
    public boolean updateDealerApplication(DealerApplyReq request, int userId) {
        MpDealerApplicationsEntity application = buildApplication(request, userId);
        return super.updateById(application);
    }

    private MpDealerApplicationsEntity buildApplication(DealerApplyReq request, Integer userId) {
        MpDealerApplicationsEntity application = new MpDealerApplicationsEntity();
        application.setId( request.getId());
        application.setApplicantName(request.getApplicantName());

        // 加密敏感数据
        application.setBusinessLicenseNumber(AESUtils.encrypt(request.getBusinessLicenseNumber()));
        application.setIdCardNumber(AESUtils.encrypt(request.getIdCardNumber()));

        // 处理并存储图片
        application.setBusinessLicenseImage(processAndEncryptImage(request.getBusinessLicenseImage()));
        application.setIdCardFrontImage(processAndEncryptImage(request.getIdCardFrontImage()));
        application.setIdCardBackImage(processAndEncryptImage(request.getIdCardBackImage()));

        application.setDescription(request.getDescription());
        application.setApplicantUserId(userId);
        application.setPhone(request.getPhone());
        application.setApplyTime(LocalDateTime.now());
        application.setApplyType(request.getApplyType());
        return application;
    }


    private String processAndEncryptImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return null;
        }
        try {
            String base64EncodedFile = "data:" + file.getContentType() + ";base64," +
                    Base64.getEncoder().encodeToString(file.getBytes());
            return AESUtils.encrypt(base64EncodedFile);
        } catch (IOException e) {
            log.error("Error processing image: ", e);
            return null;
        }
    }

    @Override
    public MpDealerApplicationsEntity getOneByUserId(Integer userId) {
        MpDealerApplicationsEntity dealerApplicationsEntity = super.getOne(new LambdaQueryWrapper<>(MpDealerApplicationsEntity.class).eq(MpDealerApplicationsEntity::getApplicantUserId, userId));
        decryptDealerApplication(dealerApplicationsEntity);
        return dealerApplicationsEntity;
    }

    @Override
    public MpDealerApplicationsEntity getOneById(Integer id) {
        MpDealerApplicationsEntity dealerApplicationsEntity = getById( id);
        decryptDealerApplication(dealerApplicationsEntity);
        return dealerApplicationsEntity;
    }

    @Override
    public IPage<MpDealerApplicationsEntity> pageList(Page<MpDealerApplicationsEntity> pageParm, MpDealerApplicationsEntity query) {
        LambdaQueryWrapper<MpDealerApplicationsEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(MpDealerApplicationsEntity::getCreateTime);
        if (StringUtils.isNotBlank(query.getApplicantName())) {
            wrapper.like(MpDealerApplicationsEntity::getApplicantName, query.getApplicantName());
        }
        if (Objects.nonNull(query.getApplicantUserId())) {
            wrapper.eq(MpDealerApplicationsEntity::getApplicantUserId, query.getApplicantUserId());
        }
        IPage<MpDealerApplicationsEntity> resultPage = super.page(pageParm, wrapper);
        if(CollectionUtil.isNotEmpty(resultPage.getRecords())){
            resultPage.getRecords().forEach(this::decryptDealerApplication);
        }
        return resultPage;
    }

}