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.domain.DriveSchoolCoach;
import cn.iocoder.yudao.module.jx.payment.mapper.DrivePayMapper;
import cn.iocoder.yudao.module.jx.payment.vo.PayVo;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
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.IDriveSchoolInfoService;
import cn.iocoder.yudao.module.jx.vo.DriveSchoolInfoVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
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.dept.DeptMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.Comparator;
import java.util.List;

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


/**
 * 驾校信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-19
 */
@Service
public class DriveSchoolInfoServiceImpl implements IDriveSchoolInfoService
{
    @Autowired
    private DriveSchoolInfoMapper driveSchoolInfoMapper;
//    @Autowired
//    private ISysDeptService deptService;
//    @Autowired
//    private ISysUserService userService;
    @Resource
    private DrivePayMapper drivePayMapper;

    @Resource
    private AdminUserApi userApi;

    @Resource
    private DeptMapper deptMapper;


    private static final double EARTH_RADIUS = 6371000; // 地球半径，单位：米

    /**
     * 查询驾校信息
     *
     * @param id 驾校信息主键
     * @return 驾校信息
     */
    @Override
    public DriveSchoolInfo selectDriveSchoolInfoById(Long id)
    {
        return driveSchoolInfoMapper.selectDriveSchoolInfoById(id);
    }

    /**
     * 查询驾校信息列表
     *
     * @param driveSchoolInfo 驾校信息
     * @return 驾校信息
     */
    @Override
    public IPage<DriveSchoolInfo> selectDriveSchoolInfoList(DriveSchoolInfo driveSchoolInfo, Page<DriveSchoolInfo> page)
    {
        return driveSchoolInfoMapper.selectDriveSchoolInfoList(driveSchoolInfo,page);
    }

    @Override
    public IPage<DriveSchoolInfo> selectDriveSchoolInfoAppletList(DriveSchoolInfo driveSchoolInfo,Page<DriveSchoolInfo> page)
    {

        IPage<DriveSchoolInfo> driveSchoolInfoIPage = driveSchoolInfoMapper.selectDriveSchoolInfoList(driveSchoolInfo, page);
        List<DriveSchoolInfo> driveSchoolInfos = driveSchoolInfoIPage.getRecords();

        for (DriveSchoolInfo driveSchoolInfo1 : driveSchoolInfos) {
            if (ObjectUtils.isNotEmpty(driveSchoolInfo.getLat()) &&ObjectUtils.isNotEmpty(driveSchoolInfo.getLgt()) &&
                    ObjectUtils.isNotEmpty(driveSchoolInfo1.getLat()) && ObjectUtils.isNotEmpty(driveSchoolInfo1.getLgt())){
                double lat = driveSchoolInfo1.getLat().doubleValue();
                double lgt = driveSchoolInfo1.getLgt().doubleValue();
                double distance = calculateDistance(driveSchoolInfo.getLat().doubleValue(), driveSchoolInfo.getLgt().doubleValue(), lat, lgt);
                driveSchoolInfo1.setDistance(distance/1000);
            }else {
                driveSchoolInfo1.setDistance(0);
            }
        }
        driveSchoolInfos.sort(Comparator.comparingDouble(DriveSchoolInfo::getDistance));
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
//
//        //获取处理好的list集合
//        int num = driveSchoolInfos.size();
//        driveSchoolInfos = driveSchoolInfos.stream().skip((long) (pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
//        CommonResult<IPage<?>> rspData = new CommonResult<IPage<?>>();
//        rspData.setCode(HttpStatus.SUCCESS);
//        rspData.setRows(driveSchoolInfos);
//        rspData.setTotal(num);
//        return rspData;
        return driveSchoolInfoIPage;
    }

