package com.cpxt.biz.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cpxt.biz.domain.BizCustomerWarehouse;
import com.cpxt.biz.domain.BizDriverClock;
import com.cpxt.biz.mapper.BizDriverClockMapper;
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.stereotype.Service;
import com.cpxt.biz.mapper.BizDriverMapper;
import com.cpxt.biz.domain.BizDriver;
import com.cpxt.biz.service.IBizDriverService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 司机Service业务层处理
 * 
 * @author YIN
 * @date 2024-12-16
 */
@Service
public class BizDriverServiceImpl implements IBizDriverService 
{
    @Autowired
    private BizDriverMapper bizDriverMapper;

    @Autowired
    private BizDriverClockMapper bizDriverClockMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询司机
     * 
     * @param id 司机主键
     * @return 司机
     */
    @Override
    public BizDriver selectBizDriverById(Long id)
    {
        return bizDriverMapper.selectById(id);
    }

    /**
     * 查询司机列表
     * 
     * @param bizDriver 司机
     * @return 司机
     */
    @Override
    public List<BizDriver> selectBizDriverList(BizDriver bizDriver)
    {
        LambdaQueryWrapper<BizDriver> queryWrapper = buildQueryWrapper(bizDriver);
        List<BizDriver> bizDrivers = bizDriverMapper.selectList(queryWrapper);
        for (BizDriver driver : bizDrivers) {
            LambdaQueryWrapper<BizDriverClock> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(BizDriverClock::getDriverId,driver.getId());
            queryWrapper1.orderByDesc(BizDriverClock::getUpdateTime);
            queryWrapper1.last("limit 1");
            driver.setBizDriverClock(bizDriverClockMapper.selectOne(queryWrapper1));
        }
        return bizDrivers;
    }

    private LambdaQueryWrapper<BizDriver> buildQueryWrapper(BizDriver bizDriver) {
        LambdaQueryWrapper<BizDriver> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotEmpty(bizDriver.getDeptId())){
            queryWrapper.in(BizDriver::getDeptId,sysDeptMapper.selectChildrenDeptById(bizDriver.getDeptId()).stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getUserId())){
            queryWrapper.eq(BizDriver::getUserId, bizDriver.getUserId());
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getName())){
            queryWrapper.like(BizDriver::getName, bizDriver.getName());
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getIdcard())){
            queryWrapper.like(BizDriver::getIdcard, bizDriver.getIdcard());
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getGender())){
            queryWrapper.eq(BizDriver::getGender, bizDriver.getGender());
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getPhone())){
            queryWrapper.like(BizDriver::getPhone, bizDriver.getPhone());
        }
        if (ObjectUtil.isNotEmpty(bizDriver.getDefaultCarNo())){
            queryWrapper.like(BizDriver::getDefaultCarNo, bizDriver.getDefaultCarNo());
        }
        queryWrapper.eq(BizDriver::getStatus,"1");
        return queryWrapper;
    }

    /**
     * 新增司机
     * 
     * @param bizDriver 司机
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBizDriver(BizDriver bizDriver)
    {
        bizDriver.setDeptName(sysDeptMapper.selectDeptById(bizDriver.getDeptId()).getDeptName());
        SysUser sysUser = new SysUser();
        setSysUser(bizDriver,sysUser);
        sysUserMapper.insertUser(sysUser);
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUserId());
        sysUserRole.setRoleId(102L); // 司机
        sysUserRoleMapper.insert(sysUserRole);
        bizDriver.setUserId(sysUser.getUserId());
        int insert = bizDriverMapper.insert(bizDriver);
        // 新增完司机后，创建该司机的行驶轨迹表
        if (insert > 0){
            Long id = bizDriver.getId();
            String tableName = "track_driver_" + id;
            bizDriverMapper.createTable(tableName); // 创建该司机的行驶轨迹表
            bizDriverMapper.addPrimaryKey(tableName); // 添加主键
            bizDriverMapper.setAutoIncrement(tableName); // 设置自增
        }
        return insert;
    }

    private void setSysUser(BizDriver bizDriver, SysUser sysUser) {
        sysUser.setDeptId(bizDriver.getDeptId());
        sysUser.setUserName(bizDriver.getPhone());
        sysUser.setNickName(bizDriver.getName());
        sysUser.setUserType("1"); // 司机
        sysUser.setPhonenumber(bizDriver.getPhone());
        sysUser.setSex(bizDriver.getGender());
        sysUser.setAvatar(bizDriver.getPhoto());
        sysUser.setPassword(bizDriver.getPhone().substring(7,11)); // 18756576807
        sysUser.setAvatar(bizDriver.getPhoto());
    }

    /**
     * 修改司机
     * 
     * @param bizDriver 司机
     * @return 结果
     */
    @Override
    public int updateBizDriver(BizDriver bizDriver)
    {
        if (ObjectUtil.isNotEmpty(bizDriver.getPhoto())){
            SysUser user = sysUserMapper.selectUserById(bizDriver.getUserId());
            user.setAvatar(bizDriver.getPhoto());
            sysUserMapper.updateUser(user);
        }
        return bizDriverMapper.updateById(bizDriver);
    }

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

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