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

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jx.payment.mapper.DriveSchoolPayMapper;
import cn.iocoder.yudao.module.jx.utils.DateUtils;
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.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCoach;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolInfo;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCoachMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolInfoMapper;
import cn.iocoder.yudao.module.jx.service.IDriveSchoolCoachService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thoughtworks.xstream.core.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.yudao.framework.common.config.CommonStr.USER_TYPE_STAFF;

/**
 * 驾校教练Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-29
 */
//@Log4j2
@Service
public class DriveSchoolCoachServiceImpl implements IDriveSchoolCoachService
{
    @Autowired
    private DriveSchoolCoachMapper driveSchoolCoachMapper;
    @Resource
    private DriveSchoolInfoMapper driveSchoolInfoMapper;
//    @Autowired
//    private ISysUserService userService;

    @Resource
    private AdminUserApi userApi;

    @Resource
    private AdminUserMapper userMapper;

    @Resource
    private DriveSchoolPayMapper driveSchoolPayMapper;

    /**
     * 查询驾校教练
     *
     * @param id 驾校教练主键
     * @return 驾校教练
     */
    @Override
    public DriveSchoolCoach selectDriveSchoolCoachById(Long id)
    {
        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectDriveSchoolCoachById(id);
        if (ObjectUtils.isNotEmpty(driveSchoolCoach) && ObjectUtils.isNotEmpty(driveSchoolCoach.getSubjectType())){
            String[] split = driveSchoolCoach.getSubjectType().split(",");
            driveSchoolCoach.setSubjectTypeList(split);
        }
        return driveSchoolCoach;
    }

    /**
     * 查询驾校教练列表
     *
     * @param driveSchoolCoach 驾校教练
     * @return 驾校教练
     */
    @Override
    public IPage<DriveSchoolCoach> selectDriveSchoolCoachList(DriveSchoolCoach driveSchoolCoach, Page<DriveSchoolCoach> page)
    {

        IPage<DriveSchoolCoach> driveSchoolCoachIPage = driveSchoolCoachMapper.selectDriveSchoolCoachList(driveSchoolCoach, page);
        List<DriveSchoolCoach> driveSchoolCoaches = driveSchoolCoachIPage.getRecords();
        for (DriveSchoolCoach schoolCoach : driveSchoolCoaches) {
            Integer integer = driveSchoolPayMapper.selectByCoachId(schoolCoach.getId());
            schoolCoach.setStudent(integer);
            if (ObjectUtils.isNotEmpty(schoolCoach.getSubjectType())){
                String[] split = schoolCoach.getSubjectType().split(",");
                schoolCoach.setSubjectTypeList(split);
            }
        }
        return driveSchoolCoachIPage;
    }

//    @Override
//    public List<DriveSchoolCoach> selectDriveSchoolCoachListAll(DriveSchoolCoach driveSchoolCoach)
//    {
//
//        List<DriveSchoolCoach> driveSchoolCoaches = driveSchoolCoachMapper.selectDriveSchoolCoachListAll(driveSchoolCoach);
//        for (DriveSchoolCoach schoolCoach : driveSchoolCoaches) {
//            Integer integer = driveSchoolPayMapper.selectByCoachId(schoolCoach.getId());
//            schoolCoach.setStudent(integer);
//            if (ObjectUtils.isNotEmpty(schoolCoach.getSubjectType())){
//                String[] split = schoolCoach.getSubjectType().split(",");
//                schoolCoach.setSubjectTypeList(split);
//            }
//        }
//        return driveSchoolCoaches;
//    }



    @Resource
    private AdminUserService adminUserService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRoleMapper userRoleMapper;


