package com.mortals.xhx.module.feedback.web;

import cn.hutool.core.date.DateUtil;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.feedback.model.*;
import com.mortals.xhx.module.feedback.model.vo.FeedbackStaffInfoVo;
import com.mortals.xhx.module.feedback.model.vo.OptionSummaryVo;
import com.mortals.xhx.module.feedback.model.vo.QuestionAnswerVo;
import com.mortals.xhx.module.feedback.service.FeedbackAnswerService;
import com.mortals.xhx.module.feedback.service.FeedbackOptionService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.mortals.framework.model.Context;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.module.feedback.service.FeedbackService;
import org.apache.commons.lang3.ArrayUtils;
import com.mortals.framework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.mortals.framework.ap.SysConstains.*;

/**
 * 绩效反馈记录信息
 *
 * @author zxfei
 * @date 2023-07-05
 */
@RestController
@RequestMapping("feedback")
public class FeedbackController extends BaseCRUDJsonBodyMappingController<FeedbackService, FeedbackEntity, Long> {

    @Autowired
    private ParamService paramService;

    @Autowired
    private FeedbackOptionService feedbackOptionService;

    @Autowired
    private FeedbackAnswerService feedbackAnswerService;

    public FeedbackController() {
        super.setModuleDesc("绩效反馈记录信息");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        Map<String, String> backStatus = new HashMap<>();
        backStatus.put("0", "未反馈");
        backStatus.put("1", "已反馈");
        this.addDict(model, "processStatus", paramService.getParamBySecondOrganize("Feedback", "processStatus"));
        this.addDict(model, "weblink", paramService.getParamBySecondOrganize("Feedback", "weblink"));
        this.addDict(model, "backStatus", backStatus);
        super.init(model, context);
    }

    @Override
    protected int infoAfter(Long id, Map<String, Object> model, FeedbackEntity entity, Context context) throws AppException {
        if (CollectionUtils.isNotEmpty(entity.getFeedbackQuestionList())) {
            for (FeedbackQuestionEntity item : entity.getFeedbackQuestionList()) {
                List<FeedbackOptionEntity> optionEntities = feedbackOptionService.find(new FeedbackOptionQuery().questionId(item.getId()));
                item.setFeedbackOptionList(optionEntities);
            }
        }

        if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
            List<FeedbackAnswerEntity> feedbackAnswerEntities = feedbackAnswerService.find(new FeedbackAnswerQuery().feedbackId(entity.getId()).staffId(context.getUser().getCustomerId()));
            if (!ObjectUtils.isEmpty(feedbackAnswerEntities)) {
                entity.setFeedbackAnswerList(feedbackAnswerEntities);
            }
        }

        if(entity!=null) {
            Date feedbackTimeStart = entity.getFeedbackTimeStart();
            Date feedbackTimeEnd = entity.getFeedbackTimeEnd();

            if (DateUtil.compare(new Date(), feedbackTimeStart) < 0) {
                entity.setProcessStatus(0);
            }

            boolean in = DateUtil.isIn(new Date(), entity.getFeedbackTimeStart(), entity.getFeedbackTimeEnd());
            if (in) {
                entity.setProcessStatus(1);
            }

            if (DateUtil.compare(new Date(), feedbackTimeEnd) > 0) {
                entity.setProcessStatus(2);
            }
        }

