package com.bs.jxc.controller;

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

import com.bs.jxc.domain.BmVesselVoyage;
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.jxc.domain.CmVessel;
import com.bs.jxc.service.ICmVesselService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 船舶基本资料Controller
 *
 * @author bs
 * @date 2023-07-09
 */
@Api(tags = "船舶基本资料")
@RestController
@RequestMapping("/jxc/vessel")
public class CmVesselController extends BaseController {
    @Resource
    private ICmVesselService cmVesselService;

    /**
     * 分页查询船舶基本资料列表
     */
    @ApiOperation("分页查询船舶基本资料列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmVessel cmVessel) {
        startPage();
        LambdaQueryWrapper<CmVessel> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVessel);
        List<CmVessel> list = cmVesselService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询船舶基本资料列表
     */
    @ApiOperation("查询船舶基本资料列表")
    @GetMapping("/list")
    public AjaxResult list(CmVessel cmVessel) {
        LambdaQueryWrapper<CmVessel> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVessel);
        List<CmVessel> list = cmVesselService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出船舶基本资料列表
     */
    @ApiOperation("导出船舶基本资料列表")
    @Log(title = "船舶基本资料导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmVessel cmVessel) {
        LambdaQueryWrapper<CmVessel> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmVessel);
        List<CmVessel> list = cmVesselService.list(queryWrapper);
        ExcelUtil<CmVessel> util = new ExcelUtil<CmVessel>(CmVessel. class);
        util.exportExcel(response, list, "船舶基本资料数据");
    }

    @Log(title = "导入船舶基本资料", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<CmVessel> util = new ExcelUtil<>(CmVessel.class);
            List<CmVessel> vesselList = util.importExcel(file.getInputStream());

            // 创建 LambdaQueryWrapper 对象
            LambdaQueryWrapper<CmVessel> queryWrapper = new LambdaQueryWrapper<>();

            // 根据具体需求进行导入操作
            for (CmVessel vessel : vesselList) {
                // 按照业务需求构建查询条件
                queryWrapper.eq(CmVessel::getId, vessel.getId()); // 示例：根据 ID 判断是否存在

                // 查询数据库中是否已存在相同记录
                Long count = cmVesselService.count(queryWrapper);

                if (count > 0) {
                    // 如果已存在记录，则进行更新操作
                    cmVesselService.update(vessel, queryWrapper);
                } else {
                    // 如果不存在记录，则进行插入操作
                    cmVesselService.save(vessel);
                }
            }

            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("导入船舶基本资料列表模板")
    @Log(title = "导入船舶基本资料模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, CmVessel cmVessel) {
        // 创建一个空的船舶基本资料列表
        List<CmVessel> emptyList = new ArrayList<>();

        // 导出空列表为 Excel 文件
        ExcelUtil<CmVessel> util = new ExcelUtil<>(CmVessel.class);
        util.exportExcel(response, emptyList, "船舶基本资料模板");
    }


    /**
     * 获取船舶基本资料详细信息
     */
    @ApiOperation("获取船舶基本资料详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cmVesselService.getById(id));
    }

    /**
     * 新增船舶基本资料
     */
    @ApiOperation("新增船舶基本资料")
    @Log(title = "船舶基本资料新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmVessel cmVessel) {

        CmVessel cmVessel1 = cmVesselService.getOne(new LambdaQueryWrapper<CmVessel>().eq(CmVessel::getVesselCode,cmVessel.getVesselCode()));
        if(cmVessel1!=null){
            return error("船舶编号已经存在，请重新输入");
        }

        return toAjax(cmVesselService.save(cmVessel));
    }

    /**
     * 修改船舶基本资料
     */
    @ApiOperation("修改船舶基本资料")
    @Log(title = "船舶基本资料修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmVessel cmVessel) {
        CmVessel cmVessel1= cmVesselService.getOne(new LambdaQueryWrapper<CmVessel>().eq(CmVessel::getVesselCode,cmVessel.getVesselCode()).ne(CmVessel::getId,cmVessel.getId()));
        if(cmVessel1!=null){
            return error("船舶编号已经存在，请重新输入");
        }
        return toAjax(cmVesselService.updateById(cmVessel));
    }

    /**
     * 删除船舶基本资料
     */
    @ApiOperation("删除船舶基本资料")
    @Log(title = "船舶基本资料删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(cmVesselService.removeBatchByIds(ids));
    }

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


        //船舶编号
        if(Validator.isNotEmpty(cmVessel.getVesselCode())){
            queryWrapper.like(CmVessel::getVesselCode,cmVessel.getVesselCode());
        }

        //船舶名称
        if(Validator.isNotEmpty(cmVessel.getVesselName())){
            queryWrapper.like(CmVessel::getVesselName,cmVessel.getVesselName());
        }

        //国籍
        if(Validator.isNotEmpty(cmVessel.getNationality())){
            queryWrapper.like(CmVessel::getNationality,cmVessel.getNationality());
        }

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

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

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

    }

}
