package com.hys.app.controller.erp.use;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hys.app.controller.erp.use.msg.MessageReceiveTypeEnum;
import com.hys.app.converter.erp.SmsMailConverter;
import com.hys.app.framework.context.user.AdminUserContext;
import com.hys.app.framework.database.BaseQueryParam;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.BeanUtils;
import com.hys.app.model.erp.dos.MessageReceiveDO;
import com.hys.app.model.erp.dos.SmsMailTemplate;
import com.hys.app.model.erp.dto.BandTemplateDTO;
import com.hys.app.model.erp.dto.SmsMailTemplateDTO;
import com.hys.app.model.erp.entity.CompanyBandMsg;
import com.hys.app.model.erp.enums.MsgTypeEnum;
import com.hys.app.model.erp.vo.SmsMailTemplateQuery;
import com.hys.app.model.erp.vo.SmsMailTemplateVO;
import com.hys.app.model.support.LogClient;
import com.hys.app.model.support.validator.annotation.Log;

import com.hys.app.model.system.dos.AdminUser;
import com.hys.app.model.system.vo.Menus;
import com.hys.app.service.erp.*;
import com.hys.app.service.system.AdminUserManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "消息  消息模板")
@RestController
@RequestMapping("/admin/erp/SmsMailTemplate")
@AllArgsConstructor
public class SmsMailController {

    private SmsMailManager smsMailManager;
    private MailSmsCountManager mailSmsCountManager;
    private MessageReceiveManager messageReceiveManager;
    private AdminUserManager adminUserManager;
    private CompanyBandMsgManager companyBandMsgManager;
    private RedisTemplate redisTemplate;

    @PostMapping("createTemplate")
    @ApiOperation(value = "创建模板")
    @Log(client = LogClient.admin, detail = "创建名称为[${smsMailTemplateDTO.name}]的模板")
    public Long createTemplate(@Valid @RequestBody SmsMailTemplateDTO smsMailTemplateDTO) {
        return smsMailManager.createTemplate(smsMailTemplateDTO);
    }

    @PostMapping("updateTemplate/{id}")
    @ApiOperation(value = "修改模板")
    @Log(client = LogClient.admin, detail = "修改名称为[${companyDO.name}]的公司信息")
    public Long updateTemplate(@Valid @RequestBody SmsMailTemplateDTO smsMailTemplateDTO, @PathVariable Long id) {
        return smsMailManager.updateTemplate(smsMailTemplateDTO, id);
    }

    @GetMapping("getById/{id}")
    @ApiOperation(value = "获取模板信息")
    public SmsMailTemplateVO renewCompanyDifference(@PathVariable Long id) {
        return SmsMailConverter.INSTANCE.convert(smsMailManager.getById(id));
    }

    @GetMapping()
    @ApiOperation(value = "模板分页")
    public IPage<SmsMailTemplateVO> queryTemplate(SmsMailTemplateQuery query) {
        return smsMailManager.queryTemplate(query);
    }


    @GetMapping("getSysNotBand/{type}")
    @ApiOperation(value = "创建邮件消息和短信消息获取未绑定的系统消息")
    public List<SmsMailTemplate> getSysNotBand(@PathVariable MsgTypeEnum type) {
        return smsMailManager.getSysNotBand(type);
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "删除模板")
    public void delete(@PathVariable Long id) {
        smsMailManager.delete(id);
    }

    @PostMapping("alterStatus/{id}")
    @ApiOperation(value = "修改模板状态")
    public void alterStatus(@PathVariable Long id) {
        SmsMailTemplate byId = smsMailManager.getById(id);
        byId.setEnableStatus(!byId.getEnableStatus());
        smsMailManager.updateById(byId);
    }

//    @GetMapping("getSendNumByCompany")
//    @ApiOperation(value = "")
//    public IPage<MailSmsCountVO> getSendNumByCompany(MailSmsCountQuery query) {
//        return mailSmsCountManager.getPage(query);
//    }

    @GetMapping("getSendNumByCompany")
    @ApiOperation(value = "获取模板树状图，勾选之后和公司绑定")
    public List<SmsMailTemplateVO> getTemplateTree() {
        List<SmsMailTemplateVO> bean = BeanUtils.toBean(smsMailManager.list(), SmsMailTemplateVO.class);

        List<CompanyBandMsg> list = companyBandMsgManager.list(new LambdaQueryWrapper<CompanyBandMsg>()
                .eq(CompanyBandMsg::getCompanyId, AdminUserContext.getCompanyId()));
        if (CollUtil.isNotEmpty(list)){
            for (CompanyBandMsg msg : list) {
                for (SmsMailTemplateVO smsMailTemplateVO : bean) {
                    if (msg.getHasSelect() && msg.getTemplateId().equals(smsMailTemplateVO.getId())){
                        smsMailTemplateVO.setHasSelect(true);
                    }
                }
            }
        }
        for (SmsMailTemplateVO templateVO : bean) {
            if (templateVO.getType().equals(MsgTypeEnum.SYSTEM)){
                templateVO.setHasSelect(true);
            }
            templateVO.setChild(bean.stream().filter(item -> item.getPid().equals(templateVO.getId())).collect(Collectors.toList()));
        }
        return bean.stream().filter(item ->item.getPid() == 0).collect(Collectors.toList());
    }

