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

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.jx.payment.entity.PayEntity;
import cn.iocoder.yudao.module.jx.payment.mapper.DrivePayMapper;
import cn.iocoder.yudao.module.jx.payment.utils.PhoneValidator;
import cn.iocoder.yudao.module.jx.payment.utils.SendSmsUtil;
import cn.iocoder.yudao.module.jx.payment.vo.PayNumberVo;
import cn.iocoder.yudao.module.jx.payment.vo.PayVo;
import cn.iocoder.yudao.module.jx.payment.vo.SchoolCourseVo;
import cn.iocoder.yudao.module.jx.utils.DateUtils;
import cn.iocoder.yudao.module.jx.utils.IDCardOCR;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCoach;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCourse;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolInfo;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolReservationCourse;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCoachMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCourseMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolInfoMapper;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolReservationCourseMapper;
import cn.iocoder.yudao.module.jx.service.DrivePayService;
import cn.iocoder.yudao.module.jx.vo.RecentlyDateVo;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.thoughtworks.xstream.core.SecurityUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.*;

@Log4j2
@Service
public class DrivePayServiceImpl implements DrivePayService {

    @Resource
    private DriveSchoolInfoMapper driveSchoolInfoMapper;
    @Resource
    private DriveSchoolCoachMapper driveSchoolCoachMapper;
    @Resource
    private DriveSchoolCourseMapper driveSchoolCourseMapper;
    @Resource
    private DriveSchoolReservationCourseMapper driveSchoolReservationCourseMapper;
    @Resource
    private DrivePayMapper drivePayMapper;
//    @Autowired
//    private ISysUserService userService;

    @Resource
    private AdminUserApi userApi;


    @Override
    public JSONObject infoCardOCR(String imagePath) throws TencentCloudSDKException {
        //imagePath ="https://lift-1313486534.cos.ap-nanjing.myqcloud.com/bsjRescue/imgs/642027e37e3fc03cbe05b08b7c97ba8.jpg";
        JSONObject res =new JSONObject();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        //当前登录用户
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO sysUser = userApi.getUser(userId);
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        SysUser sysUser = userService.selectUserById(loginUser.getUserId());
        String cardInfo = IDCardOCR.dealFunction(imagePath);
        JSONObject infoCardJson =JSONObject.parseObject(cardInfo);
        res.put("name",infoCardJson.getString("Name"));
        res.put("sex",infoCardJson.getString("Sex").equals("男")?"0":"1");
        res.put("idCard",infoCardJson.getString("IdNum"));
        res.put("Address",infoCardJson.getString("Address"));
        //计算年龄
        String birth = infoCardJson.getString("Birth").split("/")[0];
        res.put("age",year-Integer.parseInt(birth));
        res.put("phone",sysUser.getMobile());
        return res;

    }
    @Override
    public Integer insertPayInfo(PayEntity payEntity) {
//        List<DriveSchoolCoach> jlIdList = driveSchoolCoachMapper.selectAllJlId();

//        int currentCoach = (int) Math.floor((Math.random() * jlIdList.size()));
//        DriveSchoolCoach driveSchoolCoach = jlIdList.get(currentCoach);
//        payEntity.setJlId(driveSchoolCoach.getId());
        payEntity.setState(0);


        // 生成 14 位订单号
        Random random = new Random();
        StringBuilder number = new StringBuilder();

        for (int i = 0; i < 14; i++) {
            int randomDigit = random.nextInt(10);
            number.append(randomDigit);
        }
        String randomNumber = number.toString();
        payEntity.setOrderNumber(randomNumber);
        log.info("随机数为 ====================>>> {}", randomNumber);

        Long userId = SecurityFrameworkUtils.getLoginUserId();
        log.info("当前用户id ============>,{}", userId);
        payEntity.setUserId(Math.toIntExact(userId));
        //课程名字
        DriveSchoolCourse driveSchoolCourse = driveSchoolCourseMapper.selectDriveSchoolCourseById(payEntity.getCourseId().longValue());
        payEntity.setCourseName(driveSchoolCourse.getAutomatic());
        if (ObjectUtils.isNotEmpty(payEntity.getJlId())){
            payEntity.setState(3);
        }
        payEntity.setMoney(payEntity.getMoney());
        Integer id = drivePayMapper.insertPayInfo(payEntity);
        return id;
    }