    /**
     * 新增驾校教练
     *
     * @param driveSchoolCoach 驾校教练
     * @return 结果
     */
    @Override
    @Transactional
    public void insertDriveSchoolCoach(DriveSchoolCoach driveSchoolCoach)
    {
            Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        Long deptId = user.getDeptId();
//        SecurityFrameworkUtils.getLoginUserId()
        // 用户表新增数据
        AdminUserDO adminUserDO = new AdminUserDO();
        adminUserDO.setDeptId(deptId);
        adminUserDO.setRemark("驾校教练");
        adminUserDO.setNickname(driveSchoolCoach.getInstructorName());
        adminUserDO.setMobile(driveSchoolCoach.getPhone());
        adminUserDO.setUsername(driveSchoolCoach.getPhone());
        adminUserDO.setStatus(0);
//        SysUser sysUser = new SysUser();
//        sysUser.setDeptId(deptId);
//        sysUser.setRemark("驾校教练");
//        sysUser.setNickName(driveSchoolCoach.getInstructorName());
//        sysUser.setUserName(driveSchoolCoach.getPhone());
//        sysUser.setPhonenumber(driveSchoolCoach.getPhone());
//        sysUser.setStatus("0");
//        Long[] longs = new Long[1];
//        longs[0] = 102L;
//        sysUser.setRoleIds(longs);
//        sysUser.setRoleId(102L);

        //默认员工
        adminUserDO.setUserType(USER_TYPE_STAFF);

        //校验手机号唯一
        AdminUserDO users1 = userMapper.selectByMobile(driveSchoolCoach.getPhone());
        if (ObjectUtils.isNotEmpty(users1)){
            throw new RuntimeException("新增用户" + driveSchoolCoach.getPhone() + "失败，手机号码已存在");
        }
        AdminUserDO users2 = userMapper.selectByUsername(driveSchoolCoach.getPhone());
        if (ObjectUtils.isNotEmpty(users2)){
            throw new RuntimeException("新增用户" + driveSchoolCoach.getPhone() + "失败，账号已存在");
        }
        adminUserDO.setPassword(encodePassword("123456")); // 加密密码
//        sysUser.setCreateBy(SecurityUtils.getUsername());
//        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
//        userService.insertUser(sysUser);
        userMapper.insert(adminUserDO);
        //角色
        UserRoleDO entity = new UserRoleDO();
        entity.setUserId(adminUserDO.getId());
        entity.setRoleId(102L);
        userRoleMapper.insert(entity);

        String[] subjectTypeList = driveSchoolCoach.getSubjectTypeList();
        String  subjectType = "";
        for (String s : subjectTypeList) {
            subjectType = s + ",";
        }
        driveSchoolCoach.setSubjectType(subjectType);
        int i = driveSchoolCoachMapper.insertDriveSchoolCoach(driveSchoolCoach);
    }
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }
    /**
     * 修改驾校教练
     *
     * @param driveSchoolCoach 驾校教练
     * @return 结果
     */
    @Override
    public int updateDriveSchoolCoach(DriveSchoolCoach driveSchoolCoach)
    {
       // driveSchoolCoach.setUpdateTime(DateUtils.getNowDate());
        String[] subjectTypeList = driveSchoolCoach.getSubjectTypeList();
        String subjectType = "";
        for (String s : subjectTypeList) {
            subjectType+=s+",";
        }
        driveSchoolCoach.setSubjectType(subjectType);
        return driveSchoolCoachMapper.updateDriveSchoolCoach(driveSchoolCoach);
    }

    /**
     * 批量删除驾校教练
     *
     * @param ids 需要删除的驾校教练主键
     * @return 结果
     */
    @Override
    public int deleteDriveSchoolCoachByIds(Long[] ids)
    {
        return driveSchoolCoachMapper.deleteDriveSchoolCoachByIds(ids);
    }

    /**
     * 删除驾校教练信息
     *
     * @param id 驾校教练主键
     * @return 结果
     */
    @Override
    public int deleteDriveSchoolCoachById(Long id)
    {
        return driveSchoolCoachMapper.deleteDriveSchoolCoachById(id);
    }

    @Override
    public List<DriveSchoolCoach> selectDriveSchoolCoachLimitList(DriveSchoolCoach driveSchoolCoach) {
        List<DriveSchoolCoach> driveSchoolCoaches = driveSchoolCoachMapper.selectDriveSchoolCoachListAll(driveSchoolCoach);
        if (CollectionUtils.isNotEmpty(driveSchoolCoaches) && driveSchoolCoaches.size()>2){
            return driveSchoolCoaches.subList(0, 2);
        }
        return driveSchoolCoaches;
    }

    @Override
    public List<DriveSchoolCoach> selectDriveSchoolCoachListAll(@Param("entity") DriveSchoolCoach driveSchoolCoach) {
        // 检查driveSchoolCoach是否为null
        if (driveSchoolCoach == null) {
            return Collections.emptyList(); // 返回空列表，或者可以根据需求抛出异常
        }

        return driveSchoolCoachMapper.selectDriveSchoolCoachListAll(driveSchoolCoach);
    }


    @Override
    public List<DriveSchoolCoach> findSelfJlListByJxId(Long jxId) {
        DriveSchoolInfo jxInfoData = driveSchoolInfoMapper.findInfoByJxId(jxId);
        List<DriveSchoolCoach> schoolCoachList = driveSchoolCoachMapper.findJlByDeptId(jxInfoData.getDeptId());
        return schoolCoachList;
    }
}
