package com.ruoyi.basicData.service.impl;

import com.ruoyi.basicData.domain.FleetCarManage;
import com.ruoyi.basicData.domain.FleetDriverMsg;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.mapper.FleetCarManageMapper;
import com.ruoyi.basicData.mapper.FleetDriverMsgMapper;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.service.IFleetDriverMsgService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.orderPlan.domain.Ftmsorderbillscars;
import com.ruoyi.orderPlan.mapper.FtmsorderbillscarsMapper;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 【司机】Service业务层处理
 *
 * @author ruoyi
 * @date 2021-03-04
 */
@Service
public class FleetDriverMsgServiceImpl implements IFleetDriverMsgService {
    @Autowired
    private TCorpsMapper corpsMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private FleetDriverMsgMapper fleetDriverMsgMapper;

    @Autowired
    private FleetCarManageMapper fleetCarManageMapper;

    @Autowired
    private FtmsorderbillscarsMapper ftmsorderbillscarsMapper;

    /**
     * 查询【司机】
     *
     * @param id 【司机】ID
     * @return 【司机】
     */
    @Override
    public TCorps selectFleetDriverMsgById(Long id) {
        return corpsMapper.selectTCorpsById(id);
    }

    /**
     * 查询【司机】列表
     *
     * @param fleetDriverMsg 【司机】
     * @return 【司机】
     */
    @Override
    public List<FleetDriverMsg> selectFleetDriverMsgList(FleetDriverMsg fleetDriverMsg) {
        return fleetDriverMsgMapper.selectFleetDriverMsgList(fleetDriverMsg);
    }

    @Override
    public List<Map<String, Object>> selectFleetDriverMsgListMap(FleetDriverMsg fleetDriverMsg) {
        return fleetDriverMsgMapper.selectFleetDriverMsgListMap(fleetDriverMsg);
    }