    @Override
    public List<PayVo> findPayListAll(Integer state) {

        List<PayVo> payVoList = drivePayMapper.findPayListAll(SecurityFrameworkUtils.getLoginUserId());
        payVoList.forEach(item -> {
            if (item.getJxId() != null) {
                DriveSchoolInfo driveSchoolInfo = drivePayMapper.findDriveSchoolByJxId(item.getJxId());
                item.setDriveSchoolInfo(driveSchoolInfo);
            }

            if (item.getCourseId() != null) {
                DriveSchoolCourse DriveSchoolCourse = drivePayMapper.findDriveSchoolCourse(item.getCourseId());
                item.setDriveSchoolCourse(DriveSchoolCourse);
            }

            if (item.getJlId() != null) {
                DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectDriveSchoolCoachById(Long.valueOf(item.getJlId()));
                item.setDriveSchoolCoach(driveSchoolCoach);
            }
        });

        return payVoList;

    }

    @Override
    public SchoolCourseVo findPayByBookingId(Long courseId, Long jlId, Long userId) {
        SchoolCourseVo schoolCourseVo = new SchoolCourseVo();

        DriveSchoolCourse driveSchoolCourse = driveSchoolCourseMapper.selectDriveSchoolCourseById(courseId);
        log.info("课程信息为 ================>>> {}", driveSchoolCourse);
        if (driveSchoolCourse != null) {
            schoolCourseVo.setDriveSchoolCourse(driveSchoolCourse);
        }

        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectDriveSchoolCoachById(jlId);
        if (driveSchoolCoach != null) {
            schoolCourseVo.setDriveSchoolCoach(driveSchoolCoach);
        }

        PayEntity payEntity = drivePayMapper.findPayById(userId);
        schoolCourseVo.setPayEntity(payEntity);

        DriveSchoolInfo driveSchoolInfo = driveSchoolInfoMapper.selectDriveSchoolInfoById(Long.valueOf(payEntity.getJxId()));
        schoolCourseVo.setDriveSchoolInfo(driveSchoolInfo);

        return schoolCourseVo;
    }

    /* 获取 选择日期在线人数  */
    @Override
    public PayNumberVo findPayListAllNumber(String currentDate) throws Exception {
        PayNumberVo payNumberVo = new PayNumberVo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < 1; i++) {
            Date date = DateUtils.addDays(new Date(), +i);
            String formatDate = sdf.format(date);
            payNumberVo.setTimePeriod(formatDate);
        }

        if (currentDate == null || currentDate.equalsIgnoreCase("undefined")) {
            currentDate = payNumberVo.getTimePeriod();
        }

        DriveSchoolCoach selfJl = driveSchoolCoachMapper.findSelfJl(SecurityFrameworkUtils.getLoginUserId());
        if (ObjectUtils.isEmpty(selfJl)){
            throw  new Exception("请联系客服分配教练！");
        }
        List<DriveSchoolReservationCourse> courseByCurrentTimeAndJlName = driveSchoolReservationCourseMapper.findCourseByCurrentTimeAndJlName(currentDate, selfJl.getId());

        Integer swCount = 0;
        Integer xwCount = 0;

        for (DriveSchoolReservationCourse item: courseByCurrentTimeAndJlName) {
            if (item.getTimePeriod().equals("0")) {
                swCount ++;
            } else {
                xwCount ++;
            }
        }

