package com.yeejoin.amos.boot.module.common.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FeedbackSuggestionsDto;
import com.yeejoin.amos.boot.module.common.api.entity.FeedbackSuggestions;
import com.yeejoin.amos.boot.module.common.api.enums.ProblemTypeEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.FeedbackSuggestionsMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFeedbackSuggestionsService;
import com.yeejoin.amos.boot.module.common.api.vo.FeedbackSuggestionsVo;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 反馈建议表服务实现类
 *
 * @author system_generator
 * @date 2025-05-15
 */
@Service
public class FeedbackSuggestionsServiceImpl extends BaseService<FeedbackSuggestions, FeedbackSuggestions, FeedbackSuggestionsMapper> implements IFeedbackSuggestionsService {

    @Autowired
    private EmqKeeper emqKeeper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FeedbackSuggestionsMapper feedbackSuggestionsMapper;

    private static final String FEEDBACK_SUGGEST_TOPIC = "/topic/feedback/suggest";

    /**
     * 当前登录用户信息
     *
     * @return 当前登录用户信息
     */
    protected ReginParams getSelectedOrgInfo() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }

    /**
     * 保存反馈建议
     *
     * @param dto 实体
     * @return result
     */
    public FeedbackSuggestions saveFeedbackSuggestions(FeedbackSuggestionsDto dto) {
        FeedbackSuggestions suggestions = new FeedbackSuggestions();
        CompanyBo company = getSelectedOrgInfo().getCompany();
        AgencyUserModel userModel = getSelectedOrgInfo().getUserModel();
        suggestions.setCreateUserId(userModel.getUserId());
        suggestions.setCreateUserName(userModel.getRealName());
        suggestions.setCreateDate(new Date());
        suggestions.setIsDelete(Boolean.FALSE);
        CompanyModel parentCompany = Privilege.companyClient.seleteOne(company.getParentId()).getResult();
        if (!ValidationUtil.isEmpty(parentCompany)) {
            suggestions.setSuperviseOrgCode(parentCompany.getOrgCode());
            suggestions.setSuperviseOrgName(parentCompany.getCompanyName());
        }
        suggestions.setCompanyCode(company.getCompanyCode());
        suggestions.setCompanyName(company.getCompanyName());
        suggestions.setReporterUserId(Objects.toString(userModel.getUserId()));
        suggestions.setReporterUserName(userModel.getUserName());
        suggestions.setProblemType(dto.getProblemType());
        suggestions.setProblemDescription(dto.getProblemDescription());
        suggestions.setContactPerson(dto.getContactPerson());
        suggestions.setContactPhone(dto.getContactPhone());
        suggestions.setFiles(JSONObject.toJSONString(dto.getFiles()));
        // 回复状态（1：回复，0：未回复）
        suggestions.setStatus(Objects.toString(0));
        this.save(suggestions);
        // 发布消息
        sendMsg(suggestions);
        return suggestions;
    }

    public void sendMsg(FeedbackSuggestions suggestions) {
        try {
            emqKeeper.getMqttClient().publish(FEEDBACK_SUGGEST_TOPIC, JSONObject.toJSONString(suggestions).getBytes("UTF-8"), 2, false);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 分页查询
     */
    public IPage<FeedbackSuggestions> queryForFeedbackSuggestionsPage(int current, int size, String status) {
        CompanyBo company = this.getSelectedOrgInfo().getCompany();
        String companyType = company.getCompanyType();

        IPage<FeedbackSuggestions> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        IPage<FeedbackSuggestions> result = new Page<>();
        // 企业查询自己所有的反馈消息
        if (!companyType.equals("监管机构")) {
            result = this.lambdaQuery()
                    .eq(FeedbackSuggestions::getCompanyCode, company.getCompanyCode())
                    .eq(!ValidationUtil.isEmpty(status), FeedbackSuggestions::getStatus, status)
                    .orderByDesc(FeedbackSuggestions::getCreateDate)
                    .page(page);
        }
        // 监管单位查询自己管辖区域的所有反馈消息
        if (companyType.equals("监管机构")) {
            result = this.lambdaQuery()
                    .likeRight(FeedbackSuggestions::getSuperviseOrgCode, company.getOrgCode())
                    .eq(!ValidationUtil.isEmpty(status), FeedbackSuggestions::getStatus, status)
                    .orderByDesc(FeedbackSuggestions::getCreateDate)
                    .page(page);
        }
        result.getRecords().forEach(suggestions -> {
            suggestions.setProblemType(ProblemTypeEnum.getById(Integer.parseInt(suggestions.getProblemType())).getDescription());
            suggestions.setStatus("1".equals(suggestions.getStatus()) ? "已回复" : "待回复");
            suggestions.setFilesArr(JSONObject.parseArray(suggestions.getFiles()));
            suggestions.setCompanyType(feedbackSuggestionsMapper.getCompanyTypeByCompanyCode(suggestions.getCompanyCode()));
            suggestions.setCompanySeq(feedbackSuggestionsMapper.getCompanySeqByCompanyCode(suggestions.getCompanyCode()));
        });
        return result;
    }

    /**
     * 数据导出
     * @param response result
     */
    public void dataExport(HttpServletResponse response) {
        CompanyBo company = this.getSelectedOrgInfo().getCompany();
        String companyType = company.getCompanyType();
        List<FeedbackSuggestions> feedbackSuggestions = Collections.emptyList();
        // 企业查询自己所有的反馈消息
        if (!companyType.equals("监管机构")) {
            feedbackSuggestions = this.lambdaQuery()
                    .eq(FeedbackSuggestions::getCompanyCode, company.getCompanyCode())
                    .eq(FeedbackSuggestions::getIsDelete, Boolean.FALSE)
                    .orderByDesc(FeedbackSuggestions::getCreateDate)
                    .list();
        }
        // 监管单位查询自己管辖区域的所有反馈消息
        if (companyType.equals("监管机构")) {
            feedbackSuggestions = this.lambdaQuery()
                    .likeRight(FeedbackSuggestions::getSuperviseOrgCode, company.getOrgCode())
                    .eq(FeedbackSuggestions::getIsDelete, Boolean.FALSE)
                    .orderByDesc(FeedbackSuggestions::getCreateDate)
                    .list();
        }
        feedbackSuggestions.forEach(suggestion -> {
            suggestion.setProblemType(ProblemTypeEnum.getById(
                    Integer.parseInt(suggestion.getProblemType())).getDescription());
            suggestion.setStatus("1".equals(suggestion.getStatus()) ? "已回复" : "待回复");
        });
        List<FeedbackSuggestionsVo> suggestionsVo = feedbackSuggestions.stream()
                .map(suggestion -> {
                    FeedbackSuggestionsVo vo = new FeedbackSuggestionsVo();
                    vo.setProblemType(suggestion.getProblemType());
                    vo.setProblemDescription(suggestion.getProblemDescription());
                    vo.setCompanyName(suggestion.getCompanyName());
                    vo.setStatus(suggestion.getStatus());
                    vo.setCreateDate(suggestion.getCreateDate());
                    vo.setReporterUserName(suggestion.getReporterUserName());
                    vo.setContactPerson(suggestion.getContactPerson());
                    vo.setContactPhone(suggestion.getContactPhone());
                    return vo;
                })
                .collect(Collectors.toList());
        ExcelUtil.createTemplate(response, "反馈建议数据", "问题项", suggestionsVo, FeedbackSuggestionsVo.class, null, false);
    }
}