/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.gpsboot.controller.car;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.gpsboot.common.system.MessageTopicEnum;
import com.tofly.gpsboot.common.system.MessageTypeEnum;
import com.tofly.gpsboot.mapper.car.TfCarApplyMapper;
import com.tofly.gpsboot.service.car.CarBaseinfoService;
import com.tofly.gpsboot.service.car.TfCarApplyService;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.mq.IMessageRecipientService;
import com.tofly.pojo.car.CarBaseinfo;
import com.tofly.pojo.car.TfCarApply;
import com.tofly.pojo.message.Messagepush;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用车申请
 *
 * @author JF
 * @date Mon Apr 01 00:00:00 CST 2024
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tfcarapply")
@Api(tags="用车申请接口")
public class TfCarApplyController {

    private final TfCarApplyService tfCarApplyService;
    private final CarBaseinfoService carBaseinfoService;
    private final IMessageRecipientService messageRecipientService;
    private final TfCarApplyMapper carApplyMapper;
    private final IFileInfoService fileInfoService;

    /**
    * 分页查询
    * @param page 分页对象
    * @param tfCarApply 用车申请
    * @return
    */
    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getTfCarApplyPage(Page page,
                                           @ModelAttribute TfCarApply tfCarApply,
                                           @RequestParam(value = "auditStatusStr", required = false) String auditStatusStr) {
        List<String> auditStatusList = null;
        if (StringUtils.isNotBlank(auditStatusStr)) {
            auditStatusList = Arrays.stream(auditStatusStr.split(",")).collect(Collectors.toList());
        }
        return ResultRespone.success(tfCarApplyService.page(page, Wrappers.query(tfCarApply).lambda()
              .in(CollUtil.isNotEmpty(auditStatusList), TfCarApply::getAuditStatus, auditStatusList)));
    }


//    /**
//     * 通过id查询用车申请
//     * @param id id
//     * @return ResultRespone
//     */
//    @GetMapping("/{id}" )
//    @ApiOperation(value = "通过ID查询")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "BigDecimal")
//    })
//    public ResultRespone getById(@PathVariable("id" ) Long id) {
//      return ResultRespone.success(tfCarApplyService.getById(id));
//    }