        return super.infoAfter(id, model, entity, context);
    }

    /**
     * 查询问卷反馈人员列表
     *
     * @param query
     * @return
     */
    @PostMapping({"getStaffList"})
    @UnAuth
    public Rest<Object> getFeedbackStaffList(@RequestBody FeedbackEntity query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询问卷反馈人员列表";

        int code = 1;
        try {
            PageInfo pageInfo = this.buildPageInfo(query);
            Result<FeedbackStaffInfoVo> result = this.getService().getFeedbackStaffList(query, pageInfo);
            if (CollectionUtils.isNotEmpty(result.getList())) {
//                Map<Integer, List<FeedbackStaffInfoVo>> groupMap = result.getList().stream().collect(Collectors.groupingBy(FeedbackStaffInfoVo::getBackStatus));
//                if (groupMap.containsKey(1)) {
//                    model.put("feedBack", groupMap.get(1).size());
//                } else {
//                    model.put("feedBack", 0);
//                }
//                if (groupMap.containsKey(0)) {
//                    model.put("notBack", groupMap.get(0).size());
//                } else {
//                    model.put("notBack", 0);
//                }
                query.setBackStatus(1);
                PageInfo noPageInfo = new PageInfo(-1);
                Result<FeedbackStaffInfoVo> feedBack = this.getService().getFeedbackStaffList(query, noPageInfo);
                query.setBackStatus(0);
                Result<FeedbackStaffInfoVo> notBack = this.getService().getFeedbackStaffList(query, noPageInfo);
                if(CollectionUtils.isNotEmpty(feedBack.getList())){
                    model.put("feedBack", feedBack.getList().size());
                }else {
                    model.put("feedBack", 0);
                }
                if(CollectionUtils.isNotEmpty(notBack.getList())){
                    model.put("notBack", notBack.getList().size());
                }else {
                    model.put("notBack", 0);
                }
            } else {
                model.put("feedBack", 0);
                model.put("notBack", 0);
            }
            model.put("data", result.getList());
            model.put("pageInfo", result.getPageInfo());
            this.parsePageInfo(model, result.getPageInfo());
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }
        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    /**
     * 问卷单选多选反馈统计
     *
     * @param feedbackId
     * @return
     */
    @RequestMapping(value = {"getOptionSummaryList"}, method = {RequestMethod.POST, RequestMethod.GET})
    @UnAuth
    public Rest<Object> getOptionSummaryList(Long feedbackId) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询问卷单选多选反馈统计";

        int code = 1;
        try {
            List<OptionSummaryVo> result = this.getService().getOptionSummaryList(feedbackId);
            List<OptionSummaryVo> list = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(result)) {
                Map<Long, List<OptionSummaryVo>> groupMap = result.stream().collect(Collectors.groupingBy(OptionSummaryVo::getQuestionId));
                for (Long key : groupMap.keySet()) {
                    OptionSummaryVo vo = new OptionSummaryVo();
                    OptionSummaryVo temp = groupMap.get(key).get(0);
                    vo.setQuestionId(key);
                    vo.setQuestion(temp.getQuestion());
                    vo.setFeedbackId(temp.getFeedbackId());
                    vo.setQuestionType(temp.getQuestionType());
                    vo.setOptionList(groupMap.get(key));
                    list.add(vo);
                }
            }
            model.put("data", list);
            model.put("message_info", busiDesc + "成功");
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }
        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    /**
     * 问卷问题反馈详情
     *
     * @param query
     * @return
     */
    @PostMapping({"getQuestionAnswerList"})
    @UnAuth
    public Rest<Object> getQuestionAnswerList(@RequestBody FeedbackEntity query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询问卷问题反馈详情";

        int code = 1;
        try {
            PageInfo pageInfo = this.buildPageInfo(query);
            Result<QuestionAnswerVo> result = this.getService().getQuestionAnswerList(query.getQuestionId(), pageInfo);
            model.put("data", result.getList());
            model.put("pageInfo", result.getPageInfo());
            this.parsePageInfo(model, result.getPageInfo());
            model.put("message_info", busiDesc + "成功");
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    /**
     * 反馈记录整体情况统计
     *
     * @return
     */
    @PostMapping({"summary"})
    @UnAuth
    public Rest<Object> summary() {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询反馈记录整体情况统计";

        int code = 1;
        try {
            Map<String, Integer> result = this.getService().summaryFeedback();
            model.put("data", result);
            model.put("message_info", busiDesc + "成功");
            if (!ObjectUtils.isEmpty(context) && !ObjectUtils.isEmpty(context.getUser())) {
                this.recordSysLog(this.request, busiDesc + " 【成功】");
            }
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        this.init(model, context);
        ret.setCode(code);
        ret.setData(model.get("data"));
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }
}