package com.usky.meeting.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.DateUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.meeting.controller.web.SignOnOutRequestVO;
import com.usky.meeting.domain.*;
import com.usky.meeting.mapper.MeetingDeviceMapper;
import com.usky.meeting.mapper.MeetingFloorMapper;
import com.usky.meeting.mapper.MeetingInfoMapper;
import com.usky.meeting.mapper.MeetingRoomMapper;
import com.usky.meeting.repository.*;
import com.usky.meeting.service.MeetingAttendeeService;
import com.usky.meeting.service.MeetingFileService;
import com.usky.meeting.service.MeetingInfoService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.meeting.service.SysUserService;
import com.usky.meeting.service.dto.DmMeetingDto;
import com.usky.meeting.service.dto.DmMeetingDtoV2;
import com.usky.meeting.service.dto.DmUserDto;
import com.usky.meeting.service.vo.MeetingInfoRequestVO;
import com.usky.meeting.service.vo.MyMeetingInfoRequestVO;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.dynamic.scaffold.MethodRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 会议表(预约成功) 服务实现类
 * </p>
 *
 * @author zyj
 * @since 2024-03-08
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MeetingInfoServiceImpl extends AbstractCrudService<MeetingInfoMapper, MeetingInfo> implements MeetingInfoService {

    @Autowired
    private MeetingInfoRepository dmMeetingRepository;
    @Autowired
    private MeetingAttendeeRepository meetingAttendeeRepository;
    @Autowired
    private MeetingRoomRepository meetingRoomRepository;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MeetingAttendeeService meetingAttendeeService;
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;
    @Autowired
    private MeetingFloorMapper meetingFloorMapper;
    @Autowired
    private MeetingFileService meetingFileService;
    @Autowired
    private MeetingDeviceMapper deviceMapper;

    @Override
    public Map<String, Object> meetingSummary(Integer tenantId) {
        return dmMeetingRepository.meetingSummary(tenantId);
    }

    @Override
    public Map<String, Object> meetingSummaryByYear(String year, Integer tenantId) {
        return dmMeetingRepository.meetingSummaryByYear(year, tenantId);
    }

    @Override
    public JSONObject getMeetingRoomUsageByDayV2(Long roomId, String dayTime, Integer tenantId) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        JSONArray array = new JSONArray();
        JSONArray dmMeetingList = new JSONArray();

        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dtf.parse(dayTime);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获取日期中得年
        Integer year = cal.get(Calendar.YEAR);
        System.out.println("year:" + year);
        // 获取日期中得月
        Integer month = (cal.get(Calendar.MONTH) + 1);
        System.out.println("month:" + month);
        // 获取日期中得日
        Integer day = Integer.valueOf(String.format("%td", date));
        List<MeetingInfo> dmMeetings = dmMeetingRepository.getDmMeetingByStartDatDay(roomId, year, month, day, tenantId);
        LambdaQueryWrapper<SysUser> sysUserQuery = Wrappers.lambdaQuery();
        sysUserQuery.eq(SysUser::getTenantId, tenantId);
        List<SysUser> userList = sysUserService.list(sysUserQuery);
        if (userList.size() <= 0) {
            throw new BusinessException("用户信息不能为空");
        }

        if (!ObjectUtil.isEmpty(dmMeetings)) {
            for (MeetingInfo dmMeeting : dmMeetings) {
                // 参会人员信息
                List<SysUser> attendeeUserList = new ArrayList<>();
                List<MeetingAttendee> attendeeList = meetingAttendeeRepository.findMeetingAttendeeList(dmMeeting.getMeetingId(), null, tenantId);
                if (attendeeList.size() > 0) {
                    for (int i = 0; i < attendeeList.size(); i++) {
                        Long uid = attendeeList.get(i).getUserId();
                        for (int j = 0; j < userList.size(); j++) {
                            if (uid.equals(userList.get(j).getUserId())) {
                                attendeeUserList.add(userList.get(j));
                                break;
                            }
                        }
                    }
                }
                dmMeeting.setUsers(attendeeUserList);
                // 发起人信息
                for (int i = 0; i < userList.size(); i++) {
                    if (userList.get(i).getUserId().equals(Long.valueOf(dmMeeting.getInitiatorId()))) {
                        dmMeeting.setInitiatorUser(userList.get(i));
                        break;
                    }
                }

                dmMeetingList.add(dmMeeting);
                JSONArray dateArray = new JSONArray();
                double meetingStartNumber = 0.0;
                double meetingEndNumber = 0.0;
                Timestamp meetingStartTimestamp = Timestamp.valueOf(dmMeeting.getStartDate());
                Date meetingStartDate = new Date(meetingStartTimestamp.getTime());
                Calendar meetingStartCal = Calendar.getInstance();
                meetingStartCal.setTime(meetingStartDate);
                if (cal.get(Calendar.YEAR) == meetingStartCal.get(Calendar.YEAR) && cal.get(Calendar.DAY_OF_YEAR) == meetingStartCal.get(Calendar.DAY_OF_YEAR)) {
                    int meetingStartHours = meetingStartDate.getHours();
                    meetingStartNumber = meetingStartNumber + meetingStartHours;
                    int meetingStartMinutes = meetingStartDate.getMinutes();
                    if (meetingStartMinutes >= 30) {
                        meetingStartNumber = meetingStartNumber + 0.5;
                    }
                    dateArray.add(meetingStartNumber);
                } else {
                    meetingStartNumber = 0.0;
                    dateArray.add(meetingStartNumber);
                }
                Timestamp meetingEndTimestamp = Timestamp.valueOf(dmMeeting.getEndDate());
                Date meetingEndDate = new Date(meetingEndTimestamp.getTime());
                Calendar meetingEndCal = Calendar.getInstance();
                meetingEndCal.setTime(meetingEndDate);
                if (cal.get(Calendar.YEAR) == meetingEndCal.get(Calendar.YEAR) && cal.get(Calendar.DAY_OF_YEAR) == meetingEndCal.get(Calendar.DAY_OF_YEAR)) {
                    int meetingEndHours = meetingEndDate.getHours();
                    meetingEndNumber = meetingEndNumber + meetingEndHours;
                    int meetingEndMinutes = meetingEndDate.getMinutes();
                    if (meetingEndMinutes >= 30) {
                        meetingEndNumber = meetingEndNumber + 0.5;
                        if (meetingEndMinutes == 59) {
                            meetingEndNumber = meetingEndNumber + 0.5;
                        }
                    }
                    dateArray.add(meetingEndNumber);
                } else {
                    meetingEndNumber = 24.0;
                    dateArray.add(meetingEndNumber);
                }
                array.add(dateArray);
            }
        }
        jsonObject.put("timeRange", array);
        jsonObject.put("dmMeeting", dmMeetingList);
        return jsonObject;
    }

    @Override
    public List<Integer> getMeetingRoomUsageByMonth(Long roomId, String monthTime, Integer tenantId) throws ParseException {
        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = dtf.parse(monthTime);
        System.out.println("date:" + date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获取日期中得年
        Integer year = cal.get(Calendar.YEAR);
        System.out.println("year:" + year);
        // 获取日期中得月
        Integer month = (cal.get(Calendar.MONTH) + 1);
        System.out.println("month:" + month);

        List<Map<String, Object>> dmMeetings = dmMeetingRepository.getDmMeetingByStartDateYearAndMonth(roomId, year, month, tenantId);
        if (!ObjectUtils.isEmpty(dmMeetings)) {
            List<Integer> list = new ArrayList<>();
            Set<Integer> set = new HashSet<>();
            for (Map<String, Object> map : dmMeetings) {
                Date startDate = dtf.parse(map.get("start_date").toString());
                Date endDate = dtf.parse(map.get("end_date").toString());
                Calendar calendar = Calendar.getInstance();
                while (startDate.getTime() <= endDate.getTime()) {
                    // 把日期添加到集合
                    Integer startDay = Integer.valueOf(String.format("%td", startDate));
                    set.add(startDay);
                    // 设置日期
                    calendar.setTime(startDate);
                    // 把日期增加一天
                    calendar.add(Calendar.DATE, 1);
                    // 获取增加后的日期
                    startDate = calendar.getTime();
                }

            }
            list.addAll(set);
            return list;
        }
        return new ArrayList<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmMeetingDto add(DmMeetingDto resources) {
        String meetingMode = resources.getMeetingMode().toString();
        SysUser user = userRepository.getUserByDmUserId(resources.getInitiatorUser().getId());
        if (meetingMode.equals("1")) {

        } else if (meetingMode.equals("0") || meetingMode.equals("2")) {
            // 判断指定会议室预约的时间是否与存在的预约单冲突
            List<Map<String, String>> dmMeetingList = dmMeetingRepository.checkDmRoomMeetingDate(resources.getRoom().getRoomId(), resources.getStartDate(), resources.getEndDate(), resources.getMeetingId());
            if (dmMeetingList != null && dmMeetingList.size() > 0) {
                throw new BusinessException("预约时间段冲突,请重设预约时间");
            }
            if (!ObjectUtils.isEmpty(resources.getRoom())) {
                if (resources.getRoom().getStatus().equals("1")) {
                    throw new BusinessException("该会议室已停用");
                }
                resources.setRoomName(resources.getRoom().getRoomName());
            }
            if (resources.getRoom().getIsApprove() == 1) {

            } else {
                resources.setApproveStatus(1);

                try {
                    send(resources);
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
        }
        resources.setIsDelay(0);
        resources.setIsCancel(0);
        resources.setMeetingStatus(0);
        MeetingInfo meeting = this.toEntity(resources);
        this.save(meeting);

        // 循环保存会议id和会议文件记录到会议文件表中
        Long meetingId = meeting.getMeetingId();
        if (!ObjectUtils.isEmpty(resources.getMeetingFileList())) {
            for (MeetingFile meetingFile : resources.getMeetingFileList()) {
                meetingFile.setMeetingId(meetingId);
                meetingFile.setUploadUser(SecurityUtils.getUsername());
                meetingFile.setUploadTime(LocalDateTime.now());
                meetingFile.setTenantId(SecurityUtils.getTenantId());
                meetingFileService.save(meetingFile);
            }
        }

        if (!ObjectUtils.isEmpty(resources.getUsers())) {
            for (SysUser dmUser : resources.getUsers()) {
                MeetingAttendee meetingAttendee = new MeetingAttendee();
                meetingAttendee.setMeetingId(meeting.getMeetingId());
                meetingAttendee.setUserId(dmUser.getUserId());
                meetingAttendee.setTenantId(SecurityUtils.getTenantId());
                meetingAttendeeService.save(meetingAttendee);
            }

        }
        return resources;
    }

    @Override
    public CommonPage<MeetingInfo> meetingInfoList(MeetingInfoRequestVO requestVO) {
        Page<MeetingInfo> page = new Page<>(requestVO.getCurrent(), requestVO.getSize());
        LambdaQueryWrapper<MeetingInfo> queryWrapper = Wrappers.lambdaQuery();

        if (StringUtils.isNotBlank(requestVO.getName())) {
            List<String> initiatorIdList = new ArrayList<>();
            LambdaQueryWrapper<SysUser> sysUserQuery = Wrappers.lambdaQuery();
            sysUserQuery.like(SysUser::getNickName, requestVO.getName())
                    .eq(SysUser::getTenantId, SecurityUtils.getTenantId());
            List<SysUser> userList = sysUserService.list(sysUserQuery);
            if (userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    initiatorIdList.add(userList.get(i).getUserId().toString());
                }
            }

            if (CollectionUtils.isNotEmpty(initiatorIdList)) {
                queryWrapper.like(StringUtils.isNotBlank(requestVO.getRoomName()), MeetingInfo::getRoomName, requestVO.getRoomName())
                        .in(MeetingInfo::getInitiatorId, initiatorIdList)
                        .eq(null != requestVO.getMeetingStatus(), MeetingInfo::getMeetingStatus, requestVO.getMeetingStatus())
                        .eq(null != requestVO.getApproveStatus(), MeetingInfo::getApproveStatus, requestVO.getApproveStatus())
                        .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getStartDate, requestVO.getStartDate(), requestVO.getEndDate())
                        .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getEndDate, requestVO.getStartDate(), requestVO.getEndDate())
                        .eq(MeetingInfo::getTenantId, SecurityUtils.getTenantId())
                        .orderByDesc(MeetingInfo::getMeetingId);
            } else {
                queryWrapper.like(StringUtils.isNotBlank(requestVO.getRoomName()), MeetingInfo::getRoomName, requestVO.getRoomName())
                        .in(MeetingInfo::getInitiatorId, "")
                        .eq(null != requestVO.getMeetingStatus(), MeetingInfo::getMeetingStatus, requestVO.getMeetingStatus())
                        .eq(null != requestVO.getApproveStatus(), MeetingInfo::getApproveStatus, requestVO.getApproveStatus())
                        .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getStartDate, requestVO.getStartDate(), requestVO.getEndDate())
                        .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getEndDate, requestVO.getStartDate(), requestVO.getEndDate())
                        .eq(MeetingInfo::getTenantId, SecurityUtils.getTenantId())
                        .orderByDesc(MeetingInfo::getMeetingId);
            }
        } else {
            queryWrapper.like(StringUtils.isNotBlank(requestVO.getRoomName()), MeetingInfo::getRoomName, requestVO.getRoomName())
                    .eq(null != requestVO.getMeetingStatus(), MeetingInfo::getMeetingStatus, requestVO.getMeetingStatus())
                    .eq(null != requestVO.getApproveStatus(), MeetingInfo::getApproveStatus, requestVO.getApproveStatus())
                    .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getStartDate, requestVO.getStartDate(), requestVO.getEndDate())
                    .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getEndDate, requestVO.getStartDate(), requestVO.getEndDate())
                    .eq(MeetingInfo::getTenantId, SecurityUtils.getTenantId())
                    .orderByDesc(MeetingInfo::getMeetingId);
        }

        page = this.page(page, queryWrapper);
        if (page.getRecords().size() > 0) {
            List<Long> roomIdList = new ArrayList<>();
            List<Long> initIdList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                if (!roomIdList.contains(page.getRecords().get(i).getRoomId())) {
                    roomIdList.add(page.getRecords().get(i).getRoomId());
                }
                if (!initIdList.contains(page.getRecords().get(i).getInitiatorId())) {
                    initIdList.add(Long.valueOf(page.getRecords().get(i).getInitiatorId()));
                }
            }
            // 房间以及对应楼层信息
            if (roomIdList.size() > 0) {
                LambdaQueryWrapper<MeetingRoom> meetingRoomQuery = Wrappers.lambdaQuery();
                meetingRoomQuery.in(MeetingRoom::getRoomId, roomIdList)
                        .eq(MeetingRoom::getTenantId, SecurityUtils.getTenantId())
                        .eq(MeetingRoom::getStatus, 0);
                List<MeetingRoom> meetingRoomList = meetingRoomMapper.selectList(meetingRoomQuery);

                List<Long> floorIdList = new ArrayList<>();
                if (meetingRoomList.size() > 0) {
                    for (int i = 0; i < meetingRoomList.size(); i++) {
                        if (!floorIdList.contains(meetingRoomList.get(i).getFloorId())) {
                            floorIdList.add(meetingRoomList.get(i).getFloorId());
                        }
                    }
                    LambdaQueryWrapper<MeetingFloor> floorWrapper = Wrappers.lambdaQuery();
                    floorWrapper.in(MeetingFloor::getFloorId, floorIdList)
                            .eq(MeetingFloor::getTenantId, SecurityUtils.getTenantId());
                    List<MeetingFloor> meetingFloorList = meetingFloorMapper.selectList(floorWrapper);
                    for (int i = 0; i < page.getRecords().size(); i++) {
                        for (int j = 0; j < meetingRoomList.size(); j++) {
                            if (page.getRecords().get(i).getRoomId().equals(meetingRoomList.get(j).getRoomId())) {
                                page.getRecords().get(i).setRoomInfo(meetingRoomList.get(j));
                                break;
                            }
                        }
                        for (int j = 0; j < meetingFloorList.size(); j++) {
                            if (page.getRecords().get(i).getRoomInfo().getFloorId().equals(meetingFloorList.get(j).getFloorId())) {
                                page.getRecords().get(i).getRoomInfo().setMeetingFloor(meetingFloorList.get(j));
                                break;
                            }
                        }
                    }
                }
            }
            // 发起人信息
            if (initIdList.size() > 0) {
                LambdaQueryWrapper<SysUser> initIdQuery = Wrappers.lambdaQuery();
                initIdQuery.in(SysUser::getUserId, initIdList)
                        .eq(SysUser::getTenantId, SecurityUtils.getTenantId());
                List<SysUser> userList = sysUserService.list(initIdQuery);
                if (userList.size() > 0) {
                    for (int i = 0; i < page.getRecords().size(); i++) {
                        for (int j = 0; j < userList.size(); j++) {
                            if (page.getRecords().get(i).getInitiatorId().equals(userList.get(j).getUserId().toString())) {
                                page.getRecords().get(i).setInitiatorUser(userList.get(j));
                                break;
                            }
                        }
                    }
                }
            }


        }


        return new CommonPage<>(page.getRecords(), page.getTotal(), requestVO.getSize(), requestVO.getCurrent());
    }

    @Override
    public void cancel(Long meetingId) {
        MeetingInfo one = this.getById(meetingId);
        one.setIsCancel(1);
        one.setMeetingStatus(2);
        this.updateById(one);
    }

    @Override
    public CommonPage<MeetingInfo> myMeetingList(MyMeetingInfoRequestVO requestVO) {
        Integer current = requestVO.getCurrent();
        Integer size = requestVO.getSize();
        Page<MeetingInfo> page = new Page<>(current, size);

        Long userId = SecurityUtils.getUserId();
        List<BigInteger> meetingIdList = new ArrayList<>();
        List<BigInteger> meetingIds1 = dmMeetingRepository.queryMeetingIdsByUserId(userId);
        List<BigInteger> bigIntegers = dmMeetingRepository.queryMeetingIdsByInitiatorId(userId);
        meetingIdList.addAll(meetingIds1);
        meetingIdList.addAll(bigIntegers);
        List<Long> meetingIds = new ArrayList<>();
        for (BigInteger bigInteger : meetingIdList) {
            meetingIds.add(bigInteger.longValue());
        }
        LambdaQueryWrapper<MeetingInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(CollectionUtils.isNotEmpty(meetingIds), MeetingInfo::getMeetingId, meetingIds)
                .eq(MeetingInfo::getIsCancel, 0)
                .like(StringUtils.isNotBlank(requestVO.getMeetingName()), MeetingInfo::getMeetingName, requestVO.getMeetingName())
                .like(StringUtils.isNotBlank(requestVO.getMeetingDescribe()), MeetingInfo::getMeetingDescribe, requestVO.getMeetingDescribe())
                .eq(null != requestVO.getMeetingMode(), MeetingInfo::getMeetingMode, requestVO.getMeetingMode())
                .eq(null != requestVO.getMeetingStatus(), MeetingInfo::getMeetingStatus, requestVO.getMeetingStatus())
                .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getStartDate, requestVO.getStartDate(), requestVO.getEndDate())
                .between(StringUtils.isNotBlank(requestVO.getStartDate()) && StringUtils.isNotBlank(requestVO.getEndDate()), MeetingInfo::getEndDate, requestVO.getStartDate(), requestVO.getEndDate())
                .eq(MeetingInfo::getTenantId, SecurityUtils.getTenantId())
                .orderByDesc(MeetingInfo::getMeetingId);
        page = this.page(page, queryWrapper);
        if (page.getRecords().size() > 0) {
            List<Long> initIdList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                if (!initIdList.contains(page.getRecords().get(i).getInitiatorId())) {
                    initIdList.add(Long.valueOf(page.getRecords().get(i).getInitiatorId()));
                }
            }
            // 发起人信息
            if (initIdList.size() > 0) {
                LambdaQueryWrapper<SysUser> initIdQuery = Wrappers.lambdaQuery();
                initIdQuery.in(SysUser::getUserId, initIdList)
                        .eq(SysUser::getTenantId, SecurityUtils.getTenantId());
                List<SysUser> userList = sysUserService.list(initIdQuery);
                if (userList.size() > 0) {
                    for (int i = 0; i < page.getRecords().size(); i++) {
                        for (int j = 0; j < userList.size(); j++) {
                            if (page.getRecords().get(i).getInitiatorId().equals(userList.get(j).getUserId().toString())) {
                                page.getRecords().get(i).setInitiatorUser(userList.get(j));
                                break;
                            }
                        }
                    }
                }
            }


        }

        return new CommonPage<>(page.getRecords(), page.getTotal(), size, current);
    }

    @Override
    public List<Map<String, Object>> meetingSignList(Long meetingId) {
        Integer tenantId = SecurityUtils.getTenantId();
        List<Map<String, Object>> signList = dmMeetingRepository.meetingSignList(meetingId, tenantId);
        return signList;
    }

    @Override
    public void signOnOut(SignOnOutRequestVO requestVO) {
        LambdaQueryWrapper<MeetingAttendee> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MeetingAttendee::getMeetingId, requestVO.getMeetingId())
                .eq(MeetingAttendee::getUserId, requestVO.getUserId());

        String deviceCode = requestVO.getDeviceCode();
        Integer tenantId;
        if (StringUtils.isNotBlank(deviceCode)) {
            LambdaQueryWrapper<MeetingDevice> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(MeetingDevice::getDeviceCode, requestVO.getDeviceCode());
            tenantId = deviceMapper.selectOne(queryWrapper1).getTenantId();
            queryWrapper.eq(MeetingAttendee::getTenantId, tenantId);
        } else {
            queryWrapper.eq(MeetingAttendee::getTenantId, SecurityUtils.getTenantId());
        }

        MeetingAttendee one = meetingAttendeeService.getOne(queryWrapper);
        if (one != null) {
            // 签到签退类别(0.签到 1.签退)
            if (requestVO.getMothodType().equals(0)) {
                one.setIsSign(1);
                one.setSignDate(LocalDateTime.now());
                // 签到签退方式(0.人工 1.人脸 3.二维码)
                one.setSignType(requestVO.getSignType());

            } else if (requestVO.getMothodType().equals(1)) {
                one.setIsSignOut(1);
                one.setSignOutDate(LocalDateTime.now());
                one.setSignOutType(requestVO.getSignType());
            }
            meetingAttendeeService.updateById(one);
        } else {
            throw new BusinessException("您无需参加此会议！");
        }

    }

    // UPDATE meeting_info SET meeting_status = 0 WHERE is_cancel = 0 AND meeting_status != 2 AND start_date > SYSDATE;
    // UPDATE meeting_info SET meeting_status = 1 WHERE is_cancel = 0 AND meeting_status != 2 AND start_date <= SYSDATE AND end_date >= SYSDATE;
    // UPDATE meeting_info SET meeting_status = 2 WHERE is_cancel = 0 AND meeting_status != 2 AND end_date < SYSDATE;
    @Override
    public void updateMeetingInfoStatus() {
        // 根据使用中的会议id去更新对应会议室的状态
        // 更新会议室使用状态为 1-使用中
        LambdaQueryWrapper<MeetingInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MeetingInfo::getIsCancel, 0)
                .ne(MeetingInfo::getMeetingStatus, 2)
                .le(MeetingInfo::getStartDate, LocalDateTime.now())
                .ge(MeetingInfo::getEndDate, LocalDateTime.now());
        List<MeetingInfo> list = this.list(queryWrapper);
        Set<Long> roomIdList = new HashSet<>();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                roomIdList.add(list.get(i).getRoomId());
            }
        }
        meetingRoomRepository.updateMeetingRoomStatusOnUse(roomIdList);
        // 更新将会议室使用状态恢复为 0-未使用
        LambdaQueryWrapper<MeetingInfo> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(MeetingInfo::getIsCancel, 0)
                .ne(MeetingInfo::getMeetingStatus, 2)
                .lt(MeetingInfo::getEndDate, LocalDateTime.now());
        List<MeetingInfo> list1 = this.list(queryWrapper1);
        Set<Long> roomIdList1 = new HashSet<>();
        if (list1.size() > 0) {
            for (int i = 0; i < list1.size(); i++) {
                if (!roomIdList.contains(list1.get(i).getRoomId())) {
                    roomIdList1.add(list1.get(i).getRoomId());
                }
            }
        }
        meetingRoomRepository.updateMeetingRoomStatusFreeUse(roomIdList1);


        UpdateWrapper<MeetingInfo> updateWrapper = Wrappers.update();
        updateWrapper.set("meeting_status", 1)
                .eq("is_cancel", 0)
                .ne("meeting_status", 2)
                .le("start_date", LocalDateTime.now())
                .ge("end_date", LocalDateTime.now());
        this.update(updateWrapper);
        UpdateWrapper<MeetingInfo> updateWrapper1 = Wrappers.update();
        updateWrapper1.set("meeting_status", 2)
                .eq("is_cancel", 0)
                .ne("meeting_status", 2)
                .lt("end_date", LocalDateTime.now());
        this.update(updateWrapper1);
    }

    public void send(DmMeetingDto resources) throws ClientException {

        if (StringUtils.isNotBlank(resources.getSendType())) {
            String[] typeList = resources.getSendType().split(",");
            if (typeList.length > 0) {
                for (int i = 0; i < typeList.length; i++) {
                    String sendType = typeList[i];

                    if (sendType.equals("短信")) {
                        for (SysUser dmUser : resources.getUsers()) {
                            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String sj = resources.getStartDate();
                            DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", "LTAI5tH3VvRL5BUkovCokHJX", "SaaWUouNqvcA0C746gcNOH9m6SRYN4");
                            IAcsClient client = new DefaultAcsClient(profile);
                            SendSmsRequest request = new SendSmsRequest();
                            request.setPhoneNumbers(dmUser.getPhonenumber());// 接收短信的手机号码
                            request.setSignName("上海永天科技股份有限公司");// 短信签名名称
                            request.setTemplateCode("SMS_465362899");// 短信模板CODE
                            request.setTemplateParam("{\"meet\":\"" + resources.getMeetingName() + "\"," + "\"time\":\"" + resources.getStartDate() + "\"," +
                                    "\"room\":\"" + resources.getRoomName() + "\"}");
                            SendSmsResponse code = client.getAcsResponse(request);
                            if (code.getCode() != null && code.getCode().equals("OK")) {
                                // 请求成功
                            } else {
//                                throw new BusinessException("发送短信失败");
                                log.info(dmUser.getPhonenumber() + "发送短信失败");
                            }
                        }


                    } else if (sendType.equals("Email")) {
//                List<String> emailList = new ArrayList<>();
//                if (!ObjectUtils.isEmpty(resources.getUserList())) {
//                    for (DmUserDto dmUserDto : resources.getUserList()) {
//                        if (!ObjectUtils.isEmpty(dmUserDto.getEmail()) && !StringUtils.equals(dmUserDto.getId(), resources.getInitiatorUser().getId())) {
//                            emailList.add(dmUserDto.getEmail());
//                        }
//                    }
//                } else {
//                    for (User dmUser : resources.getUsers()) {
//                        if (!ObjectUtils.isEmpty(dmUser.getEmail()) && !StringUtils.equals(dmUser.getId(), resources.getInitiatorUser().getId())) {
//                            emailList.add(dmUser.getEmail());
//                        }
//                    }
//                }
//                log.info("emailList:" + emailList);
//                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String sj = sf.format(resources.getStartDate());
//                String sendContent2 = "您已受邀参加会议：" + resources.getMeetingName() + "，该会议将于" + sj + " 在" + resources.getRoomName() + "举行。请您及时准备相关参会材料，并请准时出席。";
//                sendEmail(user.getEmail(), emailList, "会议预约通知", sendContent2);
                    }
                }
            }
        }
    }

