package com.repair.controller;


import com.alibaba.excel.EasyExcel;
import com.repair.api.RepairEvaluateControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.enumModel.eRecordStatu;
import com.repair.model.pojo.RepairEvaluate;
import com.repair.model.pojo.RepairRecord;
import com.repair.model.pojo.RepairSystemMessages;
import com.repair.model.pojo.RepairTrackRecord;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.EvaluateVo;
import com.repair.services.RepairEvaluateService;
import com.repair.services.RepairRecordService;
import com.repair.services.RepairSystemMessagesService;
import com.repair.services.RepairTrackRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-10
 */
@RestController
public class RepairEvaluateController implements RepairEvaluateControllerAPI {

    @Autowired
    private RepairRecordService repairRecordService;
    @Autowired
    private RepairEvaluateService repairEvaluateService;
    @Autowired
    private RepairTrackRecordService repairTrackRecordService;
    @Autowired
    private RepairSystemMessagesService repairSystemMessagesService;

    /**
     * 新增评价数据
     * @param repairEvaluate 评价数据
     * @param bindingResult 是否为空判断
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult InsertRepairEvaluate(@RequestBody RepairEvaluate repairEvaluate, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        if(repairEvaluate.getStar() > 5){
            return CommonResult.fail("评价星级最多五颗星");
        }

        if(repairEvaluate.getStar() < 1){
            return CommonResult.fail("评价星级最低一颗星");
        }

        RepairRecord rr = repairRecordService.getRepairById(repairEvaluate.getRecordId());
        if (rr == null) {
            return CommonResult.fail("维修单已失效，评价失败！");
        }

        if (rr.getMaintenanceState() != eRecordStatu.Finished.getValue()) {
            return CommonResult.fail("已完成订单才能进行评价操作！");
        }

        RepairEvaluate re = repairEvaluateService.getRepairByRecordId(rr.getId());
        if(re != null){
            return CommonResult.fail("该订单已评价，请勿重复操作！");
        }

        try {
            int result = repairEvaluateService.insertRepairEvaluate(repairEvaluate);// 帮我们自动生成id
            if (result <= 0) {
                throw new Exception("评价失败！");
            }
            String[] mUserIds = rr.getMaintenancerId().split(",");
            List<RepairSystemMessages> rsms = new ArrayList<>();
            for (int i = 0; i < mUserIds.length; i++) {
                RepairSystemMessages rsm = new RepairSystemMessages();
                rsm.setIsRead(0);
                rsm.setRecordId(repairEvaluate.getRecordId());
                rsm.setRecipientId(Integer.valueOf(mUserIds[i]));
                rsm.setContent("用户已点评！");
                rsms.add(rsm);
            }
            //用户的
            //感谢您的点评，非常感谢您对我们的认可及支持。
            RepairSystemMessages rsmU = new RepairSystemMessages();
            rsmU.setIsRead(0);
            rsmU.setRecordId(repairEvaluate.getRecordId());
            rsmU.setRecipientId(rr.getUserId());
            rsmU.setContent("感谢您的点评，非常感谢您对我们的认可及支持。");
            rsms.add(rsmU);
            if (rsms.size() > 0) {
                boolean insertRsm = repairSystemMessagesService.inserBatchSystemMessage(rsms);
                if (!insertRsm) {
                    throw new Exception("评价失败！");
                }
            }

            //添加跟踪记录
            RepairTrackRecord rtr = new RepairTrackRecord();
            rtr.setRecordId(repairEvaluate.getRecordId());
            rtr.setMaintenanceState(eRecordStatu.Finished.getValue());
            rtr.setContent("用户评价");
            rtr.setUserId(rr.getUserId());
            rtr.setUserZzstr("用户");
            int insertRtr =repairTrackRecordService.insertRepairTrackRecord(rtr);
            if(insertRtr <= 0){
                throw new Exception("评价失败！");
            }

        } catch (Exception e) {
            throw new Exception("评价失败！");
        }

        return CommonResult.ok("评价成功");
    }

    /**
     * 评价分页数据查询
     * @param currentPage 当前页数
     * @param pageCount 一页数据条数
     * @param keyWord 关键字
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public CommonResult queryPageRepairEvaluates(@RequestParam int currentPage, @RequestParam int pageCount, String keyWord, String startTime, String endTime) {
        PageUtils<RepairEvaluate> result = repairEvaluateService.queryPageList(currentPage, pageCount, keyWord, startTime, endTime);

        return CommonResult.ok(result);
    }

    /**
     * 根据数据ID删除评价数据
     * @param id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairEvaluateById(int id) {
        RepairEvaluate data = repairEvaluateService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairEvaluateService.deleteRepairEvaluateById(id);

        return result > 0 ? CommonResult.ok() : CommonResult.fail();
    }

    /**
     * 评价报表导出
     * @param response 文件响应流
     * @param keyWord 关键字
     * @param startTime 起始时间
     * @param endTime 结束时间
     */
    @Override
    public void toRepairEvaluateExcel(HttpServletResponse response, String keyWord, String startTime, String endTime) {
        List<EvaluateVo> result = repairEvaluateService.queryEvaluateList(keyWord, startTime, endTime);

        String sheelName = "评价信息";
        try {
            String fileName = URLEncoder.encode(sheelName + new Date().getTime(), "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), EvaluateVo.class).sheet(sheelName).doWrite(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

