package com.cpxt.biz.service.impl;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpxt.biz.domain.BizCarModel;
import com.cpxt.common.core.domain.entity.SysDept;
import com.cpxt.common.core.domain.entity.SysUser;
import com.cpxt.common.utils.DateUtils;
import com.cpxt.system.domain.SysUserRole;
import com.cpxt.system.mapper.SysDeptMapper;
import com.cpxt.system.mapper.SysUserMapper;
import com.cpxt.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import com.cpxt.biz.mapper.BizCustomerMapper;
import com.cpxt.biz.domain.BizCustomer;
import com.cpxt.biz.service.IBizCustomerService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户Service业务层处理
 * 
 * @author YIN
 * @date 2024-12-16
 */
@Service
public class BizCustomerServiceImpl implements IBizCustomerService 
{
    @Autowired
    private BizCustomerMapper bizCustomerMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询客户
     * 
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public BizCustomer selectBizCustomerById(Long id)
    {
        return bizCustomerMapper.selectById(id);
    }

    /**
     * 查询客户列表（分页）
     *
     * @param bizCustomer 客户
     * @return 客户
     */
    @Override
    public Page<BizCustomer> selectBizCustomerPage(BizCustomer bizCustomer, int pageNum, int pageSize) {
        LambdaQueryWrapper<BizCustomer> queryWrapper = buildQueryWrapper(bizCustomer);
        return bizCustomerMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper);
    }

    private LambdaQueryWrapper<BizCustomer> buildQueryWrapper(BizCustomer bizCustomer) {
        LambdaQueryWrapper<BizCustomer> queryWrapper= new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(bizCustomer.getName())){
            queryWrapper.like(BizCustomer::getName, bizCustomer.getName());
        }
        if (ObjectUtil.isNotEmpty(bizCustomer.getLinkman())){
            queryWrapper.like(BizCustomer::getLinkman, bizCustomer.getLinkman());
        }
        if (ObjectUtil.isNotEmpty(bizCustomer.getLinkphone())){
            queryWrapper.like(BizCustomer::getLinkphone, bizCustomer.getLinkphone());
        }
        if (ObjectUtil.isNotEmpty(bizCustomer.getLevel())){
            queryWrapper.eq(BizCustomer::getLevel, bizCustomer.getLevel());
        }
        queryWrapper.eq(BizCustomer::getStatus,1);
        return queryWrapper;
    }

    /**
     * 查询客户列表
     * 
     * @param bizCustomer 客户
     * @return 客户
     */
    @Override
    public List<BizCustomer> selectBizCustomerList(BizCustomer bizCustomer)
    {
        LambdaQueryWrapper<BizCustomer> queryWrapper = buildQueryWrapper(bizCustomer);
        return bizCustomerMapper.selectList(queryWrapper);
    }

    /**
     * 新增客户
     * 
     * @param bizCustomer 客户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBizCustomer(BizCustomer bizCustomer)
    {
        Long parentId = sysDeptMapper.selectDeptIdByDeptName("外部单位");
        Long aLong = sysDeptMapper.selectDeptIdByDeptName(bizCustomer.getName());
        SysDept sysDept = new SysDept();
        if (ObjectUtil.isEmpty(aLong)){
            // 同步创建一个部门，名称为客户名称
            sysDept.setParentId(parentId);
            sysDept.setAncestors("0," + parentId);
            sysDept.setDeptName(bizCustomer.getName());
            sysDeptMapper.insertDept(sysDept);
            sysDept.setDeptId(sysDeptMapper.selectDeptIdByDeptName(bizCustomer.getName()));
        }else {
            sysDept.setDeptId(aLong);
        }
        // 同步新增一个用户
        SysUser user = sysUserMapper.selectUserByUserName(bizCustomer.getLinkphone());
        if (ObjectUtil.isEmpty(user)){
            SysUser sysUser = new SysUser();
            setSysUser(bizCustomer,sysUser,sysDept);
            sysUserMapper.insertUser(sysUser);

            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(101L); // 大客户
            sysUserRoleMapper.insert(sysUserRole);
        }
        return bizCustomerMapper.insert(bizCustomer);
    }

    private void setSysUser(BizCustomer bizCustomer, SysUser sysUser, SysDept sysDept) {
        sysUser.setDeptId(sysDept.getDeptId());
        sysUser.setUserName(bizCustomer.getLinkphone());
        sysUser.setNickName(bizCustomer.getName());
        sysUser.setUserType("2"); // 客户
        sysUser.setPhonenumber(bizCustomer.getLinkphone());
        sysUser.setPassword(bizCustomer.getLinkphone().substring(7,11)); // 18756576807
    }

    /**
     * 修改客户
     * 
     * @param bizCustomer 客户
     * @return 结果
     */
    @Override
    public int updateBizCustomer(BizCustomer bizCustomer)
    {
        return bizCustomerMapper.updateById(bizCustomer);
    }

    /**
     * 批量删除客户
     * 
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBizCustomerByIds(Long[] ids)
    {
        // 删除客户对应的用户
        for (Long id : ids) {
            BizCustomer bizCustomer = bizCustomerMapper.selectById(id);
            sysUserMapper.deleteByUserName(bizCustomer.getLinkphone());
        }
        UpdateWrapper<BizCustomer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", (Object[]) ids);
        updateWrapper.set("status","2"); //状态改为删除
        return bizCustomerMapper.update(null,updateWrapper);
    }

    /**
     * 删除客户信息
     * 
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteBizCustomerById(Long id)
    {
        UpdateWrapper<BizCustomer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id);
        updateWrapper.set("status","2"); //状态改为删除
        return bizCustomerMapper.update(null,updateWrapper);
    }
}
