package com.ruoyi.applet.contoller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyl.manager.staff.domain.vo.StaffVO;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.service.MemberWechatService;
import com.ruoyi.applet.mallpojo.TeacherListRequest;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.model.domain.*;
import com.ruoyi.model.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Api(description = "下单小程序端 - 派单指定相关接口")
@RestController
@RequestMapping("/applet/mall/teacher")
public class ApiMallUserTeacherController extends BaseController {

    @Autowired
    private IAppUsersService appUsersService;
    @Autowired
    private IAppletUsersTeacherService appletUsersTeacherService;
    @Autowired
    private IAppletConfigService appletConfigService;
    @Autowired
    private IAppletAddressService appletAddressService;
    @Autowired
    private IAppletOutDateService appletOutDateService;
    @Autowired
    private IOmsOrderEvaluationService omsOrderEvaluationService;
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberWechatService memberWechatService;

    @Autowired
    private IAApiAppletHhrWorkOutService apiAppletHhrWorkOutService;

    //mall-首页周边伴宠师
    @ApiOperation("mall-首页周边伴宠师接口")
    @GetMapping("/getTeacherListIndex")
    public TableDataInfo getTeacherListIndex() {
        startPage();
        AppUsers appUsers = new AppUsers();
        appUsers.setUserBcs(1);
        List<AppUsers> appUsersList = appUsersService.selectAppUsersList(appUsers);
        for (AppUsers appUsers1 : appUsersList){
            AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUsers1.getUserId());
            appUsers1.setAppletUsersTeacher(appletUsersTeacher);

            AppletAddress appletAddress = new AppletAddress();
            appletAddress.setUserId(appUsers.getUserId());
            List<AppletAddress> appletAddresses = appletAddressService.selectAppletAddressList(appletAddress);
            appUsers.setAppletAddresseList(appletAddresses);
        }
        return getDataTable(appUsersList);
    }





    //mall端-查询周边伴宠师集合
    @ApiOperation("mall端-查询周边伴宠师列表集合接口")
    @GetMapping("/getTeacherList")
    public TableDataInfo getTeacherList(TeacherListRequest request) {
        startPage();
        AppUsers appUsers = new AppUsers();
        appUsers.setUserBcs(1);



        //如果伴宠师等级传入
        if (request.getTeacherLevels() != null) {
            appUsers.setUserBcsRole(request.getTeacherLevels());
        }
        //如果传入staffName
        if (request.getStaffName() != null) {
            appUsers.setUserName(request.getStaffName());
        }


        String petType =request.getPetTypes();


        List<AppUsers> appUsersList = appUsersService.selectAppUsersList(appUsers);
        List<AppUsers> appUsersListNew = new ArrayList<>();
        for (AppUsers appUsers1 : appUsersList){


            AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUsers1.getUserId());
            appUsers1.setAppletUsersTeacher(appletUsersTeacher);

            AppletAddress appletAddress = new AppletAddress();
            appletAddress.setUserId(appUsers1.getUserId());
            List<AppletAddress> appletAddresses = appletAddressService.selectAppletAddressList(appletAddress);
            appUsers1.setAppletAddresseList(appletAddresses);



            //如果经纬度不为空
            if (request.getLatitude() != null && request.getLongitude() != null) {
                //查询该经纬度下3-15公里内的接单地址
                for (AppletAddress address : appletAddresses) {









                    if (address.getLatitude() != null && address.getLongitude() != null) {
                        //计算距离
                        Double distance = getDistance(
                                Double.parseDouble(request.getLatitude()),
                                Double.parseDouble(request.getLongitude()),
                                Double.parseDouble(address.getLatitude()),
                                Double.parseDouble(address.getLongitude())
                        );



                        //如果距离在3-15公里内
                        if (distance <= 100) {
                            // 检查appUsers1是否已经存在于appUsersListNew中
                            if (!appUsersListNew.contains(appUsers1)) {
                                appUsers1.setDistance(distance);
                                //如果性别不为空
                                if (request.getSex() != null) {
                                    //判断性别跟查出来的性别相同
                                    if (request.getSex().equals(appletUsersTeacher.getSex())) {
                                        if (!appUsersListNew.contains(appUsers1)) {
                                            appUsersListNew.add(appUsers1);
                                        }
                                    }
                                }else{
                                    if (!appUsersListNew.contains(appUsers1)) {
                                        appUsersListNew.add(appUsers1);
                                    }
                                }

                                // 如果写入了接单日期
                                if (request.getSelectedDate() != null) {
                                    // 创建一个AppletOutDate对象
                                    AppletOutDate appletOutDate = new AppletOutDate();
                                    appletOutDate.setAddressId(address.getId());

                                    // 获取不接单日期列表
                                    List<AppletOutDate> appletOutDates = appletOutDateService.selectAppletOutDateList(appletOutDate);

                                    // 创建一个SimpleDateFormat对象，用于格式化日期
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

                                    // 提取不接单日期字符串列表
                                    List<String> outDates = new ArrayList<>();
                                    for (AppletOutDate outDate : appletOutDates) {
                                        Date date = outDate.getDate(); // 假设AppletOutDate有一个getDate()方法
                                        if (date != null) {
                                            outDates.add(dateFormat.format(date)); // 将Date格式化为字符串
                                        }
                                    }

                                    // 分割request.getSelectedDate()为多个日期
                                    String[] selectedDates = request.getSelectedDate().split(",");

                                    // 初始化一个标志，用于判断是否所有日期都不在不接单日期列表中
                                    boolean allDatesValid = true;

                                    // 检查每个日期是否不在不接单日期列表中
                                    for (String selectedDate : selectedDates) {
                                        if (outDates.contains(selectedDate.trim())) {
                                            allDatesValid = false;
                                            break;
                                        }
                                    }

                                    // 如果所有日期都不在不接单日期列表中，并且appUsers1不在列表中，则添加
                                    if (allDatesValid) {
                                        if (!appUsersListNew.contains(appUsers1)) {
                                            appUsersListNew.add(appUsers1);
                                        }
                                    } else {
                                        // 如果至少有一个日期在不接单日期列表中，检查并删除appUsers1
                                        if (appUsersListNew.contains(appUsers1)) {
                                            appUsersListNew.remove(appUsers1);
                                        }
                                    }
                                }



                                // 假设 petType 是一个字符串，格式为 "3,4,5"
                                if (petType != null && appletUsersTeacher != null && appletUsersTeacher.getPetType() != null) {
                                    // 将 petType 分割为字符串数组
                                    String[] petTypes = petType.split(",");

                                    // 遍历分割后的数组，检查是否包含 appletUsersTeacher.getPetType()
                                    boolean containsPetType = false;
                                    for (String type : petTypes) {
                                        if (type.trim().equals(appletUsersTeacher.getPetType())) {
                                            containsPetType = true;
                                            break;
                                        }
                                    }

                                    if (containsPetType) {
                                        // 如果包含，检查是否已存在于列表中，不存在则添加
                                        if (!appUsersListNew.contains(appUsers1)) {
                                            appUsersListNew.add(appUsers1);
                                        }
                                    } else {
                                        // 如果不包含，检查是否存在并删除
                                        if (appUsersListNew.contains(appUsers1)) {
                                            appUsersListNew.remove(appUsers1);
                                        }
                                    }
                                } else {
                                    // 如果 petType 为空，或者 appletUsersTeacher 或其 getPetType() 为空，则检查并添加 appUsers1
                                    if (!appUsersListNew.contains(appUsers1)) {
                                        appUsersListNew.add(appUsers1);
                                    }
                                }


                            }

                        }
                    }

                }
            }else {
                appUsersListNew.add(appUsersList.get(0));
            }

        }

        for (AppUsers users : appUsersListNew) {
            users.setEvaluationNum(omsOrderEvaluationService.lambdaQuery()
                    .eq(OmsOrderEvaluation::getTechnicianId, users.getUserHh()).count());
        }

        return getDataTable(appUsersListNew);
    }



    /**
     * 计算两个经纬度之间的距离（单位：公里）
     * @param lat1 第一个点的纬度
     * @param lon1 第一个点的经度
     * @param lat2 第二个点的纬度
     * @param lon2 第二个点的经度
     * @return 两点之间的距离（公里）
     */
    public static double getDistance(double lat1, double lon1, double lat2, double lon2) {
        // 地球半径（公里）
        final int EARTH_RADIUS = 6371;

        // 将经纬度转换为弧度
        double lat1Rad = Math.toRadians(lat1);
        double lon1Rad = Math.toRadians(lon1);
        double lat2Rad = Math.toRadians(lat2);
        double lon2Rad = Math.toRadians(lon2);

        // 计算纬度差和经度差
        double latDiff = lat2Rad - lat1Rad;
        double lonDiff = lon2Rad - lon1Rad;

        // Haversine公式计算
        double a = Math.pow(Math.sin(latDiff / 2), 2) +
                Math.cos(lat1Rad) * Math.cos(lat2Rad) *
                        Math.pow(Math.sin(lonDiff / 2), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        // 计算距离
        double distance = EARTH_RADIUS * c;

        // 保留两位小数
        return Math.round(distance * 100) / 100.0;
    }

    //mall端-查询指定伴宠师详情
    @ApiOperation("mall端-查询指定伴宠师详情接口")
    @GetMapping("/getTeacherDetail")
    public AppUsers getTeacherDetail(AppUsers app) {
        //用户标识不能为空

        AppUsers appUsers = appUsersService.selectAppUsersByUserId(app.getUserId());
        AppletUsersTeacher appletUsersTeacher = appletUsersTeacherService.selectAppletUsersTeacherByUserId(appUsers.getUserId());
        appUsers.setAppletUsersTeacher(appletUsersTeacher);

        AppletAddress appletAddress = new AppletAddress();
        appletAddress.setUserId(appUsers.getUserId());
        List<AppletAddress> appletAddresses = appletAddressService.selectAppletAddressList(appletAddress);
        appUsers.setAppletAddresseList(appletAddresses);
        return appUsers;
    }

    //mall端-查询指定伴宠师近期评价
    @ApiOperation("mall端-查询指定伴宠师近期评价")
    @GetMapping("/getTeacherEvaluate")
    public AjaxResult getTeacherEvaluate(@RequestParam String id) {

        Page<OmsOrderEvaluation> page = omsOrderEvaluationService.lambdaQuery()
                .eq(OmsOrderEvaluation::getTechnicianId, id)
                .page(new Page<>(1, 10));

        for (OmsOrderEvaluation record : page.getRecords()) {
            record.setMember(memberMapper.selectById(record.getMemberId()));
        }

        return AjaxResult.success(page);
    }



    //mall端-系统派单的时候需要选择的伴宠师等级说明
    @ApiOperation("mall端-系统派单的时候需要选择的伴宠师等级说明接口")
    @GetMapping("/getTeacherLevels")
    public TableDataInfo getTeacherLevels() {
        AppletConfig appletConfig = new AppletConfig();
        appletConfig.setParamClass("order_mall");
        List<AppletConfig> appletConfigs = appletConfigService.selectAppletConfigList(appletConfig);
        return getDataTable(appletConfigs);
    }






    //mall端-下单端用户通过邀请码绑定伴宠师
    @ApiOperation("mall端-下单端用户通过邀请码绑定伴宠师")
    @GetMapping("/bindCode")
    public AjaxResult bindCode(String code, String openId) {

        if (StringUtils.isEmpty(openId)){
            throw new ServiceException("openId不能为空");
        }
        Member member = memberWechatService.isRegister(openId);

        if (member == null){
            throw new ServiceException("用户不存在");
        }

        //判断当前用户有没有绑定
        if (StringUtils.isNotEmpty(member.getInviteCode())){
            throw new ServiceException("已经绑定过了");
        }

        AppUsers users = appUsersService.bindCode(code);
        member.setInviteCode(code);
        member.setSpreadTime(LocalDateTime.now());
        member.setSpreadUid(users.getUserId());
        memberMapper.updateById(member);

        try {
            apiAppletHhrWorkOutService.checkPartnerUpgrade(users.getUserId());
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return AjaxResult.success();
    }










}
