package com.artfess.xqxt.meeting.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryField;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.api.context.ICurrentContext;
import com.artfess.uc.exception.BaseException;
import com.artfess.uc.model.User;
import com.artfess.uc.util.ContextUtil;
import com.artfess.xqxt.meeting.dao.MeetingUserDao;
import com.artfess.xqxt.meeting.manager.BizMeetingAccessoryManager;
import com.artfess.xqxt.meeting.manager.MeetingManager;
import com.artfess.xqxt.meeting.manager.MeetingUserManager;
import com.artfess.xqxt.meeting.model.BizMeetingAccessory;
import com.artfess.xqxt.meeting.model.Meeting;
import com.artfess.xqxt.meeting.model.MeetingUser;
import com.artfess.xqxt.meeting.utils.SortList;
import com.artfess.xqxt.meeting.vo.FeedBackCountVo;
import com.artfess.xqxt.meeting.vo.MeetFeedBackVO;
import com.artfess.xqxt.meeting.vo.MeetingVO;
import com.aspose.slides.internal.m0.acc;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 黎沐华
 * @date 2022/11/14 17:30
 */
@Service
public class MeetingUserManagerImpl extends BaseManagerImpl<MeetingUserDao, MeetingUser> implements MeetingUserManager {

    @Resource
    private MeetingManager meetingManager;

    @Resource
    private BizMeetingAccessoryManager meetingAccessoryManager;

    @Resource
    private MeetingUserDao meetingUserDao;


    @Override
    public PageList<MeetingUser> findList(QueryFilter<MeetingUser> queryFilter) {
        String meetingId = null;
        List<QueryField> queryFilters = queryFilter.getQuerys();
        for (QueryField field : queryFilters){
            if ("meetingId".equals(field.getProperty())){
                meetingId = field.getValue().toString();
            }
        }
        if (StringUtils.isEmpty(meetingId)) return null;
        PageList<MeetingUser> list = this.query(queryFilter);
        List<MeetingUser> listRows = list.getRows();
        if(null != listRows && listRows.size() > 0){
            for (MeetingUser user : list.getRows()){
                if(StringUtil.isNotEmpty(user.getUserId())){
//                    user.setDeptId(ContextUtil.getCurrentDeptId(user.getUserId()));
//                    user.setDeptName(ContextUtil.getCurrentDeptName(user.getUserId()));
                    String currentDeptId = ContextUtil.getCurrentDeptId(user.getUserId());
                    if(StringUtil.isNotEmpty(currentDeptId)){
                        user.setDeptId(currentDeptId);
                        user.setDeptName(ContextUtil.getCurrentDeptName(user.getUserId()));
                    }else {
                        user.setDeptId(ContextUtil.getCurrentOrgId(user.getUserId()));
                        user.setDeptName(ContextUtil.getCurrentOrgName(user.getUserId()));
                    }
                }
                QueryWrapper<BizMeetingAccessory> accessoryQueryWrapper = new QueryWrapper<>();
                accessoryQueryWrapper.eq("IS_DELE_", "0");
                accessoryQueryWrapper.eq("SOURCE_ID_", user.getId());
//                accessoryQueryWrapper.eq("CREATE_BY_",user.getUserId());
                List<BizMeetingAccessory> bizMeetingAccessories = meetingAccessoryManager.list(accessoryQueryWrapper);
                List<BizMeetingAccessory> fileList = new ArrayList<>();
                List<BizMeetingAccessory> imageList = new ArrayList<>();
                for (BizMeetingAccessory file : bizMeetingAccessories){
                    String type = file.getSuffix();
                    if ("bmp".equals(type) || "jpg".equals(type) || "png".equals(type)){
                        file.setUrl("/image"+file.getUrl().substring(file.getUrl().indexOf("ava/file/")+8));
                        imageList.add(file);
                    }else {
                        fileList.add(file);
                    }
                }
                user.setFileList(fileList);
                user.setImageList(imageList);

            }
            //按depId升序
            SortList<MeetingUser> sortList = new SortList<MeetingUser>();
            sortList.Sort(listRows, "getDeptId", "asc");
        }
        return list;
    }

