package com.bs.jxc.controller;

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

import com.bs.jxc.domain.CmCust;
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.CmPort;
import com.bs.jxc.service.ICmPortService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 港口信息Controller
 *
 * @author bs
 * @date 2023-07-10
 */
@Api(tags = "港口信息")
@RestController
@RequestMapping("/jxc/port")
public class CmPortController extends BaseController {
    @Resource
    private ICmPortService cmPortService;

    /**
     * 分页查询港口信息列表
     */
    @ApiOperation("分页查询港口信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmPort cmPort) {
        startPage();
        LambdaQueryWrapper<CmPort> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmPort);
        List<CmPort> list = cmPortService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询港口信息列表
     */
    @ApiOperation("查询港口信息列表")
    @GetMapping("/list")
    public AjaxResult list(CmPort cmPort) {
        LambdaQueryWrapper<CmPort> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmPort);
        List<CmPort> list = cmPortService.list(queryWrapper);
        return success(list);
    }

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

    @Log(title = "港口信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<CmPort> util = new ExcelUtil<>(CmPort.class);
            List<CmPort> portList = util.importExcel(file.getInputStream());

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

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

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

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

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

    @ApiOperation("导入港口信息列表模板")
    @Log(title = "导入港口信息模板", businessType = BusinessType.EXPORT)
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, CmPort cmPort) {
        // 创建一个空的港口信息列表
        List<CmPort> emptyList = new ArrayList<>();

        // 导出空列表为 Excel 文件
        ExcelUtil<CmPort> util = new ExcelUtil<>(CmPort.class);
        util.exportExcel(response, emptyList, "港口信息模板");
    }


    /**
     * 获取港口信息详细信息
     */
    @ApiOperation("获取港口信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cmPortService.getById(id));
    }

    /**
     * 新增港口信息
     */
    @ApiOperation("新增港口信息")
    @Log(title = "港口信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmPort cmPort) {

        CmPort cmPort1 = cmPortService.getOne(new LambdaQueryWrapper<CmPort>().eq(CmPort::getPortCode,cmPort.getPortCode()));
        if(cmPort1!=null){
            return error("港口代码已经存在，请重新输入");
        }

        return toAjax(cmPortService.save(cmPort));
    }

    /**
     * 修改港口信息
     */
    @ApiOperation("修改港口信息")
    @Log(title = "港口信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmPort cmPort) {
        CmPort cmPort1= cmPortService.getOne(new LambdaQueryWrapper<CmPort>().eq(CmPort::getPortCode,cmPort.getPortCode()).ne(CmPort::getId,cmPort.getId()));
        if(cmPort1!=null){
            return error("港口代码已经存在，请重新输入");
        }


        return toAjax(cmPortService.updateById(cmPort));
    }

    /**
     * 删除港口信息
     */
    @ApiOperation("删除港口信息")
    @Log(title = "港口信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(cmPortService.removeBatchByIds(ids));
    }

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




        //港口代码
        if(Validator.isNotEmpty(cmPort.getPortCode())){
            queryWrapper.like(CmPort::getPortCode,cmPort.getPortCode());
        }

        //港口名称
        if(Validator.isNotEmpty(cmPort.getPortName())){
            queryWrapper.like(CmPort::getPortName,cmPort.getPortName());
        }

        //港口英文名称
        if(Validator.isNotEmpty(cmPort.getPortEnName())){
            queryWrapper.like(CmPort::getPortEnName,cmPort.getPortEnName());
        }

        //所属国家
        if(Validator.isNotEmpty(cmPort.getConrty())){
            queryWrapper.like(CmPort::getConrty,cmPort.getConrty());
        }

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

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



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

        }

}
