package com.muyu.enterprise.controller;

import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.domain.req.BoundFenceGroupReq;
import com.muyu.enterprise.cache.AllVehicleCacheService;
import com.muyu.enterprise.cache.VehicleCacheService;
import com.muyu.enterprise.service.VehicleService;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.poi.ExcelUtil;
import com.muyu.common.core.web.controller.BaseController;
import com.muyu.common.core.web.page.TableDataInfo;
import com.muyu.domain.BoundMiddle;
import com.muyu.domain.Vehicle;
import com.muyu.domain.req.VehicleAddReq;
import com.muyu.domain.req.VehicleManageReq;
import com.muyu.domain.req.VehicleUpdReq;
import com.muyu.domain.resp.VehicleManageResp;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * @Author: LiDongJia
 * @Package: com.muyu.car.controller
 * @Project: 2112-car-cloud-server
 * @name: VehicleController
 * @Date: 2024/9/17  17:35
 * @Description: 车辆管理控制层
 */
@Log4j2
@RestController
@RequestMapping("/vehicleManage")
@Tag(name = "车辆管理控制层", description = "进行车辆管理操作")
public class VehicleController extends BaseController {

    @Autowired
    private VehicleService vehicleService;

    //添加车辆缓存
    @Autowired
    private VehicleCacheService vehicleCacheService;
    //车辆信息
    @Autowired
    private AllVehicleCacheService allVehicleCacheService;


    /**
     * 查询车辆管理列表
     *
     * @return
     */
    @RequestMapping(path = "/list", method = RequestMethod.POST)
    @Operation(summary = "车辆管理列表", description = "根据车牌号、VIN码、车辆状态筛选车辆")
    public Result<TableDataInfo<VehicleManageResp>> getVehicleList(@RequestBody VehicleManageReq vehicleManageReq) {
        startPage();
        List<VehicleManageResp> list = vehicleService.getVehicleList(vehicleManageReq);
//        将车辆信息存到Redis
//        for (VehicleManageResp resp : list) {
//            allVehicleCacheService.put(resp.getVehicleVin(), resp);
//        }
        List<Vehicle> vehicleList = vehicleService.list();
        vehicleList.forEach(vehicle -> {
            vehicleCacheService.put(vehicle.getVehicleVin(), vehicle);
        });
        return getDataTable(list);
    }

    /**
     * 车辆录入
     *
     * @param vehicleAddReq
     * @return
     */
    @PostMapping("/")
    @Operation(summary = "新增车辆", description = "录入车辆信息")
    public Result<String> save(@RequestBody VehicleAddReq vehicleAddReq) {
        boolean save = vehicleService.save(Vehicle.addBuild(vehicleAddReq));
        //获取用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取租户唯一标识
        String databaseName = loginUser.getSysUser().getDatabaseName();
        //存到redis
        vehicleCacheService.put(databaseName+vehicleAddReq.getVehicleVin(), Vehicle.addBuild(vehicleAddReq));
        return Result.success(save? "新增成功" : "新增失败");
    }

    /**
     * 通过车辆id获取车辆信息
     *
     * @param vehicleId
     * @return
     */
    @GetMapping("/{vehicleId}")
    @Operation(summary = "通过id查询车辆信息", description = "通过id查询车辆信息")
    public Result<Vehicle> findById(@PathVariable("vehicleId") Long vehicleId) {
        return Result.success(vehicleService.getById(vehicleId));
    }

    /**
     * 修改车辆信息
     *
     * @param vehicleId
     * @param vehicleUpdReq
     * @return
     */
    @PutMapping("/{vehicleId}")
    @Operation(summary = "修改车辆信息", description = "修改车辆信息")
    public Result<String> update(
            @PathVariable("vehicleId") Long vehicleId,
            @RequestBody @Validated VehicleUpdReq vehicleUpdReq) {
        vehicleService.updateById(Vehicle.updBuild(vehicleUpdReq, () -> vehicleId));
        return Result.success("修改成功");
    }

    /**
     * 通过车辆id删除车辆信息
     *
     * @param vehicleId
     * @return
     */
    @DeleteMapping("/{vehicleId}")
    @Operation(summary = "通过车辆id删除车辆信息", description = "通过车辆id删除车辆信息")
    public Result<String> delete(@PathVariable("vehicleId") Long vehicleId) {
        vehicleService.removeById(vehicleId);
        return Result.success("删除成功");
    }

    /**
     * 批量删除车辆
     *
     * @param vehicleIds
     * @return
     */
    @DeleteMapping("/batchDelete")
    @Operation(summary = "批量删除车辆")
    public Result<String> batchDelete(@RequestBody List<Long> vehicleIds) {
        vehicleService.removeBatchByIds(vehicleIds);
        return Result.success("批量删除成功");
    }

    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        List<Vehicle> list = vehicleService.list();
        ExcelUtil<Vehicle> util = new ExcelUtil<>(Vehicle.class);
        util.exportExcel(response, list, "车辆数据");
    }

    /**
     * 车辆绑定围栏组
     */
    @PostMapping("/addBoundFenceGroup")
    @Operation(description = "车辆绑定围栏组")
    public Result boundFenceGroup(
            @Validated @RequestBody BoundFenceGroupReq boundFenceGroupReq){
        vehicleService.boundFenceGroup(boundFenceGroupReq);
        return Result.success("绑定成功");
    }

    /**
     * 通过车辆vin码查询模板id
     * @param vehicleVin
     * @return
     */
    @GetMapping("/findByVehicleVin/{vehicleVin}")
    @Operation(description = "通过车辆vin码查询模板id")
    public Result<Long> findByVehicleVin(@PathVariable("vehicleVin") String vehicleVin) {
        Long templateId = vehicleService.findByVehicleVin(vehicleVin);
        return Result.success(templateId);
    }

}
