package com.yida.data.school.letter.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vdurmont.emoji.EmojiParser;
import com.yida.data.common.core.annotation.ControllerLog;
import com.yida.data.common.core.common.ModuleName;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.CurrentUser;
import com.yida.data.common.core.entity.letter.EduLetterBox;
import com.yida.data.common.core.entity.letter.EduLetterBoxReply;
import com.yida.data.common.core.entity.system.Dept;
import com.yida.data.common.core.entity.system.enums.OperationLogTypeEnum;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.vo.NameValueVO;
import com.yida.data.log.annotation.OperationLog;
import com.yida.data.school.dto.letterbox.LetterBoxDTO;
import com.yida.data.school.letter.mapper.EduLetterBoxMapper;
import com.yida.data.school.letter.service.EduLetterBoxService;
import com.yida.data.school.vo.letterbox.LetterBoxVO;
import com.yida.data.school.vo.letterbox.StaLetterVO;
import com.yida.data.system.feign.RemoteDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.time.LocalDate;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import org.springframework.web.client.RestTemplate;

@Api(tags = "校长信箱-后台")
@RestController
@RequestMapping("/letter/letterBox")
@RefreshScope
@RequiredArgsConstructor
public class EduLetterBoxController {

    private final EduLetterBoxService eduLetterBoxService;
    private final EduLetterBoxMapper eduLetterBoxMapper;

    private final RemoteDeptService remoteDeptService;
    @Value("${febs.topNum}")
    private Integer topNum;