    /**
     * 新增【司机】
     *
     * @param tCorps 【司机】
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertFleetDriverMsg(TCorps tCorps) {
        // 检验必填
        if (StringUtils.isNull(tCorps.getfPid()) ||
                StringUtils.isNull(tCorps.getfName())) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("请填写必输项");
        }
        SysDept dept = sysDeptMapper.selectDeptByDeptName("外部用户");
        if (StringUtils.isNull(dept)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未找到部门信息，请添加后再提交");
        }
        String typeValue = "[\"102\"]";
        tCorps.setfTypeid(typeValue);
        tCorps.setfTypename("司机");
        tCorps.setfStatus("0");
        if (null != tCorps.getfId()) {
//            updateDriverPhone(tCorps);
            AjaxResult result = updateFleetCarManagePhone(tCorps, dept);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return result;
            }
            tCorps.setUpdateTime(new Date());
            tCorps.setUpdateBy(SecurityUtils.getUsername());
            corpsMapper.updateTCorps(tCorps);
            return AjaxResult.success();
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(tCorps.getfTel());
            sysUser.setPhonenumber(tCorps.getfTel());
            SysUser userPhone = userMapper.checkPhoneUnique(sysUser.getPhonenumber());
            if (StringUtils.isNotNull(userPhone)) {
                return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
            } else if (userMapper.checkUserNameUnique(sysUser.getUserName()) > 1) {
                return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
            }
            long userId = 0L;
            // 查询是否有用户提前关注小程序
            SysUser user = userMapper.selectUserByTel(tCorps.getfTel());
            if (StringUtils.isNotNull(user)) {
                // 该用户提前关注小程序了
                user.setStatus("1");
                user.setRelatedNo("T");
                user.setUserSystem("2");
                user.setUpdateTime(new Date());
                user.setDeptId(dept.getDeptId());
                user.setNickName(tCorps.getfName());
                user.setUpdateBy(SecurityUtils.getUsername());
                user.setPassword(SecurityUtils.encryptPassword(tCorps.getfTel()));
                userMapper.updateUser(user);
                userId = user.getUserId();
            } else {
                // 添加用户表
                SysUser use = new SysUser();
                use.setStatus("1");
                use.setUserSystem("2");
                use.setDeptId(dept.getDeptId());
                use.setUserName(tCorps.getfTel());
                use.setNickName(tCorps.getfTel());
                use.setPhonenumber(tCorps.getfTel());
                //sysUser.setEmail(fleetDriverMsg.get);
                use.setUserType("11");
                use.setPassword(SecurityUtils.encryptPassword(tCorps.getfTel()));
                // 新增用户信息
                userMapper.insertUser(use);
                userId = use.getUserId();
            }
            // 新增用户与角色管理
            // 查询是否存在车队 角色
            SysRole role = roleMapper.selectRoleByName("车队司机");
            if (StringUtils.isNull(role)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("未找到司机角色，请创建司机角色后提交");
            }
            // 创建用户与角色关联
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(role.getRoleId());
            sysUserRole.setUserId(userId);
            list.add(sysUserRole);
            userRoleMapper.batchUserRole(list);
            tCorps.setCreateTime(new Date());
            tCorps.setCreateBy(SecurityUtils.getUsername());
            corpsMapper.insertTCorps(tCorps);
            return AjaxResult.success();
        }
    }

    @Transactional
    public void updateDriverPhone(TCorps tCorps) {
        TCorps corps = corpsMapper.selectTCorpsById(tCorps.getfId());
        SysUser sysUser = userMapper.selectUserByTel(corps.getfTel());
        if (StringUtils.isNotNull(sysUser)) {
            boolean updateStatus = false;
            // 跟新用户手机号以及姓名
            if (!sysUser.getPhonenumber().equals(tCorps.getfTel())) {
                updateStatus = true;
                sysUser.setPhonenumber(tCorps.getfTel());
            }
            if (!sysUser.getNickName().equals(tCorps.getfTel())) {
                updateStatus = true;
                sysUser.setNickName(tCorps.getfTel());
            }
            if (updateStatus) {
                sysUser.setUpdateTime(new Date());
                sysUser.setUpdateBy(SecurityUtils.getUsername());
                userMapper.updateUser(sysUser);
            }
        }
        // 更新司机表手机号以及姓名
        ftmsorderbillscarsMapper.updateftmsorderbillscarsDriverNamePhone();
    }

    @Transactional
    public AjaxResult updateFleetCarManagePhone(TCorps tCorps, SysDept dept) {
        TCorps corps = corpsMapper.selectTCorpsById(tCorps.getfId());
        SysUser sysUser = userMapper.selectUserByTel(corps.getfTel());
        if (StringUtils.isNotNull(sysUser)) {
            SysUser user = new SysUser();
            // 跟新用户手机号以及姓名
            sysUser.setNickName(tCorps.getfName());
            if (!sysUser.getPhonenumber().equals(tCorps.getfTel())) {
                user.setStatus("1");
                user.setUserType("11");
                user.setUserSystem("2");
                user.setDeptId(dept.getDeptId());
                user.setUserName(tCorps.getfTel());
                user.setNickName(tCorps.getfName());
                user.setPhonenumber(tCorps.getfTel());
                user.setPassword(SecurityUtils.encryptPassword(tCorps.getfTel()));
                user.setCreateTime(new Date());
                user.setCreateBy(SecurityUtils.getUsername());
                userMapper.insertUser(user);
                // 查询是否存在车队 角色
                SysRole role = roleMapper.selectRoleByName("外部用户");
                if (StringUtils.isNull(role)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("未找到司机角色，请创建司机角色后提交");
                }
                // 创建用户与角色关联
                List<SysUserRole> list = new ArrayList<SysUserRole>();
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(role.getRoleId());
                sysUserRole.setUserId(user.getUserId());
                list.add(sysUserRole);
                userRoleMapper.batchUserRole(list);
            }
            sysUser.setUpdateTime(new Date());
            sysUser.setDeptId(dept.getDeptId());
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            userMapper.updateUser(sysUser);
        }
        //  变更还柜状态
        Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
        ftmsorderbillscars.setDriverTel(tCorps.getfTel());
        ftmsorderbillscars.setDriverUserId(tCorps.getfId());
        ftmsorderbillscars.setDriverName(tCorps.getfName());
        ftmsorderbillscarsMapper.updateftmsorderbillscarTel(ftmsorderbillscars);
        //  变更车辆数据
        FleetCarManage fleetCarManage = new FleetCarManage();
        fleetCarManage.setDriverId(tCorps.getfId());
        fleetCarManage.setDriverTel(tCorps.getfTel());
        fleetCarManage.setDriverName(tCorps.getfName());
        fleetCarManageMapper.updateFleetCarManageByDriverId(fleetCarManage);
        return AjaxResult.success();
    }


    /**
     * 修改【司机】
     *
     * @param fleetDriverMsg 【司机】
     * @return 结果
     */
    @Override
    public int updateFleetDriverMsg(FleetDriverMsg fleetDriverMsg) {
        fleetDriverMsg.setUpdateTime(DateUtils.getNowDate());
        String tel = fleetDriverMsg.getTel();
        return fleetDriverMsgMapper.updateFleetDriverMsg(fleetDriverMsg);
    }

    /**
     * 批量删除【司机】
     *
     * @param ids 需要删除的【司机】ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteFleetDriverMsgByIds(Long[] ids) {
        int line = 0;
        for (Long id : ids) {
            line++;
            TCorps corps = corpsMapper.selectTCorpsById(id);
            Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
            ftmsorderbillscars.setDriverTel(corps.getfTel());
            ftmsorderbillscars.setDriverName(corps.getfName());
            if (ftmsorderbillscarsMapper.selectftmsorderbillscarsCount(ftmsorderbillscars) > 0) {
                return AjaxResult.error("第" + line + "行数据已被使用无法删除");
            }
            corpsMapper.deleteTCorpsById(id);
            SysUser sysUser = userMapper.selectUserByUserName(corps.getfTel());
            userMapper.deleteUserById(sysUser.getUserId());
            userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
        }
        return AjaxResult.success();
    }

    /**
     * 删除【司机】信息
     *
     * @param id 【司机】ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFleetDriverMsgById(Long id) {
        TCorps corps = corpsMapper.selectTCorpsById(id);
        SysUser sysUser = userMapper.selectUserByUserName(corps.getfTel());
        userMapper.deleteUserById(sysUser.getUserId());
        userRoleMapper.deleteUserRoleByUserId(sysUser.getUserId());
        return corpsMapper.deleteTCorpsById(id);
    }

    /**
     * 下拉框查询【司机】id、name列表
     *
     * @param tCorps 条件
     * @return 结果
     */
    @Override
    public List<TCorps> selectFleetDriverMsgIdNameList(TCorps tCorps) {
        return corpsMapper.selectTCorpsList(tCorps);
    }

}
