package com.mortals.xhx.busiz.h5.web;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.busiz.h5.req.FeedbackReq;
import com.mortals.xhx.busiz.h5.req.FeedbackSaveReq;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.feedback.model.*;
import com.mortals.xhx.module.feedback.service.FeedbackAnswerService;
import com.mortals.xhx.module.feedback.service.FeedbackService;
import com.mortals.xhx.module.feedback.service.FeedbackStaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.framework.ap.SysConstains.*;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;

/**
 * h5 申诉
 *
 * @author: zxfei
 * @date: 2023/7/7 15:08
 */
@RestController
@Slf4j
@RequestMapping("/api/v1/feedback")
public class FeedbackApiController extends AbstractBaseController<FeedbackReq> {

    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private FeedbackStaffService feedbackStaffService;
    @Autowired
    private FeedbackAnswerService answerService;

    /**
     * 反馈列表
     */
    @PostMapping(value = "list")
    public Rest<Object> feedbackList(@RequestBody FeedbackReq feedbackReq) {
        String busiDesc = "个人反馈列表";
        log.info("【{}】【请求体】--> {}", busiDesc, JSONObject.toJSONString(feedbackReq));
        Rest<Object> rest = Rest.ok();
        Map<String, Object> model = new HashMap<>();
        Context context = this.getContext();

        if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
            throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
        }
        try {
            if (ObjectUtils.isEmpty(feedbackReq.getFeedBackStartDate())) {
                //未设置时间的情况，默认为当月
                feedbackReq.setFeedBackStartDate(DateUtil.beginOfMonth(new Date()).toDateStr());
                feedbackReq.setFeedBackEndDate(DateUtil.today());
            } else {
                //格式化到指定日期的当月
                feedbackReq.setFeedBackStartDate(DateUtil.beginOfMonth(DateUtil.parse(feedbackReq.getFeedBackStartDate()).toJdkDate()).toDateStr());
                feedbackReq.setFeedBackEndDate(DateUtil.endOfMonth(DateUtil.parse(feedbackReq.getFeedBackStartDate()).toJdkDate()).toDateStr());
            }
            //PageInfo pageInfo = buildPageInfo(feedbackReq);
            PageInfo pageAllInfo = buildPageInfo(feedbackReq);

            if (YesNoEnum.YES.getValue() == feedbackReq.getFeedbackStatus()) {
                //已反馈
                //查询我已经回答过的
                List<Long> feedbackIdList = answerService.find(new FeedbackAnswerQuery().staffId(context.getUser().getCustomerId())).stream().map(i -> i.getFeedbackId()).distinct().collect(Collectors.toList());
                FeedbackQuery feedbackQuery = new FeedbackQuery();
                feedbackQuery.setIdList(feedbackIdList);

                Result<FeedbackEntity> result = feedbackService.find(feedbackQuery, pageAllInfo, null);
                model.put(PAGEINFO_KEY, result.getPageInfo());
                model.put(KEY_RESULT_DATA, result.getList());
                parsePageInfo(model, result.getPageInfo());
            } else {
                //未反馈
                //查询我的反馈 但是还未回答的
                List<Long> feedbackIdList = answerService.find(new FeedbackAnswerQuery().staffId(context.getUser().getCustomerId())).stream().map(i -> i.getFeedbackId()).distinct().collect(Collectors.toList());

                FeedbackStaffQuery feedbackStaffQuery = new FeedbackStaffQuery();
                feedbackStaffQuery.setFeedbackIdNotList(feedbackIdList);
                feedbackStaffQuery.setStaffId(context.getUser().getCustomerId());

                List<Long> unfinFeedbackList = feedbackStaffService.find(feedbackStaffQuery).stream().map(i -> i.getFeedbackId()).distinct().collect(Collectors.toList());
                FeedbackQuery feedbackQuery = new FeedbackQuery();
                feedbackQuery.setIdList(unfinFeedbackList);
                Result<FeedbackEntity> result = feedbackService.find(feedbackQuery, pageAllInfo, null);


                model.put(PAGEINFO_KEY, result.getPageInfo());
                model.put(KEY_RESULT_DATA, result.getList());
                parsePageInfo(model, result.getPageInfo());
            }
            rest.setData(model);
            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }

