package com.crunii.micro.service.sysmgr.service.impl;

import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.dto.Result;
import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.entity.main.TsmPropertyValue;
import com.crunii.micro.domain.entity.main.YcqMessageTemplate;
import com.crunii.micro.domain.repo.main.YcqMessageTemplateRepo;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqMessageTemplateDTO;
import com.crunii.micro.service.sysmgr.api.domain.dto.YcqPageMessageTemplateDTO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqMessageTemplateVO;
import com.crunii.micro.service.sysmgr.api.domain.vo.YcqTemplateCodeVO;
import com.crunii.micro.service.sysmgr.dto.sysmgr.ValueReq;
import com.crunii.micro.service.sysmgr.enums.AliEventMessageType;
import com.crunii.micro.service.sysmgr.jdbc.PropertyJdbcDao;
import com.crunii.micro.service.sysmgr.jdbc.YcqMessageTemplateDao;
import com.crunii.micro.service.sysmgr.service.YcqMessageTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class YcqMessageTemplateServiceImpl implements YcqMessageTemplateService {

    @Resource
    private PropertyJdbcDao propertyJdbcDao;

    @Resource
    private YcqMessageTemplateRepo repo;

    @Resource
    private YcqMessageTemplateDao dao;

    @Override
    public YcqMessageTemplateVO insert(YcqMessageTemplateDTO dto, Worker worker){
        Assert.notEmpty(dto.getPushEndpointList(), "参数有误");
        Assert.notEmpty(dto.getPushTypeList(), "参数有误");
        Assert.notNull(dto.getSystemName(), "应用业务系统不能为空");
        Assert.notNull(dto.getSceneName(), "业务场景名称不能为空");
        Assert.notNull(dto.getTitle(), "消息标题不能为空");
        Assert.notNull(dto.getMessageTemplate(), "消息内容不能为空");
        Assert.notNull(dto.getStatus(), "状态不能为空");
//        Assert.notNull(dto.getTemplateCode(), "短信模板不能为空");
        String title = dto.getTitle();
        String messageTemplate = dto.getMessageTemplate();
        if (title.length() > 20){
            throw new BusinessException("标题不能超过20字符，请重新输入！");
        }
        if (messageTemplate.length() > 200){
            throw new BusinessException("模板不能超过200字符，请重新输入！");
        }
        // 查询是否重复
        YcqMessageTemplate ycqMessageTemplate = new YcqMessageTemplate();
        BeanUtils.copyProperties(dto, ycqMessageTemplate);
        // 插入数据
        String pushEndPoints = String.join(",", dto.getPushEndpointList());
        String pushTypes = String.join(",", dto.getPushTypeList());
        ycqMessageTemplate.setPushType(pushTypes);
        ycqMessageTemplate.setPushEndpoint(pushEndPoints);
        ycqMessageTemplate.setCreateId(worker.getLoginId());
        ycqMessageTemplate.setOrgId(worker.getOrgId());
        ycqMessageTemplate.setCreateTime(new Date());
        ycqMessageTemplate.setTemplateCode(dto.getTemplateCode());
        YcqMessageTemplate ycqMessageTemplate1 = repo.saveAndFlush(ycqMessageTemplate);

        YcqMessageTemplateVO ycqMessageTemplateVO = new YcqMessageTemplateVO();
        BeanUtils.copyProperties(dto, ycqMessageTemplateVO);
        ycqMessageTemplateVO.setTemplateId(ycqMessageTemplate1.getTemplateId());
        return ycqMessageTemplateVO;
    }

    @Override
    public YcqMessageTemplateVO update(YcqMessageTemplateDTO dto, Integer loginId){
        // 查询是否重复（非本主键）
        Assert.notNull(dto.getAppId(), "参数有误");
        Assert.notNull(dto.getTemplateId(), "参数有误");
        List<YcqMessageTemplate> ycqMessageTemplates = dao.queryByAppId(dto.getAppId());
        long count = ycqMessageTemplates.stream().filter(item -> !Objects.equals(item.getTemplateId(), dto.getTemplateId()) && Objects.equals(item.getSceneName(), dto.getSceneName()) && Objects.equals(item.getTitle(), dto.getTitle())).count();
        if (count > 0){
            throw new BusinessException("无法修改，当前业务系统和场景下存在相同消息标题！");
        }
        YcqMessageTemplate update = ycqMessageTemplates.stream().filter(item -> Objects.equals(item.getTemplateId(), dto.getTemplateId())).findFirst().get();
        // 修改数据

        update.setUpdateTime(new Date());
        update.setUpdateId(loginId);
        String pushEndPoints = String.join(",", dto.getPushEndpointList());
        String pushTypes = String.join(",", dto.getPushTypeList());
        update.setAppId(dto.getAppId());
        update.setSceneName(dto.getSceneName());
        update.setTitle(dto.getTitle());
        update.setMessageTemplate(dto.getMessageTemplate());
        update.setPushType(pushTypes);
        update.setPushEndpoint(pushEndPoints);
        update.setStatus(dto.getStatus());
        update.setTemplateType(dto.getTemplateType());
        update.setTemplateCode(dto.getTemplateCode());
        repo.saveAndFlush(update);

        YcqMessageTemplateVO ycqMessageTemplateVO = new YcqMessageTemplateVO();
        BeanUtils.copyProperties(dto, ycqMessageTemplateVO);
        return ycqMessageTemplateVO;
    }

    @Override
    public YcqMessageTemplateVO updateStatus(YcqMessageTemplateDTO dto, Integer loginId){
        Long templateId = dto.getTemplateId();
        Assert.notNull(templateId, "参数有误");
        YcqMessageTemplate one = repo.getOne(templateId);
        if (null == one){
            throw new BusinessException("信息异常，请联系管理员");
        }
        one.setStatus(dto.getStatus());
        repo.saveAndFlush(one);
        YcqMessageTemplateVO vo = new YcqMessageTemplateVO();
        BeanUtils.copyProperties(one, vo);
        return vo;
    }

    @Override
    public boolean deleteBatch(List<Long> ids, Integer loginId) {
        dao.deleteBatch(ids, loginId);
        return true;
    }

    /**
     * 分页查询所有
     * @return
     */
    @Override
    public PageRsp<YcqMessageTemplateVO> pageByCondition(PageReq<YcqPageMessageTemplateDTO> req, Integer loginId){
        // 分页查询数据
        return dao.pageQuery(req, loginId);
    }

    @Override
    public List<YcqTemplateCodeVO> pageTemplateCode() {
        List<YcqTemplateCodeVO> templateCodeList = new ArrayList<>();

        // 获取枚举类中的所有枚举值
        AliEventMessageType[] eventMessageTypes = AliEventMessageType.values();

        for (AliEventMessageType messageType : eventMessageTypes) {
            YcqTemplateCodeVO templateCodeVO = new YcqTemplateCodeVO();
            templateCodeVO.setTemplateCode(messageType.getCode());
            templateCodeVO.setTemplateName(messageType.getDescription());

            templateCodeList.add(templateCodeVO);
        }

        return templateCodeList;
    }


    private String getValue(Integer id, String code){
        ValueReq valueReq = new ValueReq();
        valueReq.setPropCode(code);
        PageReq<ValueReq> pageRsp = new PageReq<>();
        pageRsp.setQuery(valueReq);
        PageRsp<TsmPropertyValue> tsmPropertyValuePageRsp = propertyJdbcDao.pageValue(pageRsp);
        List<TsmPropertyValue> values = tsmPropertyValuePageRsp.getResult();
        if (CollectionUtils.isEmpty(values)){
            throw new BusinessException("未完善配置信息，请联系管理员");
        }
        List<TsmPropertyValue> collect = values.stream().filter(item -> Objects.equals(item.getValueCode(), String.valueOf(id))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            throw new BusinessException("未查询到该位置配置，请联系管理员");
        }
        return collect.get(0).getValueName();
    }
}