    /**
     * 新增用车申请
     * @param tfCarApply 用车申请
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增用车申请" )
    @ApiOperation(value = "新增用车申请")
    @PostMapping("/saveOrUpdate")
    public ResultRespone saveOrUpdate(TfCarApply tfCarApply, @RequestPart(required = false) @ApiParam("附件列表") List<MultipartFile> fileList) {
        String carApplyPath = "/xrty/carApply/";
        if (tfCarApply.getId() == null) {
            if (CollUtil.isNotEmpty(fileList)) {
                StringBuilder annex = fileInfoService.saveFileList(fileList, carApplyPath, "TF_CAR_APPLY");
                tfCarApply.setAnnex(annex.toString());
            }
            if (tfCarApply.getCarNumber() == null) {
                sendMessage(tfCarApply, null);
                return ResultRespone.success(tfCarApplyService.save(tfCarApply));
            }
            TfCarApply carApply = tfCarApplyService.getOne(new QueryWrapper<TfCarApply>().lambda()
                    .eq(TfCarApply::getCarNumber, tfCarApply.getCarNumber())
                    .isNull(TfCarApply::getEndTime));
            if (carApply != null) {
                throw new ToflyDeniedException("当前车辆未还车，不能再次申请");
            }
            CarBaseinfo carBaseinfo = new CarBaseinfo();
            carBaseinfo.setStatus(tfCarApply.getStatus());
            carBaseinfoService.update(carBaseinfo, new QueryWrapper<CarBaseinfo>().lambda().eq(CarBaseinfo::getCarNumber, tfCarApply.getCarNumber()));

            sendMessage(tfCarApply, tfCarApply.getStatus());

            return ResultRespone.success(tfCarApplyService.save(tfCarApply));
        } else {
            CarBaseinfo carBaseinfo = new CarBaseinfo();
            carBaseinfo.setStatus(tfCarApply.getStatus());
            if (StringUtils.isNotBlank(tfCarApply.getAuditStatus()) && tfCarApply.getAuditStatus().equals("2")) {
                carBaseinfoService.update(carBaseinfo, new QueryWrapper<CarBaseinfo>().lambda().eq(CarBaseinfo::getCarNumber, tfCarApply.getCarNumber()));
            }

            if (CollUtil.isNotEmpty(fileList)) {
                StringBuilder annex = fileInfoService.saveFileList(fileList, carApplyPath, "TF_CAR_APPLY");
                if (StringUtils.isBlank(tfCarApply.getAnnex())) {
                    tfCarApply.setAnnex(annex.toString());
                } else {
                    tfCarApply.setAnnex(tfCarApply.getAnnex() + "," + annex.toString());
                }
            }
            sendMessage(tfCarApply, tfCarApply.getStatus());

            return ResultRespone.success(tfCarApplyService.updateById(tfCarApply));
        }
    }

    private void sendMessage(TfCarApply tfCarApply, String carStatus) {
        List<Map<String, Object>> realNameAll = carApplyMapper.getRealNameAll();

        Messagepush messagepush = new Messagepush();
        // 消息主题/消息类型/消息表名/消息表中id/路由地址跳转
        messagepush.setTopic(MessageTopicEnum.CAR_APPLY.getTopic());
        messagepush.setType(MessageTypeEnum.MESSAGE_TYPE_CAR_APPLY.getCode());
        messagepush.setTableName(MessageTopicEnum.CAR_APPLY.getTableName());
        // 跳转到查看页面
//        messagepush.setRouteIp(auditWebSelHiddenTroubleRouteIp);
        // 消息与接收人信息处理
        if (tfCarApply.getAuditStatus() != null
                && tfCarApply.getAuditStatus().equals("1")
                && tfCarApply.getAuditUser() != null
                && tfCarApply.getApplyUser() != null) {
            String userName = String.valueOf(realNameAll.stream()
                    .filter(e -> String.valueOf(e.get("id")).equals(String.valueOf(tfCarApply.getApplyUser())))
                    .collect(Collectors.toList())
                    .get(0)
                    .get("realName"));
            messagepush.setMessage(userName + "正在进行用车申请，请审核。");
            messageRecipientService.setMessageRecipient(messagepush, tfCarApply.getAuditUser());
        } else if (tfCarApply.getAuditStatus() != null
                && tfCarApply.getAuditStatus().equals("2")
                && tfCarApply.getApplyUser() != null
                && tfCarApply.getCarNumber() != null
                && carStatus.equals("1")) {
            messagepush.setMessage("用车申请已通过审核，可用车辆车牌号：" + tfCarApply.getCarNumber());
            messageRecipientService.setMessageRecipient(messagepush, tfCarApply.getApplyUser());
        } else if (tfCarApply.getAuditStatus() != null
                && tfCarApply.getAuditStatus().equals("2")
                && tfCarApply.getApplyUser() != null
                && tfCarApply.getCarNumber() != null
                && carStatus.equals("2")) {
            messagepush.setMessage("还车已通过审核，车辆已还车，车牌号：" + tfCarApply.getCarNumber());
            messageRecipientService.setMessageRecipient(messagepush, tfCarApply.getApplyUser());
        } else if (tfCarApply.getAuditStatus() != null
                && tfCarApply.getAuditStatus().equals("3")
                && tfCarApply.getApplyUser() != null) {
            messagepush.setMessage("用车申请被驳回");
            messageRecipientService.setMessageRecipient(messagepush, tfCarApply.getApplyUser());
        }
    }

//    /**
//     * 修改用车申请
//     * @param tfCarApply 用车申请
//     * @return ResultRespone
//     */
//    @ToFlyAppLog(title="修改用车申请" )
//    @ApiOperation(value = "修改用车申请")
//    @PutMapping
//    public ResultRespone updateById(@RequestBody TfCarApply tfCarApply) {
//      return ResultRespone.success(tfCarApplyService.updateById(tfCarApply));
//    }

//    /**
//     * 通过id删除用车申请
//     * @param id id
//     * @return ResultRespone
//     */
//    @ToFlyAppLog(title="通过id删除用车申请" )
//    @ApiOperation(value = "通过ID删除用车申请")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "BigDecimal")
//    })
//    @DeleteMapping("/{id}" )
//    public ResultRespone removeById(@PathVariable Long id) {
//      return ResultRespone.success(tfCarApplyService.removeById(id));
//    }

    /**
     * 通过id批量删除用车申请
     * @param ids id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id批量删除用车申请" )
    @ApiOperation(value = "通过ID批量删除用车申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds" )
    public ResultRespone removeById(String ids) {
        return ResultRespone.success(tfCarApplyService.removeByIds(Arrays.asList(ids.split(","))));
    }
}
