package com.ltgk.boat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ltgk.boat.domain.dto.DsBoatBindCrewDTO;
import com.ltgk.boat.domain.entity.DsBoatBindCrew;
import com.ltgk.boat.domain.entity.DsBoatDevice;
import com.ltgk.boat.service.IDsBoatBindCrewService;
import com.ltgk.boat.service.IDsBoatDeviceService;
import com.ltgk.common.annotation.Log;
import com.ltgk.common.annotation.RepeatSubmit;
import com.ltgk.common.constant.Constants;
import com.ltgk.common.core.controller.BaseController;
import com.ltgk.common.core.domain.AjaxResult;
import com.ltgk.common.core.page.TableDataInfo;
import com.ltgk.common.enums.BusinessType;
import com.ltgk.common.utils.SecurityUtils;
import com.ltgk.common.utils.StringUtils;
import com.ltgk.common.utils.bean.BeanUtils;
import com.ltgk.common.utils.poi.ExcelUtil;
import com.ltgk.common.validation.groups.Detail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 渔船绑定船员 前端控制器
 *
 * @author Qi ChengBin
 * @date 2024-12-18
 */
@Api(tags = "渔船绑定船员")
@RestController
@RequestMapping("/fishingPort/dsBoatBindCrew")
@Validated
public class DsBoatBindCrewController extends BaseController {

    @Resource
    private IDsBoatBindCrewService dsBoatBindCrewService;
    @Resource
    private IDsBoatDeviceService dsBoatDeviceService;

    /**
     * 分页查询渔船绑定船员列表
     * 现在采用番禺的逻辑，但是番禺那边没有这个页面，不知道是否正确
     *
     * @param dsBoatBindCrewDTO: 渔船绑定船员数据传输对象
     * @return com.ltgk.common.core.page.TableDataInfo
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询渔船绑定船员列表")
    public TableDataInfo page(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        List<DsBoatBindCrew> dsBoatBindCrewList = dsBoatBindCrewService.findDsBoatBindCrewPage(dsBoatBindCrewDTO);
        return getDataTable(dsBoatBindCrewList);
    }

    /**
     * 根据船名获取绑定船员列表
     *
     * @param dsBoatBindCrewDTO:
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024/12/18 14:13
     */
    @PostMapping("/findBoatBindCrewByBoatName")
    @ApiOperation(value = "根据船名获取绑定船员列表，无分页")
    public AjaxResult findBoatBindCrewByBoatName(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        return AjaxResult.success(dsBoatBindCrewService.findBoatBindCrewByBoatName(dsBoatBindCrewDTO));
    }

    /**
     * 不分页查询渔船绑定船员列表
     *
     * @param dsBoatBindCrewDTO:
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024/12/18 14:19
     */
    @PostMapping("/findBoatBindCrewList")
    @ApiOperation(value = "不分页列表")
    public AjaxResult findBoatBindCrewList(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        return AjaxResult.success(dsBoatBindCrewService.findBoatBindCrewList(dsBoatBindCrewDTO));
    }