    /**
     * 反馈问卷新增
     */
    @PostMapping(value = "save")
    public Rest<FeedbackEntity> feedbackAnswerSave(@RequestBody FeedbackSaveReq req) {
        Context context = this.getContext();
        String busiDesc = "反馈回答";
        Rest<FeedbackEntity> rest = Rest.ok(busiDesc + " 【成功】");
        try {
            if (ObjectUtils.isEmpty(context) || ObjectUtils.isEmpty(context.getUser())) {
                throw new AppException(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT);
            }
            if (ObjectUtils.isEmpty(req.getFeedbackId())) throw new AppException("反馈信息ID不能为空！");

            //如果时间已经结束 则不能再提交
            FeedbackEntity feedbackEntity = feedbackService.get(req.getFeedbackId(), context);
            if(ObjectUtils.isEmpty(feedbackEntity)) throw new AppException("未找到当前问卷，请联系管理员！");
            if (DateUtil.compare(new Date(), feedbackEntity.getFeedbackTimeStart()) < 0)
                throw new AppException("当前反馈问卷信息还未开始！");
            if (DateUtil.compare(new Date(), feedbackEntity.getFeedbackTimeEnd()) > 0)
                throw new AppException("当前反馈问卷信息已经过了截止日期！");

            //判断是否已经回答过，已经回答了的 不重复提交
            int count = answerService.count(new FeedbackAnswerQuery().feedbackId(req.getFeedbackId()).staffId(context.getUser().getCustomerId()), context);
            if (count > 0) throw new AppException("该问卷反馈已经提交过，不能重复提交！");

            //添加问答
            List<FeedbackAnswerEntity> feedbackAnswerList = req.getFeedbackAnswerList();
            for (FeedbackAnswerEntity feedbackAnswerEntity : feedbackAnswerList) {

                feedbackAnswerEntity.setFeedbackId(req.getFeedbackId());
                feedbackAnswerEntity.setStaffId(context.getUser().getCustomerId());
                feedbackAnswerEntity.setCreateUserId(context.getUser().getId());
                feedbackAnswerEntity.setCreateTime(new Date());
                List<FeedbackAnswerOptionEntity> feedbackAnswerOptionList = feedbackAnswerEntity.getFeedbackAnswerOptionList();
                for (FeedbackAnswerOptionEntity feedbackAnswerOptionEntity : feedbackAnswerOptionList) {
                    feedbackAnswerOptionEntity.setCreateUserId(context.getUser().getId());
                    feedbackAnswerOptionEntity.setCreateTime(new Date());
                }
            }


            answerService.save(feedbackAnswerList, context);

            recordSysLog(request, busiDesc + " 【成功】");
        } catch (Exception e) {
            log.error(busiDesc, e);
            rest = Rest.fail(super.convertException(e));
        }
        return rest;
    }


    protected PageInfo buildPageInfo(FeedbackReq query) {
        PageInfo pageInfo = new PageInfo();
        if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getPage())) {
            pageInfo.setCurrPage(query.getPage());
        }

        if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getSize())) {
            pageInfo.setPrePageResult(query.getSize());
        }

        return pageInfo;
    }


    protected void parsePageInfo(Map<String, Object> model, PageInfo pageInfo) {
        model.put(TOTAL, pageInfo.getTotalResult());
        model.put(PER_PAGE, pageInfo.getPrePageResult());
        model.put(CURRENT_PAGE, pageInfo.getCurrPage());
        model.put(LAST_PAGE, pageInfo.getTotalPage());
        model.put(PAGEINFO_KEY, pageInfo);
    }

    public static void main(String[] args) {

    }

}