    @Resource
    private AdminUserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserRoleMapper userRoleMapper;
    /**
     * 新增驾校信息
     *
     * @param driveSchoolInfo 驾校信息
     * @return 结果
     */
    @Override
    @Transactional
    public CommonResult insertDriveSchoolInfo(DriveSchoolInfo driveSchoolInfo)
    {
        //部门表新增数据
//        SysDept sysDept = new SysDept();
//        sysDept.setParentId(211L);
//        sysDept.setCreateBy(SecurityUtils.getUsername());
//        sysDept.setStatus("0");
//        sysDept.setLeader(driveSchoolInfo.getLeaderName());
//        sysDept.setDeptName(driveSchoolInfo.getSchoolName());
//        sysDept.setPhone(driveSchoolInfo.getPhone());
//        deptService.insertDept(sysDept);

        DeptDO deptDO = new DeptDO();
        deptDO.setParentId(211L);
        deptDO.setCreator(SecurityFrameworkUtils.getLoginUserNickname());
        deptDO.setStatus(0);
        if (ObjectUtils.isNotEmpty(driveSchoolInfo.getPhone())){
            AdminUserDO users1 = userMapper.selectByMobile(driveSchoolInfo.getPhone());
            if (ObjectUtils.isNotEmpty(users1)){
                deptDO.setLeaderUserId(users1.getId());
            }
        }
        deptDO.setName(driveSchoolInfo.getSchoolName());
        deptDO.setPhone(driveSchoolInfo.getPhone());
        deptMapper.insert(deptDO);
        //用户表新增数据
//        SysUser sysUser = new SysUser();
//        sysUser.setDeptId(sysDept.getDeptId());
//        sysUser.setNickName(driveSchoolInfo.getLeaderName());
//        sysUser.setUserName(driveSchoolInfo.getPhone());
//        sysUser.setPhonenumber(driveSchoolInfo.getPhone());
//        sysUser.setStatus("0");
//        Long[] longs = new Long[1];
//        longs[0] = 124L;
//        sysUser.setRoleIds(longs);
//        sysUser.setRoleId(124L);
//
//        if (!userService.checkUserNameUnique(sysUser))
//        {
//            return CommonResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
//        }
//        else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !userService.checkPhoneUnique(sysUser))
//        {
//            return CommonResult.error("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
//        }
//        sysUser.setCreateBy(SecurityUtils.getUsername());
//        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
//        userService.insertUser(sysUser);

        AdminUserDO adminUserDO = new AdminUserDO();
        adminUserDO.setDeptId(deptDO.getId());
        adminUserDO.setRemark("驾校负责人");
        adminUserDO.setNickname(driveSchoolInfo.getLeaderName());
        adminUserDO.setMobile(driveSchoolInfo.getPhone());
        adminUserDO.setUsername(driveSchoolInfo.getPhone());
        adminUserDO.setStatus(0);
        adminUserDO.setUserType(USER_TYPE_STAFF);

        //校验手机号唯一
        AdminUserDO users1 = userMapper.selectByMobile(driveSchoolInfo.getPhone());
        if (ObjectUtils.isNotEmpty(users1)){
            throw new RuntimeException("新增用户" + driveSchoolInfo.getPhone() + "失败，手机号码已存在");
        }
        AdminUserDO users2 = userMapper.selectByUsername(driveSchoolInfo.getPhone());
        if (ObjectUtils.isNotEmpty(users2)){
            throw new RuntimeException("新增用户" + driveSchoolInfo.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(124L);
        userRoleMapper.insert(entity);
        //驾校信息表新增数据
        driveSchoolInfo.setDeptId(deptDO.getId());
        return CommonResult.success(driveSchoolInfoMapper.insertDriveSchoolInfo(driveSchoolInfo));
    }

    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }
    /**
     * 修改驾校信息
     *
     * @param driveSchoolInfo 驾校信息
     * @return 结果
     */
    @Override
    public int updateDriveSchoolInfo(DriveSchoolInfo driveSchoolInfo)
    {
        //driveSchoolInfo.setUpdateTime(DateUtils.getNowDate());
        return driveSchoolInfoMapper.updateDriveSchoolInfo(driveSchoolInfo);
    }

    /**
     * 批量删除驾校信息
     *
     * @param ids 需要删除的驾校信息主键
     * @return 结果
     */
    @Override
    public int deleteDriveSchoolInfoByIds(Long[] ids)
    {
        return driveSchoolInfoMapper.deleteDriveSchoolInfoByIds(ids);
    }

    /**
     * 删除驾校信息信息
     *
     * @param id 驾校信息主键
     * @return 结果
     */
//    @Resource
//    private SysUserMapper sysUserMapper;
    @Resource
    private DriveSchoolCoachMapper driveSchoolCoachMapper;
    @Override
    public int deleteDriveSchoolInfoById(Long id)
    {
        return driveSchoolInfoMapper.deleteDriveSchoolInfoById(id);
    }

    /**
     * 根据部门id获取驾校信息
     *
     * @return 驾校信息
     */
    @Override
    public DriveSchoolInfoVO getSchoolInfoByDeptId(Long deptId) {
        // 获取驾校信息
        DriveSchoolInfoVO schoolInfoByDeptId = driveSchoolInfoMapper.getSchoolInfoByDeptId(deptId);
        return schoolInfoByDeptId;
    }



    @Override
    public List<PayVo> findSelfSchoolData() {

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        List<PayVo> payVoList = drivePayMapper.findPayByUserIdList(userId);

        payVoList.forEach(item -> {
            DriveSchoolInfo driveSchoolInfo = driveSchoolInfoMapper.selectDriveSchoolInfoById(Long.valueOf(item.getJxId()));
            item.setDriveSchoolInfo(driveSchoolInfo);
        });

        return payVoList;
    }


    /**
     * 计算两个经纬度之间的距离
     * @param lat1
     * @param lon1
     * @param lat2
     * @param lon2
     * @return
     */
    public static double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double dLat = toRadians(lat2 - lat1);
        double dLon = toRadians(lon2 - lon1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
                        Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        double distance = EARTH_RADIUS * c;
        return distance;
    }
    private static double toRadians(double degrees) {
        return degrees * Math.PI / 180;
    }
}