    /***
     * @Author wjm
     * @Description 分页查询信箱列表
     * @Date 2020/6/10 10:07
     */
    @ApiOperation("分页查询信箱列表")
    @GetMapping("/findLetterPageList")
    public ResultBean<IPage<EduLetterBox>> findLetterPageList(@ApiParam("问题名称") @RequestParam(required = false) String title,
        @ApiParam("学校id") @RequestParam Long schoolId,
        @ApiParam("信件类型") @RequestParam(required = false) String contentType,
        @ApiParam("手机号") @RequestParam(required = false) String appPhone,
        @ApiParam("是否已回复0=否，1是") @RequestParam Integer reply,
        @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNo,
        @ApiParam("数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        //查询分页数据
        Page page = new Page();
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        return ResultBean.buildSuccess(eduLetterBoxService.findList(page, title, schoolId, contentType, appPhone, reply));
    }


    /***
     * @Author wjm
     * @Description 提交回复信息
     * @Date 2020/6/10 0:27
     */

    @ApiOperation("提交回复信息")
    @PostMapping("/submitReplyLetter")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "提交回复信息", type = OperationLogTypeEnum.INSERT)
    public ResultBean submitReplyLetter(@RequestBody EduLetterBox eduLetterBox) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        if (ObjectUtil.isEmpty(currentUser)) {
            return ResultBean.buildError("登录失败，请重新登录");
        }
        if (ObjectUtil.isEmpty(eduLetterBox.getReplyContent())) {
            return ResultBean.buildError("回复内容不能为空");
        }
        eduLetterBoxService.submitReplyLetter(eduLetterBox);
        return ResultBean.buildSuccess();
    }


    /***
     * @Author wjm
     * @Description 提交审核
     * @Date 2020/6/10 0:28
     */
    @ApiOperation("提交审核")
    @PostMapping("/submitExamineLetter")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "提交审核", type = OperationLogTypeEnum.INSERT)
    public ResultBean submitExamineLetter(@RequestBody EduLetterBox eduLetterBox) {
        EduLetterBox eduLetterBox1 = eduLetterBoxMapper.selectById(eduLetterBox.getId());
        if ("0".equals(eduLetterBox1.getStatus())) {
            return ResultBean.buildError("不能重复审核");
        }
        eduLetterBoxService.updateById(eduLetterBox);
        return ResultBean.buildSuccess();
    }


    /**
     * 撤回
     *
     * @param id
     * @return
     */
    @ApiOperation("撤回")
    @GetMapping("/retract")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "撤回", type = OperationLogTypeEnum.UPDATE)
    public ResultBean retract(@ApiParam("信箱id") @RequestParam Long id) {
        eduLetterBoxMapper.updateByReply(id);
        return ResultBean.buildSuccess();
    }


    @ApiOperation("批量公开")
    @PostMapping("/listOpenLetter")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "批量公开", type = OperationLogTypeEnum.UPDATE)
    public ResultBean listOpenLetter(@RequestBody List<Long> ids) {
        Collection<EduLetterBox> eduLetterBoxes = eduLetterBoxService.listByIds(ids);
        for (EduLetterBox eduLetterBox : eduLetterBoxes) {
            eduLetterBox.setOpen(1);
        }
        eduLetterBoxService.saveOrUpdateBatch(eduLetterBoxes);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量回复")
    @PostMapping("/listReplyLetter")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "批量回复", type = OperationLogTypeEnum.UPDATE)
    public ResultBean listReplyLetter(@RequestBody LetterBoxDTO letterBoxDTO) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        Collection<EduLetterBox> eduLetterBoxes = eduLetterBoxService.listByIds(letterBoxDTO.getIds());
        eduLetterBoxService.listReplyLetter(letterBoxDTO, eduLetterBoxes, currentUser);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("进行置顶或公开操作")
    @GetMapping(value = "updateTopOrOpen")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "进行置顶或公开操作", type = OperationLogTypeEnum.UPDATE)
    public ResultBean updateTopOrOpen(@ApiParam("信箱id") @RequestParam Long id,
        @ApiParam("学校id") @RequestParam Long schoolId,
        @ApiParam("1为置顶，null为取消置顶") @RequestParam(required = false) Integer top,
        @ApiParam("1为公开，0为取消公开") @RequestParam(required = false) Integer open) {
        CurrentUser currentUser = FebsUtil.getCurrentUser();

        if (ObjectUtil.isEmpty(currentUser)) {
            return ResultBean.buildError("登录失效请重新登录");
        }
        if (ObjectUtil.isNotEmpty(top)) {
            Integer num = eduLetterBoxMapper.getTopNum(schoolId);
            if (num >= topNum) {
                return ResultBean.buildError("置顶已达最大数量，请先取消其他置顶信件");
            }
        }
        EduLetterBox eduLetterBox = new EduLetterBox();
        eduLetterBox.setId(id);
        eduLetterBox.setTop(top);
        eduLetterBox.setOpen(open);
        eduLetterBox.setUpdateId(currentUser.getUserId());
        eduLetterBoxService.updateById(eduLetterBox);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("取消置顶")
    @GetMapping(value = "updateTop")
    @OperationLog(module = ModuleName.LETTER_BOX, methods = "取消置顶", type = OperationLogTypeEnum.UPDATE)
    public ResultBean updateTop(@ApiParam("信箱id") @RequestParam Long id,
        @ApiParam("1为置顶，null为取消置顶") @RequestParam(required = false) Integer top) {

        if (ObjectUtil.isEmpty(FebsUtil.getCurrentUser())) {
            return ResultBean.buildError("登录失效请重新登录");
        }
        eduLetterBoxMapper.updateTop(id, top);
        return ResultBean.buildSuccess();
    }

    @GetMapping("/viewLetter")
    public ResultBean viewLetter(Long id, String title,
        Integer status, String contentType) {
        EduLetterBox eduLetterBox = eduLetterBoxMapper.selectById(id);
        if (StrUtil.isNotBlank(eduLetterBox.getContent())) {
            eduLetterBox.setContent(EmojiParser.parseToUnicode(eduLetterBox.getContent()));
        }
        if (!CollectionUtils.isEmpty(eduLetterBox.getEduLetterBoxReplyList())) {
            for (EduLetterBoxReply eduLetterBoxReply : eduLetterBox.getEduLetterBoxReplyList()) {
                if (StringUtils.equals("0", eduLetterBoxReply.getReply())) {
                    eduLetterBox.setQuestionReplyMark("1");
                    break;
                }
            }
            if (Objects.isNull(eduLetterBox.getQuestionReplyMark())) {
                eduLetterBox.setQuestionReplyMark("0");
            }
        } else {
            eduLetterBox.setQuestionReplyMark("0");
        }
        CurrentUser currentUser = FebsUtil.getCurrentUser();
        EduLetterBox letterBox = new EduLetterBox();
        letterBox.setTitle(title);
        letterBox.setStatus(status);
        letterBox.setContentType(contentType);
        letterBox.setSchoolId(currentUser.getDeptId());
        // 是否显示上一条
        boolean previousShow = true;
        // 是否显示下一条
        boolean nextShow = true;
        // 上一条id
        Integer previous = null;
        // 下一条id
        Integer next = null;
        List<EduLetterBox> listViewLetter = eduLetterBoxService.findListViewLetter(letterBox);
        for (int i = 0; i < listViewLetter.size(); i++) {
            // 判断是否只有一条数据
            if (Objects.equals(listViewLetter.get(0).getId(), id) && Objects
                .equals(listViewLetter.get(listViewLetter.size() - 1).getId(), id)) {
                previousShow = false;
                nextShow = false;
                break;
            }
            // 判断是否是第一条数据
            if (Objects.equals(listViewLetter.get(0).getId(), id)) {
                previousShow = false;
                next = listViewLetter.get(1).getId().intValue();
                break;
            }

            // 判断是否是最后一条数据
            if (Objects.equals(listViewLetter.get(listViewLetter.size() - 1).getId(), id)) {
                nextShow = false;
                previous = listViewLetter.get(listViewLetter.size() - 2).getId().intValue();
                break;
            }

            if (Objects.equals(listViewLetter.get(i).getId(), id)) {
                previous = listViewLetter.get(i - 1).getId().intValue();
                next = listViewLetter.get(i + 1).getId().intValue();
                break;
            }

        }

        LetterBoxVO letterBoxVO = new LetterBoxVO();
        letterBoxVO.setEduLetterBox(eduLetterBox);
        letterBoxVO.setLetterBox(letterBox);
        letterBoxVO.setNext(next);
        letterBoxVO.setNextShow(nextShow);
        letterBoxVO.setPrevious(previous);
        letterBoxVO.setPreviousShow(previousShow);
        return ResultBean.buildSuccess(letterBoxVO);
    }

    @ApiOperation("校长信箱统计数据")
    @GetMapping("/getStaData")
    public ResultBean<StaLetterVO> getStaData(String startDate, String endDate) {
        List<Long> schoolIds = remoteDeptService.getSchoolByArea(null, null).getData().stream().map(Dept::getDeptId).collect(
            Collectors.toList());
        return ResultBean
            .buildSuccess(eduLetterBoxService.getStaData(LocalDate.parse(startDate), LocalDate.parse(endDate), schoolIds));
    }

    @ApiOperation("校长信息标题词云")
    @GetMapping("/titleCloud")
    public ResultBean<List<NameValueVO<String, Integer>>> titleCloud(String startDate, String endDate) {
        List<Long> schoolIds = remoteDeptService.getSchoolByArea(null, null).getData().stream().map(Dept::getDeptId).collect(
            Collectors.toList());
        return ResultBean.buildSuccess(eduLetterBoxService.titleCloud(startDate, endDate, schoolIds));
    }
}
