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

import cn.hutool.core.collection.CollectionUtil;
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.service.CarMainService;
import cn.iocoder.yudao.module.custom.service.CustomerCarService;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.custom.vo.CustomerMainSaveReqVO;
import cn.iocoder.yudao.module.inspection.service.AppInspectionPartnerService;
import cn.iocoder.yudao.module.partner.entity.PartnerCustomerInfo;
import cn.iocoder.yudao.module.partner.mapper.PartnerCustomerInfoMapper;
import cn.iocoder.yudao.module.partner.service.IPartnerCustomerInfoService;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.shop.entity.ShopUserCar;
import cn.iocoder.yudao.module.shop.service.IShopUserCarService;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.DateUtils;
import cn.iocoder.yudao.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import static cn.iocoder.yudao.common.BaseConstants.SIGN_CREATE;

/**
 * 客户信息Service业务层处理
 *
 * @author zcy
 * @date 2023-09-13
 */
@Service
public class PartnerCustomerInfoServiceImpl extends ServiceImpl<PartnerCustomerInfoMapper, PartnerCustomerInfo> implements IPartnerCustomerInfoService
{
    @Autowired
    private IShopUserCarService userCarService;
    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Resource
    private PartnerCustomerInfoMapper customerInfoMapper;
    @Autowired
    private PartnerCustomerInfoMapper partnerCustomerInfoMapper;
    @Resource
    private CustomerMainService customerMainService;
    @Autowired
    private CarMainService carMainService;
    @Resource
    private CustomerCarService customerCarService;

    /**
     * 查询客户信息列表
     *
     * @param partnerCustomerInfo 客户信息
     * @return 客户信息
     */
    @Override
    public List<PartnerCustomerInfo> selectPartnerCustomerInfoList(PartnerCustomerInfo partnerCustomerInfo)
    {
        List<PartnerCustomerInfo> partnerCustomerInfos = customerInfoMapper.selectPartnerCustomerInfoList(partnerCustomerInfo);
        for (PartnerCustomerInfo customerInfo : partnerCustomerInfos) {
            List<ShopUserCar> list = userCarService.selectUserCarsByUserId(customerInfo.getUserId());
            if (CollectionUtil.isNotEmpty(list)){
                customerInfo.setUserCarList(list);
            }else {
                customerInfo.setUserCarList(new ArrayList<>());
            }
        }
        return partnerCustomerInfos;
    }

    @Override
    public IPage<PartnerCustomerInfo> queryListPage(PartnerCustomerInfo entity, Page<PartnerCustomerInfo> page) {
        IPage<PartnerCustomerInfo> partnerCustomerInfos = customerInfoMapper.pagePartnerCustomerInfoList(entity,page);
        partnerCustomerInfos.getRecords().forEach(item ->{
            List<ShopUserCar> list = userCarService.selectUserCarsByUserId(item.getUserId());
            if (CollectionUtil.isNotEmpty(list)){
                item.setUserCarList(list);
            }else {
                item.setUserCarList(new ArrayList<>());
            }
        });
        return partnerCustomerInfos;
    }

    /**
     * 查询客户信息
     *
     * @param id 客户信息主键
     * @return 客户信息
     */
    @Override
    public PartnerCustomerInfo selectPartnerCustomerInfoById(Long id)
    {
        return baseMapper.selectPartnerCustomerInfoById(id);
    }

    /**
     * 新增客户信息
     *
     * @param partnerCustomerInfo 客户信息
     * @return 结果
     */
    @Override

    public int insertPartnerCustomerInfo(PartnerCustomerInfo partnerCustomerInfo) throws Exception {
        // 获取当前商户信息
        ShopMallPartners partners = partnerService.shopInfo();

        // 检查客户是否已存在
        LambdaQueryWrapper<PartnerCustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerCustomerInfo::getPartnerId, partners.getPartnerId())
                .eq(PartnerCustomerInfo::getCustomerPhone, partnerCustomerInfo.getCustomerPhone());

