package com.yonge.cooleshow.admin.controller;


import com.alibaba.fastjson.JSONObject;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.biz.dal.dto.ImGroupSearchDto;
import com.yonge.cooleshow.biz.dal.entity.ImGroup;
import com.yonge.cooleshow.biz.dal.entity.ImHistoryMessage;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.redis.service.RedisCache;
import com.yonge.toolset.utils.date.DateUtil;
import com.yonge.toolset.utils.validator.ValidationKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 即时通讯群组(ImGroup)表控制层
 *
 * @author zx
 * @since 2022-03-22 10:45:56
 */
@Api(tags = "即时通讯群组")
@RestController
@Slf4j
@RequestMapping("${app-config.url.admin:}/imGroup")
public class ImGroupController extends BaseController {
    /**
     * 服务对象
     */
    @Autowired
    private ImGroupService imGroupService;
    @Autowired
    private SysUserService sysUserService;



    @Autowired
    private RedisCache redisCache;

    @ApiOperation("获取群详情")
    @PostMapping(value = "/getDetail/{groupId}")
    @PreAuthorize("@pcs.hasPermissions('imGroup/detail')")
    public HttpResponseResult<ImGroup> getDetail(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId) throws Exception {
        ImGroup group = imGroupService.getGroupById(groupId);
        if (group == null) {
            return failed(HttpStatus.NO_CONTENT, "群组不存在");
        }
        return succeed(group);
    }

    @ApiOperation("群列表")
    @PostMapping(value = "/queryAll")
    @PreAuthorize("@pcs.hasPermissions('imGroup/queryAll')")
    public HttpResponseResult<List<ImGroup>> queryAll(@Valid @RequestBody ImGroupSearchDto imGroupSearchDto, BindingResult bindingResult) throws Exception {
        ValidationKit.ignoreFields(bindingResult,"createUserId");
        imGroupSearchDto.setUserId(sysUserService.getUserId());
        return succeed(imGroupService.queryAll(imGroupSearchDto));
    }

    @ApiOperation("退出群聊")
    @PostMapping(value = "/quit/{groupId}")
    public HttpResponseResult quit(@ApiParam(value = "群编号", required = true) @PathVariable("groupId") String groupId,
                                   @RequestParam(value = "quit",required = false, defaultValue = "false") boolean quit
                                   ) throws Exception {
        imGroupService.quit(groupId,sysUserService.getUserId(), ClientEnum.STUDENT, quit);
        return succeed();
    }


    @GetMapping(value = "/syncImHistoryMessageTask")
    // 融云同步即时通讯聊天记录
    public void syncImHistoryMessageTask(String date) throws Exception {
        if (date == null) {
            date = DateUtil.format(DateUtil.addHours(new Date(), -2), DateUtil.YEAR_MONTH_DAY_HOUR);
        }
        // 获取输入日期
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
        Date currentDate = format.parse(date);

        // 创建Calendar对象 设置为输入时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);

        // 将日期减少三天
        calendar.add(Calendar.DATE, -3);

        // 获取减少三天后的日期
        Date targetTime = calendar.getTime();

        calendar.setTime(currentDate);

        //按照小时递减
        while (currentDate.after(targetTime)) {
            imGroupService.getAndSaveImHistoryMessage(DateUtil.format(currentDate, DateUtil.YEAR_MONTH_DAY_HOUR));
            calendar.add(Calendar.HOUR, -1);
            currentDate = calendar.getTime();
        }

    }

    @ApiOperation("IM导入消息")
    @PostMapping(value = "/ImportIM")
    public void ImportIM() throws Exception {

        CompletableFuture.runAsync(() -> {
            try {
                List<ImHistoryMessage> info;
                //计算总数据量
                int count = imGroupService.queryCount();
                //计算调用次数
//                int num = (int) Math.ceil(count / 100);
//                for (int i = 1; i <=num ; i++) {
//                    int page =i;
//                    int size =100;
//                    //获取融云消息
//                    //List<ImGroup> list = imGroupService.lambdaQuery().last("limit "+(page-1)*size+","+size).list();
//                    info = imGroupService.getRongYunInfo(page,size);
//                    //IM导入
//                    imGroupService.importInfo(info);
//                }
                info = imGroupService.getRongYunInfo(1,count);
                //IM导入
                imGroupService.importInfo(info);
            } catch (Exception e) {
                log.error("IM导入消息失败", e);
            }
        });
    }


    @ApiOperation("清除导入会话")
    @PostMapping(value = "/clearImportIm")
    public void clearImportIm() throws Exception {

        CompletableFuture.runAsync(() -> {
            try {
                List<ImHistoryMessage> info;
                //计算总数据量
                int count = imGroupService.queryCount();
                //计算调用次数
//                int num = (int) Math.ceil(count / 100);
//                for (int i = 1; i <=num ; i++) {
//                    int page =i;
//                    int size =100;
//                    //获取融云消息
//                    //List<ImGroup> list = imGroupService.lambdaQuery().last("limit "+(page-1)*size+","+size).list();
//                    info = imGroupService.getRongYunInfo(page,size);
//                    //IM导入
//                    imGroupService.importInfo(info);
//                }
                info = imGroupService.getRongYunInfo(1,count);
                //IM导入
                imGroupService.clearImportIm(info);
            } catch (Exception e) {
                log.error("IM导入消息失败", e);
            }
        });
    }
    @GetMapping(value = "/groupTransfer")
    @ApiOperation("群导入")
    public void groupTransfer() {
        CompletableFuture.runAsync(() -> {
            try {
                imGroupService.groupTransfer();
            } catch (Exception e) {
                log.error("群导入失败", e);
            }
        });
    }

    @GetMapping(value = "/importUser")
    @ApiOperation("导入用户")
    public void importUser() {
        imGroupService.importUser();
    }


    @ApiOperation("群头像更新")
    @PostMapping(value = "/groupAvatarUpdate")
    public R<JSONObject> groupAvatarUpdate() {
        CompletableFuture.runAsync(() -> {
            imGroupService.groupAvatarUpdate();
        });
        return R.defaultR();
    }


}