//    //邮箱通知
//    public void sendEmail(String recipientMailbox, List<String> recipientMailbox1, String emailSubject, String messageBody) {
//        // 发送人的邮件和密码
//        String myEmailAccount = EmailProperties.myEmailAccount;
//        String myEmailPassword = EmailProperties.myEmailPassword;
//        SendMailUtils.sendMail(myEmailAccount, myEmailPassword, recipientMailbox, recipientMailbox1, null, emailSubject, messageBody, false);
//    }

//    public JSONObject reserveMeetingData(DmMeetingDto resources) {
//        String reserveMeetingUrl = UrlProperties.erpYyUrl + "/api-im-logic/busi/meeting/reserveMeeting";
//        JSONObject reserveMeetingJson = new JSONObject();
//        reserveMeetingJson.put("originatorId", resources.getInitiatorUser().getId());
//        reserveMeetingJson.put("originatorName", resources.getInitiatorUser().getName());
//        reserveMeetingJson.put("meetingTitle", resources.getMeetingName());
//        reserveMeetingJson.put("meetingType", "video");
//        reserveMeetingJson.put("meetingStartTime", resources.getStartDate().getTime());
//        long diff = resources.getEndDate().getTime() - resources.getStartDate().getTime();
//        long min = diff / (1000 * 60);
//        reserveMeetingJson.put("appointmentDuration", min * 60);
//        reserveMeetingJson.put("appointmentRemindDuration", 60);
//        reserveMeetingJson.put("advanceTime", null);
//        reserveMeetingJson.put("remarks", resources.getMeetingDescribe());
//        JSONArray invitedUserList = new JSONArray();
//        if (ObjectUtils.isEmpty(resources.getUserList())) {
//            Set<User> userList = resources.getUsers();
//            for (User dmUserDto : userList) {
//                DmUserDto dmUserDto1 = dmUserService.findById(dmUserDto.getId());
//                JSONObject invitedUser = new JSONObject();
//                invitedUser.put("userId", dmUserDto1.getId());
//                invitedUser.put("userName", dmUserDto1.getName());
//                invitedUser.put("jobName", dmUserDto1.getDept().getName());
//                invitedUser.put("mobile", dmUserDto1.getContacts());
//                invitedUserList.add(invitedUser);
//            }
//        } else {
//            Set<DmUserDto> userList = resources.getUserList();
//            for (DmUserDto dmUserDto : userList) {
//                DmUserDto dmUserDto1 = dmUserService.findById(dmUserDto.getId());
//                JSONObject invitedUser = new JSONObject();
//                invitedUser.put("userId", dmUserDto1.getId());
//                invitedUser.put("userName", dmUserDto1.getName());
//                invitedUser.put("jobName", dmUserDto1.getDept().getName());
//                invitedUser.put("mobile", dmUserDto1.getContacts());
//                invitedUserList.add(invitedUser);
//            }
//        }
//        reserveMeetingJson.put("invitedUserList", invitedUserList);
//        Map<String, String> headersMap = new HashMap<String, String>();
//        headersMap.put("Content-Type", "application/json; charset=utf-8");
//        headersMap.put("serviceId", "USky");
//        headersMap.put("serviceUserId", resources.getInitiatorUser().getId());
//        log.info("reserveMeetingJson:" + reserveMeetingJson.toJSONString());
//        String reserveMeetingData = HttpClientUtil.sendPost(reserveMeetingUrl, "POST", headersMap, reserveMeetingJson.toString());
//        log.info("reserveMeetingData:" + reserveMeetingData);
//        try {
//            JSONObject reserveMeetingDataJson = JSONObject.parseObject(reserveMeetingData);
//            String code = reserveMeetingDataJson.getString("code");
//            if (!StringUtils.equals(code, "0000")) {
//                saveLog("ERP系统预约会议接口返回失败！", reserveMeetingData, reserveMeetingJson.toJSONString(), UrlProperties.erpYyUrl, "/api-im-logic/busi/meeting/reserveMeeting");
//            }
//            return reserveMeetingDataJson;
//        } catch (Exception ex) {
//            saveLog("ERP系统预约会议接口返回失败！", reserveMeetingData, reserveMeetingJson.toJSONString(), UrlProperties.erpYyUrl, "/api-im-logic/busi/meeting/reserveMeeting");
//            throw new BadRequestException("ERP系统预约会议接口返回失败！");
//        }
//    }

    public MeetingInfo toEntity(DmMeetingDto dto) {
        if (dto == null) {
            return null;
        }

        MeetingInfo dmMeeting = new MeetingInfo();

        dmMeeting.setCreateBy(SecurityUtils.getUsername());
        dmMeeting.setCreateTime(LocalDateTime.now());
        dmMeeting.setTenantId(SecurityUtils.getTenantId());
        dmMeeting.setMeetingName(dto.getMeetingName());
        dmMeeting.setRoomId(dto.getRoomId());
        dmMeeting.setRoomName(dto.getRoomName());
        dmMeeting.setMeetingDescribe(dto.getMeetingDescribe());
        dmMeeting.setMeetingType(dto.getMeetingType());
        dmMeeting.setInitiatorId(dto.getInitiatorUser().getId());
        dmMeeting.setStartDate(LocalDateTime.parse(dto.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        dmMeeting.setEndDate(LocalDateTime.parse(dto.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        dmMeeting.setApproveStatus(dto.getApproveStatus());
        dmMeeting.setApproveSuggest(dto.getApproveSuggest());
        dmMeeting.setActualCount(dto.getActualCount());
        dmMeeting.setPlanCount(dto.getPlanCount());
        dmMeeting.setIsDelay(dto.getIsDelay());
        dmMeeting.setRemark(dto.getRemark());
        dmMeeting.setMeetingStatus(dto.getMeetingStatus());
        dmMeeting.setTaskId(dto.getTaskId());
        dmMeeting.setProcInstId(dto.getProcInstId());
        dmMeeting.setIsCancel(dto.getIsCancel());
        dmMeeting.setSendType(dto.getSendType());
        dmMeeting.setIsApprove(dto.getIsApprove());
        dmMeeting.setMeetingMode(dto.getMeetingMode());

        return dmMeeting;
    }
//
//    @Override
//    public DmMeetingDto toDto(MeetingInfo entity) {
//        if ( entity == null ) {
//            return null;
//        }
//
//        DmMeetingDto dmMeetingDto = new DmMeetingDto();
//
//        dmMeetingDto.setCreateBy( entity.getCreateBy() );
//        dmMeetingDto.setUpdateBy( entity.getUpdateBy() );
//        dmMeetingDto.setCreateTime( entity.getCreateTime() );
//        dmMeetingDto.setUpdateTime( entity.getUpdateTime() );
//        dmMeetingDto.setMeetingId( entity.getMeetingId() );
//        dmMeetingDto.setMeetingName( entity.getMeetingName() );
//        dmMeetingDto.setRoom( dmMeetingRoomToDmMeetingRoomDto( entity.getRoom() ) );
//        dmMeetingDto.setRoomName( entity.getRoomName() );
//        dmMeetingDto.setMeetingDescribe( entity.getMeetingDescribe() );
//        dmMeetingDto.setMeetingType( entity.getMeetingType() );
//        dmMeetingDto.setDept( deptToDeptDto( entity.getDept() ) );
//        dmMeetingDto.setInitiatorUser( dmUserToDmUserDto( entity.getInitiatorUser() ) );
//        Set<User> set = entity.getUsers();
//        if ( set != null ) {
//            dmMeetingDto.setUsers( new HashSet<User>( set ) );
//        }
//        Set<LocalStorage> set1 = entity.getLocalStorages();
//        if ( set1 != null ) {
//            dmMeetingDto.setLocalStorages( new HashSet<LocalStorage>( set1 ) );
//        }
//        Set<DmDevice> set2 = entity.getDmDevices();
//        if ( set2 != null ) {
//            dmMeetingDto.setDmDevices( new HashSet<DmDevice>( set2 ) );
//        }
//        dmMeetingDto.setStartDate( entity.getStartDate() );
//        dmMeetingDto.setEndDate( entity.getEndDate() );
//        dmMeetingDto.setApproveStatus( entity.getApproveStatus() );
//        dmMeetingDto.setApproveSuggest( entity.getApproveSuggest() );
//        dmMeetingDto.setActualCount( entity.getActualCount() );
//        dmMeetingDto.setPlanCount( entity.getPlanCount() );
//        dmMeetingDto.setIsDelay( entity.getIsDelay() );
//        dmMeetingDto.setRemark( entity.getRemark() );
//        dmMeetingDto.setMeetingStatus( entity.getMeetingStatus() );
//        dmMeetingDto.setTaskId( entity.getTaskId() );
//        dmMeetingDto.setProcInstId( entity.getProcInstId() );
//        dmMeetingDto.setIsCancel( entity.getIsCancel() );
//        dmMeetingDto.setSendType( entity.getSendType() );
//        dmMeetingDto.setMeetingProp( entity.getMeetingProp() );
//        dmMeetingDto.setIsApprove( entity.getIsApprove() );
//        if ( entity.getGcAssignUser() != null ) {
//            dmMeetingDto.setGcAssignUser( Long.parseLong( entity.getGcAssignUser() ) );
//        }
//        dmMeetingDto.setMeetingMode( entity.getMeetingMode() );
//
//        return dmMeetingDto;
//    }
}
