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

import cn.hutool.core.collection.CollectionUtil;
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.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 客户信息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;

    /**
     * 查询客户信息列表
     *
     * @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
    @Transactional(rollbackFor = Exception.class)
    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");

            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);

        }
        if (!StringUtils.isEmpty(partnerCustomerInfo.getCustomerPhone())&&!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();
        if (CollectionUtil.isNotEmpty(userCarList)){
            for (ShopUserCar shopUserCar : userCarList) {
                LambdaQueryWrapper<ShopUserCar> queryWrapper1 =new LambdaQueryWrapper<>();
                queryWrapper1.eq(ShopUserCar::getUserId,user.getId()).eq(ShopUserCar::getCarNo,shopUserCar.getCarNo());
                ShopUserCar one = userCarService.getOne(queryWrapper1);
                if (ObjectUtils.isNotEmpty(one)){
                    //保养日期
                    if (null!=shopUserCar.getMaintenanceDate()){
                        one.setMaintenanceDate(shopUserCar.getMaintenanceDate());
                    }
                    if (null!=shopUserCar.getMaintenanceMileage()){
                        one.setMaintenanceMileage(shopUserCar.getMaintenanceMileage());
                    }
                    if (null!=shopUserCar.getInspectionDate()){
                        one.setInspectionDate(shopUserCar.getInspectionDate());
                    }

                    if (null!=shopUserCar.getInsuranceDate()){
                        one.setInsuranceDate(shopUserCar.getInsuranceDate());
                    }
                    if (null!=shopUserCar.getNextMaintenanceDate()){
                        one.setNextMaintenanceDate(shopUserCar.getNextMaintenanceDate());
                    }
                    if (null!=shopUserCar.getNextMaintenanceMileage()){
                        one.setNextMaintenanceMileage(shopUserCar.getNextMaintenanceMileage());
                    }
                    if (null!=shopUserCar.getNextInspectionDate()){
                        one.setNextInspectionDate(shopUserCar.getNextInspectionDate());
                    }
                    if (null!=shopUserCar.getInsuranceExpiryDate()){
                        one.setInsuranceExpiryDate(shopUserCar.getInsuranceExpiryDate());
                    }
                    userCarService.updateById(one);
                }else {
                    shopUserCar.setUserId(user.getId());
                    userCarService.save(shopUserCar);
                }

            }
        }
        partnerCustomerInfo.setPartnerId(partners.getPartnerId());
        partnerCustomerInfo.setUserId(user.getId());
        return baseMapper.insertPartnerCustomerInfo(partnerCustomerInfo);
    }

    /**
     * 修改客户信息
     *
     * @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);
    }
}
