package cn.iocoder.yudao.module.custom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.custom.entity.CarMain;
import cn.iocoder.yudao.module.custom.entity.CustomerCar;
import cn.iocoder.yudao.module.custom.entity.CustomerMain;
import cn.iocoder.yudao.module.custom.entity.UserCar;
import cn.iocoder.yudao.module.custom.mapper.UserCarMapper;
import cn.iocoder.yudao.module.custom.service.CarMainService;
import cn.iocoder.yudao.module.custom.service.CustomerCarService;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.custom.service.UserCarService;
import cn.iocoder.yudao.module.custom.vo.DrivelicenseVO;
import cn.iocoder.yudao.module.custom.vo.UserCarVO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.util.VehicleLicenseOCR;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户车辆信息表--用户个人录入的 Service 实现类
 *
 * @author vinjor-M
 */
@Service
@Validated
public class UserCarServiceImpl extends ServiceImpl<UserCarMapper, UserCar> implements UserCarService {

    @Resource
    private UserCarMapper userCarMapper;
    @Resource
    private CustomerMainService customerMainService;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private CarMainService carMainService;
    @Resource
    private CustomerCarService customerCarService;


    /**
     * 创建或更新车辆信息
     *
     * @param userCarVO 车辆信息
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author vinjor-M
     * @date 14:11 2024/10/11
     **/
    @Override
    public CommonResult<?> createOrUpdate(UserCarVO userCarVO) {
        //车牌号英文全部转大写
        userCarVO.setLicenseNumber(userCarVO.getLicenseNumber().toUpperCase());
        //设置所属者
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        userCarVO.setUserId(loginUser.getId());
        this.saveOrUpdate(userCarVO);
        return CommonResult.ok();
    }