        PartnerCustomerInfo customerInfo = this.getOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(customerInfo)) {
            throw new Exception("客户已存在");
        }

        // 查找或创建用户
        AdminUserDO user = userService.selectUserByPhone(partnerCustomerInfo.getCustomerPhone());
        if (ObjectUtils.isEmpty(user)) {
            RoleDO role = roleService.queryRole("jcyh");
            if (role != null) {
                UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
                user = new AdminUserDO();
                BeanUtils.copyProperties(partnerCustomerInfo, user);
                userSaveReqVO.setUsername(partnerCustomerInfo.getCustomerPhone());
                userSaveReqVO.setNickname(partnerCustomerInfo.getCustomerName());
                userSaveReqVO.setPassword("123456");
                Long uid = userService.createUser(userSaveReqVO);
                user.setId(uid);
                Set<Long> ids = new HashSet<>();
                ids.add(role.getId());
                permissionService.assignUserRole(uid, ids);
            } else {
                throw new RuntimeException("无法找到角色 'jcyh'");
            }
        }

        // 角色分配
        if (!StringUtils.isEmpty(partnerCustomerInfo.getRoleCode())) {
            RoleDO sysRole = roleService.queryRole(partnerCustomerInfo.getRoleCode());
            Set<Long> ids = new HashSet<>();
            ids.add(sysRole.getId());
            permissionService.assignUserRole(user.getId(), ids);
        }

        // 车辆信息处理
        List<ShopUserCar> userCarList = partnerCustomerInfo.getUserCarList();
        List<CarMain> saveCarList = new ArrayList<>();
        List<CustomerCar> saveCustomerCarList = new ArrayList<>();
        List<ShopUserCar> saveUserCarList = new ArrayList<>();

        UserCar userCar1 = new UserCar();
        if (CollectionUtil.isNotEmpty(userCarList)) {
            for (ShopUserCar shopUserCar : userCarList) {
                // 生成车辆ID
                String carId = UUID.randomUUID().toString().replace("-", "");
                CarMain carMain = new CarMain();
                carMain.setId(carId);
                carMain.setUserId(user.getId());
                carMain.setLicenseNumber(shopUserCar.getCarNo());
                carMain.setEngineNumber(userCar1.getEngineNumber());
                carMain.setVin(userCar1.getVin());
                carMain.setCarModel(shopUserCar.getCarModel());
                // 设置其它车辆信息
                carMain.setMaintenanceDate(convertToLocalDateTime(shopUserCar.getMaintenanceDate()));
                carMain.setMaintenanceMileage(convertToBigDecimal(shopUserCar.getMaintenanceMileage()));
                carMain.setInspectionDate(convertToLocalDateTime(shopUserCar.getInspectionDate()));
                carMain.setInsuranceDate(convertToLocalDateTime(shopUserCar.getInsuranceDate()));
                carMain.setNextMaintenanceDate(convertToLocalDateTime(shopUserCar.getNextMaintenanceDate()));
                carMain.setNextMaintenanceMileage(convertToBigDecimal(shopUserCar.getNextMaintenanceMileage()));
                carMain.setNextInspectionDate(convertToLocalDateTime(shopUserCar.getNextInspectionDate()));
                carMain.setInsuranceExpiryDate(convertToLocalDateTime(shopUserCar.getInsuranceExpiryDate()));
                carMain.setCarBrand(shopUserCar.getCarBrand());
                carMain.setCarNature(shopUserCar.getCarNature());
                carMain.setCarCategory(userCar1.getCarCategory());
                carMain.setCarRegisterDate(convertToLocalDateTime(shopUserCar.getCarRegisterDate()));
                carMain.setCarLicenseImg(shopUserCar.getCarLicenseImg());
                carMain.setCheckDate(convertToLocalDateTime(shopUserCar.getCheckDate()));
                carMain.setNextCheckDate(convertToLocalDateTime(shopUserCar.getNextCheckDate()));

                // 保存车辆信息
                saveCarList.add(carMain);

                // 客户与车辆的关联关系
                CustomerCar customerCar = new CustomerCar();
                customerCar.setId(UUID.randomUUID().toString().replace("-", ""));
                customerCar.setCusId(user.getId().toString());
                customerCar.setCarId(carId);
                customerCar.setIsOwner(userCar1.getIsOwner()); // 是否为车主
                saveCustomerCarList.add(customerCar);

                // 保存用户车辆信息
                ShopUserCar userCar = new ShopUserCar();
                userCar.setUserId(user.getId());
                userCar.setCarNo(shopUserCar.getCarNo());
                userCar.setCarModel(shopUserCar.getCarModel());
                userCar.setMaintenanceDate(shopUserCar.getMaintenanceDate());
                userCar.setMaintenanceMileage(shopUserCar.getMaintenanceMileage());
                userCar.setInspectionDate(shopUserCar.getInspectionDate());
                userCar.setInsuranceDate(shopUserCar.getInsuranceDate());
                userCar.setNextMaintenanceDate(shopUserCar.getNextMaintenanceDate());
                userCar.setNextMaintenanceMileage(shopUserCar.getNextMaintenanceMileage());
                userCar.setNextInspectionDate(shopUserCar.getNextInspectionDate());
                userCar.setInsuranceExpiryDate(shopUserCar.getInsuranceExpiryDate());
                saveUserCarList.add(userCar);
            }
        }

        // 验证手机号
        if (!StringUtils.isMobile(partnerCustomerInfo.getCustomerPhone())) {
            throw new Exception("手机号不符合规范");
        }

        // 创建客户信息
        CustomerMain customerMain = new CustomerMain();
        customerMain.setId(UUID.randomUUID().toString().replace("-", ""));
        customerMain.setUserId(user.getId());
        customerMain.setCusName(partnerCustomerInfo.getCustomerName());
        customerMain.setPhoneNumber(partnerCustomerInfo.getCustomerPhone());
        customerMain.setSex(partnerCustomerInfo.getSex());
        customerMain.setIsHangAccount("0");
        customerMain.setTypeCode("01");
        // 设置客户初始来源
        //customerMain.setDataFrom("01");
        // 设置注册方式
        customerMain.setInviterType("01");

        // 保存客户信息
        customerMainService.saveOrUpdate(customerMain);

        // 保存车辆信息和客户与车辆关联关系
        carMainService.saveOrUpdateBatch(saveCarList);
        customerCarService.saveBatch(saveCustomerCarList);

        // 保存用户车辆信息
        for (ShopUserCar userCar : saveUserCarList) {
            // 检查是否已存在
            LambdaQueryWrapper<ShopUserCar> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(ShopUserCar::getUserId, userCar.getUserId()).eq(ShopUserCar::getCarNo, userCar.getCarNo());
            ShopUserCar existingUserCar = userCarService.getOne(queryWrapper1);
            if (existingUserCar != null) {
                // 更新用户车辆信息
                userCarService.updateById(userCar);
            } else {
                // 保存新用户车辆信息
                userCarService.save(userCar);
            }
        }

        // 填充 partnerCustomerInfo
        partnerCustomerInfo.setPartnerId(partners.getPartnerId());
        partnerCustomerInfo.setUserId(user.getId());

        // 插入 partner_customer_info
        return baseMapper.insertPartnerCustomerInfo(partnerCustomerInfo);
    }

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

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




    /**
     * 修改客户信息
     *
     * @param partnerCustomerInfo 客户信息
     * @return 结果
     */
    @Override
    public int updatePartnerCustomerInfo(PartnerCustomerInfo partnerCustomerInfo)
    {
        List<ShopUserCar> userCarList = partnerCustomerInfo.getUserCarList();
        for (ShopUserCar shopUserCar : userCarList) {
            shopUserCar.setUserId(partnerCustomerInfo.getUserId());
        }
        if (CollectionUtil.isNotEmpty(userCarList)){
            userCarService.deleteShopUserCarByUserId(partnerCustomerInfo.getUserId());
            userCarService.saveBatch(userCarList);
        }
        if (!StringUtils.isEmpty(partnerCustomerInfo.getCustomerPhone())&&!StringUtils.isEmpty(partnerCustomerInfo.getRoleCode())){
            AdminUserDO sysUser = userService.selectUserByPhone(partnerCustomerInfo.getCustomerPhone());
//            RoleDO sysRole = roleService.queryRole(partnerCustomerInfo.getRoleCode());

            if (ObjectUtils.isNotEmpty(sysUser)){
                Set<Long> ids = new HashSet<Long>();
                ids.add(sysUser.getId());
                permissionService.assignUserRole(sysUser.getId(),ids);
            }else {
                UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
                userSaveReqVO.setUsername(partnerCustomerInfo.getCustomerPhone());
                userSaveReqVO.setNickname(partnerCustomerInfo.getCustomerName());
                userSaveReqVO.setMobile(partnerCustomerInfo.getCustomerPhone());
                userSaveReqVO.setDeptId(partnerCustomerInfo.getDeptId());
                Long uid = userService.createUser(userSaveReqVO);
                Set<Long> ids = new HashSet<Long>();
                ids.add(sysUser.getId());
                permissionService.assignUserRole(uid,ids);
            }

        }

        partnerCustomerInfo.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updatePartnerCustomerInfo(partnerCustomerInfo);
    }

    /**
     * 批量删除客户信息
     *
     * @param ids 需要删除的客户信息主键
     * @return 结果
     */
    @Override
    public int deletePartnerCustomerInfoByIds(Long[] ids)
    {
        return baseMapper.deletePartnerCustomerInfoByIds(ids);
    }




}
