package com.repair.controller;


import com.repair.api.RepairLeaveMessageControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.enumModel.eRecordStatu;
import com.repair.model.pojo.RepairLeaveMessage;
import com.repair.model.pojo.RepairRecord;
import com.repair.model.pojo.RepairSystemMessages;
import com.repair.model.pojo.RepairTrackRecord;
import com.repair.model.request.repairLeaveMessageRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.RepairLogisticsVo;
import com.repair.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-20
 */
@RestController
public class RepairLeaveMessageController implements RepairLeaveMessageControllerAPI {

    @Autowired
    private RepairUserService repairUserService;
    @Autowired
    private RepairRecordService repairRecordService;
    @Autowired
    private RepairTrackRecordService repairTrackRecordService;
    @Autowired
    private RepairLeaveMessageService repairLeaveMessageService;
    @Autowired
    private RepairSystemMessagesService repairSystemMessagesService;

    /**
     * 新增留言信息
     * @param rc 留言信息
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult insertRepairLeaveMessage(RepairLeaveMessage rc, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = repairLeaveMessageService.insertRepairLeaveMessage(rc);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 根据数据ID更新留言信息
     * @param rc 留言信息
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult updateRepairLeaveMessageById(RepairLeaveMessage rc, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = repairLeaveMessageService.updateRepairLeaveMessage(rc);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }


    @Override
    public CommonResult queryPageRepairLeaveMessages(int currentPage, int pageCount, String name) {
        PageUtils<RepairLeaveMessage> result = repairLeaveMessageService.queryPageRepairLeaveMessages(currentPage, pageCount, name);

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult deleteRepairLeaveMessageById(int id) {
        RepairLeaveMessage data = repairLeaveMessageService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairLeaveMessageService.deleteRepairLeaveMessageById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult transferToLogistics(repairLeaveMessageRequest rlmr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        //只有待确认能转后勤
        RepairRecord rr = repairRecordService.getRepairById(rlmr.getRecordId());
        if (rr == null) {
            return CommonResult.fail("报修单不存在，转后勤失败");
        }

        if (rr.getMaintenanceState() != eRecordStatu.ToConfirmed.getValue()) {
            return CommonResult.fail("待确认的报修单才能进行转后勤操作");
        }

        /**
         * 获取报修工单对应校区的所有后勤人员
         */
        List<RepairLogisticsVo> users = repairUserService.queryLogisticsList(rlmr.getRecordId());
        if (users.size() <= 0) {
            return CommonResult.fail("该报修区域缺少后勤人员");
        }

        //有可能有多个后勤
        List<RepairLeaveMessage> datas = new ArrayList<>();
        List<RepairSystemMessages> messages = new ArrayList<>();
        for (RepairLogisticsVo u : users) {
            RepairLeaveMessage data = new RepairLeaveMessage();
            data.setSenderId(rlmr.getUserId());
            data.setRecipientId(u.getId());
            data.setContent(rlmr.getContent());
            data.setRecordId(rlmr.getRecordId());
            datas.add(data);

            RepairSystemMessages rsm = new RepairSystemMessages();
            rsm.setIsRead(0);
            rsm.setRecordId(rlmr.getUserId());
            rsm.setRecipientId(u.getId());
            rsm.setContent("用户已提交留言，请尽快处理！");
            messages.add(rsm);
        }

        try {
            boolean result = repairLeaveMessageService.inserBatchLeaveMessage(datas);

            if (!result) {
                throw new Exception("转后勤失败！");
            }
            //将工单状态更改为待处理
            rr.setId(rlmr.getRecordId());
            rr.setMaintenanceState(eRecordStatu.ToLogistics.getValue());

            int updateR = repairRecordService.updateRepairRecord(rr);
            if (updateR <= 0) {
                throw new Exception("转后勤失败！");
            }

            boolean insertRsm = repairSystemMessagesService.inserBatchSystemMessage(messages);
            if (!insertRsm) {
                throw new Exception("报修单转后勤失败！");
            }

            //添加跟踪记录
            RepairTrackRecord rtr = new RepairTrackRecord();
            rtr.setRecordId(rlmr.getRecordId());
            rtr.setMaintenanceState(eRecordStatu.ToLogistics.getValue());
            rtr.setContent("用户转后勤：" + rlmr.getContent());
            rtr.setUserId(rlmr.getUserId());
            rtr.setUserZzstr("用户");
            int insertRtr = repairTrackRecordService.insertRepairTrackRecord(rtr);
            if (insertRtr <= 0) {
                throw new Exception("转后勤失败！");
            }
        } catch (Exception e) {
            throw new Exception("转后勤失败！");
        }

        return CommonResult.ok("转后勤成功");
    }
}