    /**
     * 查询当前登录用户的所有车辆
     *
     * @return java.util.List<cn.iocoder.yudao.module.custom.vo.UserCarVO>
     * @author vinjor-M
     * @date 14:28 2024/10/11
     **/
    @Override
    public List<UserCarVO> getMyCar(Long userId) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        return userCarMapper.selectByUserId(null==userId?loginUser.getId():userId);
    }

    /**
     * @param imagePath 公网图片地址
     * @return java.lang.Object
     * @author vinjor-M
     * @date 16:59 2024/10/11
     **/
    @Override
    public Object vehicleLicenseOCR(String imagePath) throws TencentCloudSDKException {
        String info = VehicleLicenseOCR.dealFunction(imagePath);
        JSONObject infoJson = JSONUtil.parseObj(info);
        DrivelicenseVO licenseVO = BeanUtil.toBean(infoJson.getJSONObject("FrontInfo"),DrivelicenseVO.class);
        if(licenseVO.getModel().contains("牌")){
            licenseVO.setBrand(licenseVO.getModel().split("牌")[0]);
        }
        return licenseVO;
    }

    /**
     * 将客户信息授权给某个修理厂
     * @author PQZ
     * @date 12:40 2024/10/12
     * @param tenantId 租户id
     * @param dataFrom 客户来源
     * @param userId 邀请者的用户ID
     * @param newUserId 被邀请者的用户ID
     * @param inviteType 邀请类型
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @TenantIgnore
    public void empowerUserInfo(Long tenantId,String dataFrom,Long userId,Long newUserId,String inviteType) {
        /*1、基础数据准备*/
        if(null==newUserId){
            newUserId = SecurityFrameworkUtils.getLoginUserId();
        }
        //获取当前登录用户信息
        AdminUserRespDTO loginUser = userApi.getUser(newUserId);
        //获取当前登录用户车辆信息
        List<UserCarVO> carList = this.getMyCar(newUserId);
        //需要保存的关联关系
        List<CustomerCar> saveCustomerCarList = new ArrayList<>();
        //需要保存的车辆信息
        List<CarMain> saveCarList = new ArrayList<>();
        //查是否已有客户信息，若有则更新,没有则插入
        final CustomerMain[] oldMain = {null};
        //查已有的车辆信息，若有则更新,没有则插入
        final Map<String, CarMain>[] carMap = new Map[]{new HashMap<>()};
        Long finalNewUserId = newUserId;
        TenantUtils.execute(tenantId, () -> {
            //客户在这个租户下的信息
            oldMain[0] = customerMainService.getCustomerByUserId(finalNewUserId);
            //客户在这个租户下的车辆信息
            List<CarMain> oldCarMainList=carMainService.selectListByUserId(finalNewUserId);
            carMap[0] = oldCarMainList.stream().collect(Collectors.toMap(CarMain::getLicenseNumber, Function.identity()));
        });
        String customerId;
        CustomerMain customerMain;
        /*2、数据转换，将用户表关联信息转换成客户表关联信息 */
        //转换客户数据
        if(null== oldMain[0]){
            //新增客户
            customerId = UUID.randomUUID().toString().replace("-", "");
            customerMain = new CustomerMain();
            customerMain.setId(customerId);
            customerMain.setUserId(newUserId);
            //客户租户
            customerMain.setTenantId(tenantId);
            //统一为个人客户
            customerMain.setTypeCode("01");
            //客户初始来源系统
            customerMain.setDataFrom(dataFrom);
            //默认不允许挂账
            customerMain.setIsHangAccount("0");
            if(null!=userId){
                //是被邀请的，设置邀请者信息
                customerMain.setInviter(userId.toString());
                customerMain.setInviterType(inviteType);
            }
        }else{
            //更新客户信息
            customerId = oldMain[0].getId();
            customerMain = oldMain[0];
        }
        customerMain.setCusName(loginUser.getNickname());
        customerMain.setSex(String.valueOf(loginUser.getSex()));
        customerMain.setPhoneNumber(loginUser.getMobile());
        //转换车辆及关联关系数据
        if (CollUtil.isNotEmpty(carList)){
            carList.forEach(item ->{
                CarMain carItem = new CarMain();
                if(carMap[0].containsKey(item.getLicenseNumber())){
                    //更新
                    BeanUtil.copyProperties(carMap[0].get(item.getLicenseNumber()),carItem);
                }else{
                    //插入
                    carItem = new CarMain();
                    String carId = UUID.randomUUID().toString().replace("-", "");
                    carItem.setId(carId);
                    CustomerCar customerCarItem = new CustomerCar();
                    //客户与车辆关联关系
                    customerCarItem.setCusId(customerId);
                    customerCarItem.setCarId(carId);
                    customerCarItem.setIsOwner(item.getIsOwner());
                    saveCustomerCarList.add(customerCarItem);
                }
                //车辆信息
                carItem.setEngineNumber(item.getEngineNumber());
                carItem.setVin(item.getVin());
                carItem.setUserId(finalNewUserId);
                carItem.setLicenseNumber(item.getLicenseNumber());
                carItem.setCarModel(item.getCarModel());
                carItem.setMaintenanceDate(convertToLocalDateTime(item.getMaintenanceDate()));
                carItem.setMaintenanceMileage(convertToBigDecimal(item.getMaintenanceMileage()));
                carItem.setInspectionDate(convertToLocalDateTime(item.getInspectionDate()));
                carItem.setInsuranceDate(convertToLocalDateTime(item.getInsuranceDate()));
                carItem.setCheckDate(convertToLocalDateTime(item.getCheckDate()));
                carItem.setNextMaintenanceDate(convertToLocalDateTime(item.getNextMaintenanceDate()));
                carItem.setNextMaintenanceMileage(convertToBigDecimal(item.getNextMaintenanceMileage()));
                carItem.setNextInspectionDate(convertToLocalDateTime(item.getNextInspectionDate()));
                carItem.setInsuranceExpiryDate(convertToLocalDateTime(item.getInsuranceExpiryDate()));
                carItem.setNextCheckDate(convertToLocalDateTime(item.getNextCheckDate()));
                carItem.setCarBrand(item.getCarBrand());
                carItem.setCarNature(item.getCarNature());
                carItem.setCarCategory(item.getCarCategory());
                carItem.setCarRegisterDate(convertToLocalDateTime(item.getCarRegisterDate()));
                carItem.setCarLicenseImg(item.getCarLicenseImg());
                saveCarList.add(carItem);
            });
        }
        /*3、数据保存*/
        TenantUtils.execute(tenantId, () -> {
            //保存客户信息
            customerMainService.saveOrUpdate(customerMain);
            //保存或更新车辆信息
            if(!saveCarList.isEmpty()){
                carMainService.saveOrUpdateBatch(saveCarList);
            }
            if(!saveCustomerCarList.isEmpty()){
                //保存客户与车辆关联关系
                customerCarService.saveBatch(saveCustomerCarList);
            }
        });
    }

    /* Date转换为LocalDateTime */
    private LocalDateTime convertToLocalDateTime(Date carRegisterDate) {
        if (carRegisterDate != null) {
            return LocalDateTime.ofInstant(carRegisterDate.toInstant(), ZoneId.systemDefault());
        }
        return null;
    }

    /* Long转换为BigDecimal */
    private BigDecimal convertToBigDecimal(Long value) {
        if (value != null) {
            return BigDecimal.valueOf(value);
        }
        return null;
    }

}
