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

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
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.mapper.CustomerCarMapper;
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.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.common.BaseConstants.*;
import static cn.iocoder.yudao.framework.common.config.CommonStr.USER_TYPE_CUS;

/**
 * 客户车辆管理关联
 *
 * @author pqz
 */
@Service
@Validated
public class CustomerCarServiceImpl extends ServiceImpl<CustomerCarMapper, CustomerCar> implements CustomerCarService {

    @Resource
    @Lazy
    private CustomerMainService customerMainService;
    @Resource
    @Lazy
    private CarMainService carMainService;
    @Resource
    @Lazy
    private AdminUserApi adminUserApi;

    /**
     * 保存客户与车辆的关联关系
     *
     * @param mainId       主表id
     * @param mainTable    主表标识（cust：客户，car：车辆）
     * @param customerCars List<CustomerCar>
     * @return void
     * @author PQZ
     * @date 18:45 2024/8/3
     **/
    @Override
    public void bindCustomerCar(String mainId, String mainTable, List<CustomerCar> customerCars) {
        /*1、删除已有关联关系*/
        LambdaQueryWrapper<CustomerCar> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0);
        if (CUS_SIGN_CUSTOMER.equals(mainTable)) {
            //如果主表是客户表
            lambdaQueryWrapper.eq(CustomerCar::getCusId, mainId);
            this.remove(lambdaQueryWrapper);
        } else if(CUS_SIGN_CAR.equals(mainTable)){
            //如果主表是车辆表
            lambdaQueryWrapper.eq(CustomerCar::getCarId, mainId);
            this.remove(lambdaQueryWrapper);
        }

        /*2、保存新关联关系*/
        if (ObjectUtil.isNotEmpty(customerCars) && !customerCars.isEmpty()) {
            customerCars.forEach(item -> {
                //防止主键重复
                item.setId(null);
            });
            this.saveBatch(customerCars);
        }

    }


    /**
     * 保存客户及车辆信息
     *
     * @param saveReqVO CustomerMainSaveReqVO
     * @return void
     * @author PQZ
     * @date 15:51 2024/11/12
     **/
    @Override
    public Map<String,String> saveCustomerAndCar(CustomerMainSaveReqVO saveReqVO) throws Exception {
        Map<String,String> rtnMap = new HashMap<>();
        chekData(saveReqVO);
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        saveReqVO.getCar().setLicenseNumber(saveReqVO.getCar().getLicenseNumber().toUpperCase());
        //用户信息
        AdminUserRespDTO userDTO = adminUserApi.getUserByUsername(saveReqVO.getPhoneNumber());
        if (null == userDTO){
            //客户信息不存在，直接新增客户、新增车辆及绑定关系
            UserDTO user = new UserDTO();
            //如果不存在创建用户；
            user.setUsername(saveReqVO.getPhoneNumber());
            user.setNickname(saveReqVO.getCusName());
            //默认密码
            user.setPassword(PASSWORD_DEFAULT);
            user.setMobile(saveReqVO.getPhoneNumber());
            user.setUserType(USER_TYPE_CUS);
            user.setTenantId(loginUser.getTenantId());
            //创建用户
            Long userId = adminUserApi.createUser(user);
            saveReqVO.setUserId(userId);
            //创建客户信息
            CustomerMain customerMain = BeanUtils.toBean(saveReqVO,CustomerMain.class);
            customerMain.setId(null);
            customerMain.setDataFrom("02");
            customerMainService.save(customerMain);
            //创建车辆信息
            CarMain carMain = saveReqVO.getCar();
            carMain.setUserId(userId);
            carMainService.save(carMain);
            //客户和车的关联关系
            CustomerCar customerCar = new CustomerCar();
            customerCar.setCusId(customerMain.getId());
            customerCar.setCarId(carMain.getId());
            //默认车主
            customerCar.setIsOwner("1");
            this.save(customerCar);
            rtnMap.put("userId",userId.toString());
            rtnMap.put("carId",carMain.getId());
        } else {
            //已有 用户
            Long userId = userDTO.getId();
            saveReqVO.setUserId(userId);
            //查是否存在客户信息
            CustomerMain customerMain = customerMainService.getCustomerByUserId(userId);
            if(null==customerMain){
                //不存在客户信息，新增客户
                customerMain = BeanUtils.toBean(saveReqVO,CustomerMain.class);
                customerMain.setId(null);
                customerMain.setDataFrom("02");
                customerMainService.save(customerMain);
            }
            //根据客户信息+车牌号查这个客户是否已有这个车
            CarMain carMain = carMainService.selectByUserIdAndCarNumber(userId,saveReqVO.getCar().getLicenseNumber());
            if(null==carMain){
                //这个客户不存在这个车辆信息，新增
                carMain = saveReqVO.getCar();
                carMain.setUserId(userId);
                carMainService.save(carMain);
                //客户和车的关联关系
                CustomerCar customerCar = new CustomerCar();
                customerCar.setCusId(customerMain.getId());
                customerCar.setCarId(carMain.getId());
                //默认车主
                customerCar.setIsOwner("1");
                this.save(customerCar);
            }
            rtnMap.put("userId",userId.toString());
            rtnMap.put("carId",carMain.getId());
        }
        return rtnMap;
    }

    private void chekData(CustomerMainSaveReqVO saveReqVO) throws Exception {
        if (StringUtils.isEmpty(saveReqVO.getPhoneNumber())){
            throw new Exception("联系方式不能为空");
        }
        if (StringUtils.isEmpty(saveReqVO.getCusName())){
            throw new Exception("客户姓名不能为空");
        }
        if (saveReqVO.getCar() == null){
            throw new Exception("车辆信息不能为空");
        }
        if (StringUtils.isEmpty(saveReqVO.getCar().getLicenseNumber())){
            throw new Exception("车牌号不能为空");
        }
    }
}