package com.bs.cm.controller;

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

import com.bs.cm.domain.CmVehicle;
import com.bs.cm.domain.CmVehicleRfidDate;
import com.bs.cm.service.ICmVehicleRfidDateService;
import com.bs.cm.service.ICmVehicleService;
import com.bs.common.constant.HttpStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.cm.domain.CmVehicleRfid;
import com.bs.cm.service.ICmVehicleRfidService;
import javax.annotation.Resource;

/**
 * 车辆RFID信息Controller
 *
 * @author bs
 * @date 2025-01-12
 */
@Api(tags = "车辆RFID信息")
@RestController
@RequestMapping("/cm/vehicle/rfid")
public class CmVehicleRfidController extends BaseController {
    @Resource
    private ICmVehicleRfidService cmVehicleRfidService;
    @Resource
    private ICmVehicleService cmVehicleService;
    @Resource
    private ICmVehicleRfidDateService cmVehicleRfidDateService;

    /**
     * 分页查询车辆RFID信息列表
     */
    @ApiOperation("分页查询车辆RFID信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmVehicleRfid cmVehicleRfid) {
        startPage();
        LambdaQueryWrapper<CmVehicleRfid> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVehicleRfid);
        List<CmVehicleRfid> list = cmVehicleRfidService.list(queryWrapper);
        list = cmVehicleRfidService.getVehicleInfo(list);
        return getDataTable(list);
    }

    /**
     * 查询车辆RFID信息列表
     */
    @ApiOperation("查询车辆RFID信息列表")
    @GetMapping("/list")
    public AjaxResult list(CmVehicleRfid cmVehicleRfid) {
        LambdaQueryWrapper<CmVehicleRfid> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVehicleRfid);
        List<CmVehicleRfid> list = cmVehicleRfidService.list(queryWrapper);
        list = cmVehicleRfidService.getVehicleInfo(list);
        return success(list);
    }

    /**
     * 检查车辆RFID状态
     */
    @ApiOperation("检查车辆RFID状态")
    @GetMapping("/check")
    public AjaxResult check(CmVehicleRfid cmVehicleRfid) {
        if(Validator.isNotEmpty(cmVehicleRfid.getRfidNo()) && Validator.isNotEmpty(cmVehicleRfid.getVehicleId())){
            LambdaQueryWrapper<CmVehicleRfid> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(CmVehicleRfid::getVehicleId, cmVehicleRfid.getVehicleId());
            queryWrapper.eq(CmVehicleRfid::getRfidNo, cmVehicleRfid.getRfidNo());
            queryWrapper.eq(CmVehicleRfid::getIsValid, "Y");
            List<CmVehicleRfid> list = cmVehicleRfidService.list(queryWrapper);
            if (null != list && list.size() > 0) {
                return error("此RFID已经在该车工作，请勿重复绑定");
            } else {
                queryWrapper = new LambdaQueryWrapper();
                queryWrapper.ne(CmVehicleRfid::getVehicleId, cmVehicleRfid.getVehicleId());
                queryWrapper.eq(CmVehicleRfid::getRfidNo, cmVehicleRfid.getRfidNo());
                queryWrapper.eq(CmVehicleRfid::getIsValid, "Y");
                list = cmVehicleRfidService.list(queryWrapper);
                if (null != list && list.size() > 0) {
                    CmVehicle vehicle = cmVehicleService.getById(list.get(0).getVehicleId());
                    if (null != vehicle) {
                        return new AjaxResult(HttpStatus.SUCCESS, "此RFID已经在其他车辆" + vehicle.getVehicleNo() +"绑定，是否换绑到本车？", vehicle, "ok");
                    } else {
                        return success(new CmVehicle());
                    }
                } else {
                    return success(new CmVehicle());
                }
            }
        } else {
            return error("请输入RFID编号和车辆信息");
        }
    }

    /**
     * 导出车辆RFID信息列表
     */
    @ApiOperation("导出车辆RFID信息列表")
    @Log(title = "车辆RFID信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmVehicleRfid cmVehicleRfid) {
        LambdaQueryWrapper<CmVehicleRfid> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVehicleRfid);
        List<CmVehicleRfid> list = cmVehicleRfidService.list(queryWrapper);
        ExcelUtil<CmVehicleRfid> util = new ExcelUtil<CmVehicleRfid>(CmVehicleRfid. class);
        util.exportExcel(response, list, "车辆RFID信息数据");
    }

    /**
     * 获取车辆RFID信息详细信息
     */
    @ApiOperation("获取车辆RFID信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CmVehicleRfid rfid = cmVehicleRfidService.getById(id);
        if (null != rfid) {
            CmVehicle vehicle = cmVehicleService.getById(rfid.getVehicleId());
            rfid.setVehicle(vehicle);
        }
        return success(rfid);
    }

    /**
     * 新增车辆RFID信息
     */
    @ApiOperation("新增车辆RFID信息")
    @Log(title = "车辆RFID信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmVehicleRfid cmVehicleRfid) {
        if(Validator.isNotEmpty(cmVehicleRfid.getRfidNo()) && Validator.isNotEmpty(cmVehicleRfid.getVehicleId())) {
            LambdaQueryWrapper<CmVehicleRfid> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(CmVehicleRfid::getVehicleId, cmVehicleRfid.getVehicleId());
            queryWrapper.eq(CmVehicleRfid::getRfidNo, cmVehicleRfid.getRfidNo());
            queryWrapper.eq(CmVehicleRfid::getIsValid, "Y");
            List<CmVehicleRfid> list = cmVehicleRfidService.list(queryWrapper);
            if (null != list && list.size() > 0) {
                return error("此RFID已经在该车工作，请勿重复绑定");
            } else {
                queryWrapper = new LambdaQueryWrapper();
                queryWrapper.ne(CmVehicleRfid::getVehicleId, cmVehicleRfid.getVehicleId());
                queryWrapper.eq(CmVehicleRfid::getRfidNo, cmVehicleRfid.getRfidNo());
                queryWrapper.eq(CmVehicleRfid::getIsValid, "Y");
                list = cmVehicleRfidService.list(queryWrapper);
                List<Long> ids = new ArrayList<>();
                // 如果在其他车辆绑定
                if (null != list && list.size() > 0) {
                    // 让其他车辆失效
                    for (CmVehicleRfid rfid : list) {
                        rfid.setIsValid("N");
                        ids.add(rfid.getId());
                    }
                    cmVehicleRfidService.updateBatchById(list);
                    List<CmVehicleRfidDate> lsDate = cmVehicleRfidDateService.list(new LambdaQueryWrapper<CmVehicleRfidDate>().in(CmVehicleRfidDate::getRfidId, ids));
                    if (null != lsDate && lsDate.size() > 0) {
                        // 让其他车辆的rfid日期结束
                        for (CmVehicleRfidDate rfidDate : lsDate) {
                            rfidDate.setExpiringDate(new Date());
                        }
                        cmVehicleRfidDateService.updateBatchById(lsDate);
                    }
                }
                // 处理新绑定
                cmVehicleRfidService.save(cmVehicleRfid);
                CmVehicleRfidDate rfidDate = new CmVehicleRfidDate();
                rfidDate.setRfidId(cmVehicleRfid.getId());
                rfidDate.setRfidNo(cmVehicleRfid.getRfidNo());
                rfidDate.setVehicleId(cmVehicleRfid.getVehicleId());
                rfidDate.setEffectiveDate(new Date());
                rfidDate.setSetupDate(new Date());
                cmVehicleRfidDateService.save(rfidDate);
                return success("绑定成功");
            }
        } else {
            return error("请输入RFID编号和车辆信息");
        }
        //return toAjax(cmVehicleRfidService.save(cmVehicleRfid));
    }

    /**
     * 修改车辆RFID信息
     */
    @ApiOperation("修改车辆RFID信息")
    @Log(title = "车辆RFID信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmVehicleRfid cmVehicleRfid) {
        return toAjax(cmVehicleRfidService.updateById(cmVehicleRfid));
    }


    /**
     * 删除车辆RFID信息
     */
    @ApiOperation("删除车辆RFID信息")
    @Log(title = "车辆RFID信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        if (null != ids && ids.size() > 0) {
            List<CmVehicleRfid> list = cmVehicleRfidService.listByIds(ids);
            if (null != list && list.size() > 0) {
                for (CmVehicleRfid rfid : list) {
                    rfid.setIsValid("N");
                }
                cmVehicleRfidService.updateBatchById(list);
                List<CmVehicleRfidDate> lsDate = cmVehicleRfidDateService.list(new LambdaQueryWrapper<CmVehicleRfidDate>().in(CmVehicleRfidDate::getRfidId, ids));
                if (null != lsDate && lsDate.size() > 0) {
                    // 让车辆的rfid日期结束
                    for (CmVehicleRfidDate rfidDate : lsDate) {
                        rfidDate.setExpiringDate(new Date());
                    }
                    cmVehicleRfidDateService.updateBatchById(lsDate);
                }
            }
            return success("解绑成功");
        } else {
            return error("请选择需要解绑的车辆RFID");
        }
        //return toAjax(cmVehicleRfidService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CmVehicleRfid> queryWrapper,CmVehicleRfid cmVehicleRfid){


        //车辆标签ID
        if(Validator.isNotEmpty(cmVehicleRfid.getId())){
            queryWrapper.eq(CmVehicleRfid::getId,cmVehicleRfid.getId());
        }

        //车辆ID
        if(Validator.isNotEmpty(cmVehicleRfid.getVehicleId())){
            queryWrapper.eq(CmVehicleRfid::getVehicleId,cmVehicleRfid.getVehicleId());
        }

        //标签编号
        if(Validator.isNotEmpty(cmVehicleRfid.getRfidNo())){
            queryWrapper.eq(CmVehicleRfid::getRfidNo,cmVehicleRfid.getRfidNo());
        }

        //厂商
        if(Validator.isNotEmpty(cmVehicleRfid.getManufacturer())){
            queryWrapper.eq(CmVehicleRfid::getManufacturer,cmVehicleRfid.getManufacturer());
        }

        //是否有效
        if(Validator.isNotEmpty(cmVehicleRfid.getIsValid())){
            queryWrapper.eq(CmVehicleRfid::getIsValid,cmVehicleRfid.getIsValid());
        }

        //备注
        if(Validator.isNotEmpty(cmVehicleRfid.getRemark())){
            queryWrapper.eq(CmVehicleRfid::getRemark,cmVehicleRfid.getRemark());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(cmVehicleRfid.getDelFlag())){
            queryWrapper.eq(CmVehicleRfid::getDelFlag,cmVehicleRfid.getDelFlag());
        }

        //创建部门
        if(Validator.isNotEmpty(cmVehicleRfid.getCreateDept())){
            queryWrapper.eq(CmVehicleRfid::getCreateDept,cmVehicleRfid.getCreateDept());
        }

        //创建人
        if(Validator.isNotEmpty(cmVehicleRfid.getCreateBy())){
            queryWrapper.eq(CmVehicleRfid::getCreateBy,cmVehicleRfid.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(cmVehicleRfid.getCreateTime())){
            queryWrapper.eq(CmVehicleRfid::getCreateTime,cmVehicleRfid.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(cmVehicleRfid.getUpdateBy())){
            queryWrapper.eq(CmVehicleRfid::getUpdateBy,cmVehicleRfid.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(cmVehicleRfid.getUpdateTime())){
            queryWrapper.eq(CmVehicleRfid::getUpdateTime,cmVehicleRfid.getUpdateTime());
        }

        //租户ID
        if(Validator.isNotEmpty(cmVehicleRfid.getTenantId())){
            queryWrapper.eq(CmVehicleRfid::getTenantId,cmVehicleRfid.getTenantId());
        }

        }

}