    /**
     * 导出渔船绑定船员列表
     *
     * @param dsBoatBindCrewDTO: 渔船绑定船员数据传输对象
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @Log(title = "渔船绑定船员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出渔船绑定船员数据")
    public void export(HttpServletResponse response, @RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        LambdaQueryWrapper<DsBoatBindCrew> wrapper = getDsBoatBindCrewLambdaQueryWrapper(dsBoatBindCrewDTO);
        List<DsBoatBindCrew> dsBoatBindCrewList = dsBoatBindCrewService.list(wrapper);
        ExcelUtil<DsBoatBindCrew> util = new ExcelUtil<DsBoatBindCrew>(DsBoatBindCrew.class);
        util.exportExcel(response, dsBoatBindCrewList, "渔船绑定船员数据");
    }

    /**
     * 获取渔船绑定船员详细信息
     *
     * @param dsBoatBindCrewDTO: 渔船绑定船员数据传输对象
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @PostMapping(value = "/detail")
    @ApiOperation(value = "获取渔船绑定船员详细数据")
    public AjaxResult detail(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        return success(dsBoatBindCrewService.getById(dsBoatBindCrewDTO.getId()));
    }

    /**
     * 新增渔船绑定船员信息
     *
     * @param dsBoatBindCrew: 渔船绑定船员实体对象
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @RepeatSubmit(message = "请勿重复提交")
    @Log(title = "新增渔船绑定船员", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation(value = "新增渔船绑定船员数据")
    public AjaxResult add(@RequestBody DsBoatBindCrew dsBoatBindCrew) {
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        dsBoatBindCrew.setDelFlag(Constants.FLAG_FALSE)
                .setCreateBy(userName)
                .setCreateAt(new Date())
                .setUpdateBy(userName)
                .setUpdateAt(new Date());
        return toAjax(dsBoatBindCrewService.save(dsBoatBindCrew));
    }

    /**
     * 修改渔船绑定船员信息
     *
     * @param dsBoatBindCrew: 渔船绑定船员实体对象
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @Log(title = "修改渔船绑定船员", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation(value = "修改渔船绑定船员数据")
    public AjaxResult edit(@Validated(Detail.class) @RequestBody DsBoatBindCrew dsBoatBindCrew) {
        String userName = SecurityUtils.getLoginUser().getUser().getNickName();
        dsBoatBindCrew.setUpdateBy(userName)
                .setUpdateAt(new Date());
        return toAjax(dsBoatBindCrewService.updateById(dsBoatBindCrew));
    }

    /**
     * 删除渔船绑定船员信息
     *
     * @param dsBoatBindCrewDTO: 渔船绑定船员数据传输对象
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024-12-18
     */
    @Log(title = "删除渔船绑定船员", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ApiOperation(value = "批量删除渔船绑定船员数据")
    public AjaxResult delete(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        return toAjax(dsBoatBindCrewService.removeById(dsBoatBindCrewDTO.getId()));
    }

    /**
     * 根据登录用户查询跟登录用户相关的船员信息；登录用户所拥有渔船下绑定的船员信息
     *
     * @param dto:
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2025/3/27
     */
    @PostMapping("/findBoatBindCrewByLoginUser")
    @ApiOperation(value = "移动端-根据登录用户查询跟登录用户相关的船员信息；登录用户所拥有渔船下绑定的船员信息")
    public AjaxResult findBoatBindCrewByLoginUser(@RequestBody DsBoatBindCrewDTO dto) {
        return success(dsBoatBindCrewService.findBoatBindCrewByLoginUser(dto));
    }

    /**
     * 移动端渔船绑定船员
     *
     * @param dsBoatBindCrewDTO:
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024/12/18 14:50
     */
    @RepeatSubmit(message = "请勿重复提交")
    @PostMapping("/addByApp")
    @ApiOperation(value = "移动端渔船绑定船员")
    public AjaxResult addByApp(@RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        return toAjax(dsBoatBindCrewService.addByApp(dsBoatBindCrewDTO));
    }

    /**
     * 根据船员ID，解除渔船与船员绑定关系
     *
     * @param dsBoatBindCrewDTO:
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2024/12/18 17:35
     */
    @PostMapping("/unBindBoatToCrew")
    @ApiOperation(value = "根据船员ID，解除渔船与船员绑定关系")
    public AjaxResult unBindBoatToCrew(@Validated @RequestBody DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        return toAjax(dsBoatBindCrewService.unBindBoatToCrew(dsBoatBindCrewDTO));
    }


    /**
     * 根据查询参数组装查询wrapper
     *
     * @param dsBoatBindCrewDTO:
     * @return com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.ltgk.crew.domain.entity.DsBoatBindCrew>
     * @author Qi ChengBin
     * @date 2024/12/18 10:51
     */
    private LambdaQueryWrapper<DsBoatBindCrew> getDsBoatBindCrewLambdaQueryWrapper(DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        // 开始时间，结束时间  -- 根据绑定时间走
        String startTime = dsBoatBindCrewDTO.getStartTime();
        String endTime = dsBoatBindCrewDTO.getEndTime();
        DsBoatBindCrew dsBoatBindCrew = getDsBoatBindCrew(dsBoatBindCrewDTO);
        LambdaQueryWrapper<DsBoatBindCrew> wrapper = new LambdaQueryWrapper<>(dsBoatBindCrew);
        wrapper.ge(StringUtils.isNotBlank(startTime), DsBoatBindCrew::getBindTime, startTime)
                .le(StringUtils.isNotBlank(endTime), DsBoatBindCrew::getBindTime, endTime)
                .orderByDesc(DsBoatBindCrew::getBindTime);
        return wrapper;
    }

    /**
     * 根据数据传输对象转换成数据对象
     *
     * @param dsBoatBindCrewDTO:
     * @return com.ltgk.crew.domain.entity.DsBoatBindCrew
     * @author Qi ChengBin
     * @date 2024/12/18 10:52
     */
    private DsBoatBindCrew getDsBoatBindCrew(DsBoatBindCrewDTO dsBoatBindCrewDTO) {
        dsBoatBindCrewDTO.queryCheck();
        DsBoatBindCrew dsBoatBindCrew = new DsBoatBindCrew();
        BeanUtils.copyProperties(dsBoatBindCrewDTO, dsBoatBindCrew);
        return dsBoatBindCrew;
    }

    /**
     * 根据船员主键查询 渔船的terminalCode
     *
     * @param dto：
     * @return com.ltgk.common.core.domain.AjaxResult
     * @author Qi ChengBin
     * @date 2025/7/2
     */
    @PostMapping("/getBoatTerminalCodeByCrewId")
    @ApiOperation(value = "根据船员id 查询 所绑定的渔船的 terminalCode 的值")
    public AjaxResult getBoatTerminalCodeByCrewId(@RequestBody DsBoatBindCrewDTO dto) {
        DsBoatBindCrew dsBoatBindCrew = dsBoatBindCrewService.lambdaQuery()
                .eq(DsBoatBindCrew::getCrewId, dto.getCrewId())
                .eq(DsBoatBindCrew::getDelFlag, 0)
                .orderByDesc(DsBoatBindCrew::getBindTime)
                .last("limit 1")
                .one();
        if (Objects.isNull(dsBoatBindCrew)) {
            return error("该船员暂未绑定渔船!");
        }

        String boatName = dsBoatBindCrew.getBoatName1();
        if (StringUtils.isBlank(boatName)) {
            boatName = dsBoatBindCrew.getBoatName2();
        }
        if (StringUtils.isBlank(boatName)) {
            return error("该船员绑定渔船为空，无法进行定位");
        }

        DsBoatDevice dsBoatDevice = dsBoatDeviceService.lambdaQuery()
                .eq(DsBoatDevice::getBoatName, boatName)
                .eq(DsBoatDevice::getDelFlag, 0)
                .eq(DsBoatDevice::getDeviceType, "AIS")
                .orderByDesc(DsBoatDevice::getUpdateAt)
                .last("limit 1")
                .one();

        if (Objects.isNull(dsBoatDevice)) {
            return error("该船员绑定渔船的终端设备不存在");
        }
        return success(dsBoatDevice.getMmsi());
    }

}