    @Override
    public void feedBack(MeetFeedBackVO meetFeedBackVO) {
        User currentUser = ContextUtil.getCurrentUser();
        String meetingId = meetFeedBackVO.getMeetingId();
        Assert.notNull(meetingId, "会议ID不能为空");
        String userId = currentUser.getId();
        if(StringUtil.isNotEmpty(meetFeedBackVO.getUserId())){
            userId = meetFeedBackVO.getUserId();
        }
        QueryWrapper<MeetingUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MEETING_ID_", meetingId).eq("USER_ID_", userId);
        List<MeetingUser> list = this.list(queryWrapper);
        if(null == list || list.size() == 0){
            throw new BaseException("未查询到您参加该会议，无需反馈！");
        }
        // 1.更新反馈状态
        for (MeetingUser meetingUser : list){
            // 设置反馈结果
            meetingUser.setFeedBack(meetFeedBackVO.getFeedBack());
            // 状态置为已反馈
            meetingUser.setFeedBackStatus("0");
            // 设置反馈时间
            meetingUser.setFeedBackDate(LocalDateTime.now());
            // 计算预计入会时间
            if(null != meetFeedBackVO.getEstimatedArrivalDate()){
                meetingUser.setEstimatedArrivalDate(meetFeedBackVO.getEstimatedArrivalDate());
                // 计算晚到时间
                Meeting meeting = meetingManager.get(meetingId);
                if(null != meeting && meeting.getStartTime() != null){
                    Duration duration = Duration.between(meeting.getStartTime(), meetFeedBackVO.getEstimatedArrivalDate());
                    //相差的分钟数
                    long minutes = duration.toMinutes();
                    meetingUser.setEstimatedArrivalTime(minutes);
                }
            }
            //反馈结果，1：准时参加会议，2：推迟参加会议，3：不能参加会议
            if(!"1".equals(meetFeedBackVO.getFeedBack())){
                // 不能入会原因
                meetingUser.setNotJoiningReasons(meetFeedBackVO.getNotJoiningReasons());
                // 2.更新反馈附件xin下
                List<String> accessoryIds = meetFeedBackVO.getAccessoryIds();
                if(null != accessoryIds && accessoryIds.size() > 0){
                    // 1.现将以前的附件数据删除状态置为1（已删除）
                    QueryWrapper<BizMeetingAccessory> oldAccessoryQueryWrapper = new QueryWrapper<>();
                    oldAccessoryQueryWrapper.eq("SOURCE_ID_", meetingUser.getId());
                    List<BizMeetingAccessory> oldBizMeetingAccessories = meetingAccessoryManager.list(oldAccessoryQueryWrapper);
                    if(null != oldBizMeetingAccessories && oldBizMeetingAccessories.size() > 0){
                        for (BizMeetingAccessory bizMeetingAccessory : oldBizMeetingAccessories){
                            bizMeetingAccessory.setIsDele("1");
                        }
                        meetingAccessoryManager.updateBatchById(oldBizMeetingAccessories);
                    }

                    // 2.将现有的置为没有删除，置为0
                    QueryWrapper<BizMeetingAccessory> accessoryQueryWrapper = new QueryWrapper<>();
                    accessoryQueryWrapper.in("ID_", accessoryIds);
                    List<BizMeetingAccessory> bizMeetingAccessories = meetingAccessoryManager.list(accessoryQueryWrapper);
                    if(null != bizMeetingAccessories && bizMeetingAccessories.size() > 0){
                        for (BizMeetingAccessory bizMeetingAccessory : bizMeetingAccessories){
                            bizMeetingAccessory.setSourceId(meetingUser.getId());
                            bizMeetingAccessory.setIsDele("0");
                        }
                        meetingAccessoryManager.updateBatchById(bizMeetingAccessories);
                    }
                }
            }else {
                // 不能入会原因设置为空
                meetingUser.setNotJoiningReasons("");
                // 预计入会时间设为空
                meetingUser.setEstimatedArrivalDate(null);
                // 晚到时间
                meetingUser.setEstimatedArrivalTime(null);
                // 2.更新反馈附件信息,删除以前的附件
                List<String> accessoryIds = meetFeedBackVO.getAccessoryIds();
                QueryWrapper<BizMeetingAccessory> accessoryQueryWrapper = new QueryWrapper<>();
                accessoryQueryWrapper.eq("SOURCE_ID_", meetingUser.getId());
                meetingAccessoryManager.remove(accessoryQueryWrapper);
            }
        }
        this.updateBatchById(list);

    }

    @Override
    public FeedBackCountVo feedBackCount(String meetingId) {
        FeedBackCountVo vo = new FeedBackCountVo();
        QueryWrapper<MeetingUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MEETING_ID_", meetingId);
        /// 总人数
        vo.setTotal(this.count(queryWrapper));
        // 已反馈
        queryWrapper.eq("FEED_BACK_STATUS_", "0");
        vo.setFeedBacked(this.count(queryWrapper));
        // 准时参加
        queryWrapper.eq("FEED_BACK_", "1");
        vo.setSignMeeting(this.count(queryWrapper));
        // 延迟入会
        queryWrapper.clear();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MEETING_ID_", meetingId);
        queryWrapper.eq("FEED_BACK_STATUS_", "0");
        queryWrapper.eq("FEED_BACK_", "2");
        vo.setDelaySignMeeting(this.count(queryWrapper));
        //不能参加会议
        queryWrapper.clear();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MEETING_ID_", meetingId);
        queryWrapper.eq("FEED_BACK_STATUS_", "0");
        queryWrapper.eq("FEED_BACK_", "3");
        vo.setUnSignMeeting(this.count(queryWrapper));
        // 未反馈
        queryWrapper.clear();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MEETING_ID_", meetingId);
        queryWrapper.eq("FEED_BACK_STATUS_", "1");
        vo.setUnFeedBacked(this.count(queryWrapper));
        return vo;
    }
}