        payNumberVo.setSwCount(swCount);
        payNumberVo.setXwCount(xwCount);
        return payNumberVo;
    }

    @Override
    public void insertBookingInfo(String currentDate, Integer period, Integer jlId) {

        Calendar calendar = Calendar.getInstance();

        String[] parts = currentDate.split("-");
        int month = Integer.parseInt(parts[0]);
        int day = Integer.parseInt(parts[1]);

        currentDate = LocalDate.of(calendar.get(Calendar.YEAR), month, day).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

//        DriveSchoolCoach selfJl = driveSchoolCoachMapper.findSelfJl(SecurityFrameworkUtils.getLoginUserId());
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (ObjectUtils.isEmpty(SecurityFrameworkUtils.getLoginUser()) && StringUtils.isNotEmpty(SecurityFrameworkUtils.getLoginUserNickname())){

        }
        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectDriveSchoolCoachById(Long.valueOf(jlId));
        driveSchoolReservationCourseMapper.insertBookingInfo(userId, currentDate, period, driveSchoolCoach.getInstructorName());

//        String formattedTime = currentTime.format(formatter);




        if (PhoneValidator.isValid(driveSchoolCoach.getPhone())) {
            SendSmsUtil.sendMsgCommon(new String[]{SecurityFrameworkUtils.getLoginUserNickname()+"  "+SecurityFrameworkUtils.getLoginUserNickname(),currentDate+" "+(period==1?"上午":"下午")}, driveSchoolCoach.getPhone(),"1400852709","蓝安汽车小程序","2143603");
        }


    }

    @Override
    public DriveSchoolCoach findSelfJl() {

        List<DriveSchoolReservationCourse> courseByUserId = driveSchoolReservationCourseMapper.findCourseByUserId(SecurityFrameworkUtils.getLoginUserId());
////        Long userId = SecurityFrameworkUtils.getLoginUserId();
////        List<DriveSchoolCoach> driveSchoolCoach = driveSchoolCoachMapper.findSelfJl(userId);
////        List<DriveSchoolReservationCourse> courseByUserId = driveSchoolReservationCourseMapper.findCourseByUserId(SecurityFrameworkUtils.getLoginUserId());
////        if (!courseByUserId.isEmpty()) {
////            return driveSchoolCoach.get(0);
////        }
////        return driveSchoolCoach.get(0);
//
//        List<DriveSchoolReservationCourse> courseByUserId = driveSchoolReservationCourseMapper.findCourseByUserId(SecurityFrameworkUtils.getLoginUserId());
//
//        List<DriveSchoolCoach> schoolCoachList = new ArrayList<>();
//
//        courseByUserId.forEach(item -> {
////            item.getCoachName()
//            schoolCoachList.add(driveSchoolCoachMapper.findCoachByCoachName(item.getCoachName()));
//        });
//
//        if (schoolCoachList.isEmpty()) {
//            return null;
//        }
//
//        return schoolCoachList.get(0);

        PayVo payVoData = drivePayMapper.findPayByUserIdOne(SecurityFrameworkUtils.getLoginUserId());

        if (payVoData.getJlId() == null) {
            return null;
        }

        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectDriveSchoolCoachById(Long.valueOf(payVoData.getJlId()));
        return driveSchoolCoach;
    }

    @Override
    public PayVo findSelfInfo() {
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        String avatar = loginUser.getInfo().get("avatar");
        AdminUserRespDTO sysUser = userApi.getUser(SecurityFrameworkUtils.getLoginUserId());
        if (ObjectUtils.isEmpty(sysUser)){
            throw new RuntimeException("请先登录！");
        }
        //SysUser sysUser = userService.selectUserById(SecurityFrameworkUtils.getLoginUserId());
        PayVo payVo = drivePayMapper.findPayByUserId(SecurityFrameworkUtils.getLoginUserId());
       if(ObjectUtils.isNotEmpty(payVo)){
           DriveSchoolCoach coach = driveSchoolCoachMapper.selectDriveSchoolCoachById(Long.parseLong(payVo.getJlId().toString()));
           List<PayVo> currentJlCount = drivePayMapper.findStuCount(coach.getId());
           //学员数
           if (ObjectUtils.isNotEmpty(currentJlCount)){
               coach.setStudent(currentJlCount.size());
           }else {
               coach.setStudent(0);
           }
           DriveSchoolInfo driveSchoolInfo = driveSchoolInfoMapper.selectDriveSchoolInfoById(Long.parseLong(payVo.getJxId().toString()));
           payVo.setDriveSchoolCoach(coach);
           if (ObjectUtils.isNotEmpty(sysUser) && ObjectUtils.isNotEmpty(sysUser.getAvatar())){
               payVo.setUserIcon(sysUser.getAvatar());
           }
           payVo.setUserIcon(sysUser.getAvatar());
           payVo.setDriveSchoolInfo(driveSchoolInfo);
           return payVo;
       }else {
           PayVo payVo1 = new PayVo();
           if (ObjectUtils.isNotEmpty(sysUser) && ObjectUtils.isNotEmpty(sysUser.getAvatar())){
               payVo1.setUserIcon(sysUser.getAvatar());
           }
           payVo1.setName(sysUser.getNickname());
           DriveSchoolCoach coach =new DriveSchoolCoach();
           payVo1.setPhone(sysUser.getMobile());
           payVo1.setDriveSchoolCoach(coach);
           payVo1.setDriveSchoolInfo(new DriveSchoolInfo());
           return payVo1;
       }

    }

    @Override
    public List<RecentlyDateVo> findRecentlyDate() {
        List<RecentlyDateVo> res = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");

        for (int i = 0; i < 7; i++) {
            Date date = DateUtils.addDays(new Date(), +i);
            String formatDate = sdf.format(date);

            LocalDate today = LocalDate.now();
            int dayOfWeek = today.get(ChronoField.DAY_OF_WEEK) % 7;

            RecentlyDateVo re = new RecentlyDateVo();
            re.setDateInfo(formatDate);
            re.setWeekStr(dayOfWeek);

            res.add(re);
            System.out.println("当前数据日期为 ===>" + formatDate);

        }
        log.info("当前日期为 =========> {}", res);
        return res;

    }


}