    @PostMapping("updateSelectMsg")
    @ApiOperation(value = "公司选中的模板")
    @Log(client = LogClient.admin, detail = "修改了消息配置")
    public void updateSeletMsg(@RequestBody BandTemplateDTO dto) {
        AdminUserContext.hasSuperAdminQuery(dto.getCompanyId());
        AdminUser model = adminUserManager.getModel(AdminUserContext.getAdminUserId());
        if (!model.getUsername().equals("admin")) {
            throw new ServiceException("只能admin账号才能进行此操作");
        }
        List<SmsMailTemplateVO> arrayList = new ArrayList<>();
        for (SmsMailTemplateVO vo : dto.getVos()) {
            if (CollUtil.isNotEmpty(vo.getChild())){
                arrayList.add(vo);
                getChild(arrayList,vo);
            }else {
                arrayList.add(vo);
            }
            if (vo.getType().equals(MsgTypeEnum.SYSTEM)) {
                vo.setHasSelect(true);
            }
        }
        Set<SmsMailTemplateVO> collect = new HashSet<>(arrayList);
        List<CompanyBandMsg> list = new ArrayList<>();
        for (SmsMailTemplateVO vo : collect) {
            CompanyBandMsg companyBandMsg = new CompanyBandMsg();
            companyBandMsg.setCompanyId(AdminUserContext.getCompanyId());
            companyBandMsg.setTemplateId(vo.getId());
            companyBandMsg.setTemplateCode(vo.getCode());
            companyBandMsg.setHasSelect(vo.getHasSelect());
            list.add(companyBandMsg);
        }
        companyBandMsgManager.remove(new LambdaQueryWrapper<CompanyBandMsg>().eq(CompanyBandMsg::getCompanyId,AdminUserContext.getCompanyId()));
        companyBandMsgManager.saveBatch(list);
        redisTemplate.opsForHash().delete("companyTemplate", model.getCompanyId().toString());
        redisTemplate.opsForHash().put("companyTemplate",AdminUserContext.getCompanyId().toString(),list.stream().filter(CompanyBandMsg::getHasSelect).collect(Collectors.toList()));
    }

    private void getChild(List<SmsMailTemplateVO> list, SmsMailTemplateVO vo) {
        for (SmsMailTemplateVO child : vo.getChild()) {
            list.add(child);
            getChild(list, child);
        }
    }



//    @GetMapping("getMessageByTypeCompany/{type}")
//    @ApiOperation(value = "获取各公司发的消息记录")
//    public IPage<MessageReceiveDO> getMessageByTypeCompany(BaseQueryParam query, @PathVariable String type) {
//        return messageReceiveManager.getPage(query, type);
//    }

    @GetMapping("countNotReadSys")
    @ApiOperation(value = "统计自己账号所有未读的消息")
    public long countNotReadSys() {
        return messageReceiveManager.count(new LambdaQueryWrapper<MessageReceiveDO>()
                .eq(MessageReceiveDO::getUserId, AdminUserContext.getAdminUserId())
                .eq(MessageReceiveDO::getType, MessageReceiveTypeEnum.SYSTEM)
                .eq(MessageReceiveDO::getStatus, false));
    }

    @GetMapping("getSysMsgByOwn/{type}")
    @ApiOperation(value = "获取自己所有的消息")
    public IPage<MessageReceiveDO> getMessageByTypeCompany(BaseQueryParam query ,  @PathVariable MessageReceiveTypeEnum type) {
        //把自己所有的消息全部设置为已读
        MessageReceiveDO messageReceiveDO = new MessageReceiveDO();
        messageReceiveDO.setStatus(true);
        messageReceiveManager.update(messageReceiveDO, new LambdaQueryWrapper<MessageReceiveDO>()
                .eq(MessageReceiveDO::getUserId, AdminUserContext.getAdminUserId())
                .eq(MessageReceiveDO::getType, MessageReceiveTypeEnum.SYSTEM));
        return messageReceiveManager.page(new Page<>(query.getPageNo(), query.getPageSize()), new LambdaQueryWrapper<MessageReceiveDO>()
                .eq(MessageReceiveDO::getUserId, AdminUserContext.getAdminUserId())
                .eq(ObjectUtil.isNotNull(type),MessageReceiveDO::getType,type)
                .orderByAsc(MessageReceiveDO::getStatus));
    }







}
