package com.bs.jxc.controller;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.bs.jxc.domain.BmVesselCargo;
import com.bs.jxc.domain.BmVesselVoyage;
import com.bs.jxc.domain.CkBill;
import com.bs.jxc.service.IBmVesselCargoService;
import com.bs.jxc.service.IBmVesselVoyageService;
import com.bs.jxc.service.ICkBillService;
import com.bs.jxc.service.ICkBillStockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 船舶航次Controller
 *
 * @author bs
 * @date 2023-07-10
 */
@Api(tags = "船舶航次")
@RestController
@RequestMapping("/jxc/bmvoyage")
public class BmVesselVoyageController extends BaseController {
    @Resource
    private IBmVesselVoyageService bmVesselVoyageService;
    @Resource
    private IBmVesselCargoService bmVesselCargoService;
    @Resource
    private ICkBillStockService ckBillStockService;
    @Resource
    private ICkBillService ckBillService;

    /**
     * 分页查询船舶航次列表
     */
    @ApiOperation("分页查询船舶航次列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(BmVesselVoyage bmVesselVoyage) {
        startPage();
        LambdaQueryWrapper<BmVesselVoyage> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,bmVesselVoyage);
        List<BmVesselVoyage> list = bmVesselVoyageService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询船舶航次列表
     */
    @ApiOperation("查询船舶航次列表")
    @GetMapping("/list")
    public AjaxResult list(BmVesselVoyage bmVesselVoyage) {
        LambdaQueryWrapper<BmVesselVoyage> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,bmVesselVoyage);
        List<BmVesselVoyage> list = bmVesselVoyageService.list(queryWrapper);
        return success(list);
    }

    /**
     * 查询船舶航次列表
     */
    @ApiOperation("查询船舶航次列表")
    @GetMapping("/newList")
    public List<BmVesselVoyage> newList(BmVesselVoyage bmVesselVoyage){

        return bmVesselVoyageService.newList();
    }


    /**
     * 导出船舶航次列表
     */
    @ApiOperation("导出船舶航次列表")
    @Log(title = "船舶航次导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BmVesselVoyage bmVesselVoyage) {
        LambdaQueryWrapper<BmVesselVoyage> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,bmVesselVoyage);
        List<BmVesselVoyage> list = bmVesselVoyageService.list(queryWrapper);
        ExcelUtil<BmVesselVoyage> util = new ExcelUtil<BmVesselVoyage>(BmVesselVoyage. class);
        util.exportExcel(response, list, "船舶航次数据");
    }

    /**
     * 获取船舶航次详细信息
     */
    @ApiOperation("获取船舶航次详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bmVesselVoyageService.getById(id));
    }

    /**
     * 新增船舶航次
     */
    @ApiOperation("新增船舶航次")
    @Log(title = "船舶航次新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BmVesselVoyage bmVesselVoyage) {
        BmVesselVoyage tempVoyage = bmVesselVoyageService.getOne(new LambdaQueryWrapper<BmVesselVoyage>().eq(BmVesselVoyage::getVoyageNo,bmVesselVoyage.getVoyageNo()));
        if(tempVoyage!=null){
            return error("航次号已经存在，请重新输入");
        }
        bmVesselVoyage.setStatus("0");
        return toAjax(bmVesselVoyageService.save(bmVesselVoyage));
    }

    /**
     * 修改船舶航次
     */
    @ApiOperation("修改船舶航次")
    @Log(title = "船舶航次修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmVesselVoyage bmVesselVoyage) {
        BmVesselVoyage tempVoyage = bmVesselVoyageService.getOne(new LambdaQueryWrapper<BmVesselVoyage>().eq(BmVesselVoyage::getVoyageNo,bmVesselVoyage.getVoyageNo()).ne(BmVesselVoyage::getId,bmVesselVoyage.getId()));
        if(tempVoyage!=null){
            return error("航次号已经存在，请重新输入");
        }
        return toAjax(bmVesselVoyageService.updateById(bmVesselVoyage));
    }

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

    @ApiOperation("确认船舶载货清单")
    @GetMapping(value = "/check/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult checkBmvoyage(@PathVariable("id") Long id) throws ServletException {
        BmVesselVoyage voyage = bmVesselVoyageService.getById(id);
        if (null != voyage) {
            if ("1".equals(voyage.getStatus())) {
                return warn("此航次已经确认， 不能重复确认！");
            } else {
                List<BmVesselCargo> bmVesselCargos = bmVesselCargoService.list(new LambdaQueryWrapper<BmVesselCargo>().eq(BmVesselCargo::getVoyageId, id));
                List<CkBill> ckBills = new ArrayList<>();
                for (int i = 0; i < bmVesselCargos.size(); i++) {
                    CkBill ckBill = ckBillService.getOne(new LambdaQueryWrapper<CkBill>().eq(CkBill::getVoyageCargoId, bmVesselCargos.get(i).getId()));
                    if(ckBill==null){
                        return error("确认前,请先完善确认单的出入库信息");
                    }
                    ckBills.add(ckBill);
                }
                AjaxResult ret = error();
                for (int i = 0; i < ckBills.size(); i++) {
                    ret = ckBillService.warehouseWork(ckBills.get(i), false);
                    if (ret.isFail()) {
                        return ret;
                    }
                }
                if (ret.isOk()) {
                    voyage.setStatus("1");
                    return toAjax(bmVesselVoyageService.updateById(voyage));
                } else {
                    //抛出异常进行数据回滚
                    throw new ServletException("载货清单确认失败");
                }
            }
        } else {
            return error("请选择航次进行确认");
        }
    }

    @ApiOperation("取消确认船舶载货清单")
    @GetMapping(value = "/uncheck/{id}")
    public AjaxResult uncheckBmvoyage(@PathVariable("id") Long id) {
        if (null != id) {
            BmVesselVoyage voyage = bmVesselVoyageService.getById(id);
            if (null != voyage) {
                if ("0".equals(voyage.getStatus())) {
                    return warn("此航次未确认，不能取消确认！");
                } else {
                    List<CkBill> ckBills = ckBillService.list(new LambdaQueryWrapper<CkBill>().eq(CkBill::getVoyageId, id));
                    AjaxResult ret = error();
                    for (int i = 0; i < ckBills.size(); i++) {
                        CkBill ckBill = ckBills.get(i);
                        if(ckBill.getBillStatus().equals("0")){
                            return error("未提交的单据不允许做撤回操作");
                        }
                        ret = ckBillService.warehouseWork(ckBill, true);
                        if(ret.isFail()){
                            return ret;
                        }
                    }
                    if (ret.isOk()) {
                        voyage.setStatus("0");
                        return toAjax(bmVesselVoyageService.updateById(voyage));
                    } else {
                        return error("取消确认失败");
                    }
                }
            } else {
                return error("请选择航次进行确认");
            }
        }
        return success();
    }

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


        if(bmVesselVoyage.getId() != null){
            queryWrapper.eq(BmVesselVoyage::getId,bmVesselVoyage.getId());
        }

        //航次号
        if(Validator.isNotEmpty(bmVesselVoyage.getVoyageNo())){
            queryWrapper.like(BmVesselVoyage::getVoyageNo,bmVesselVoyage.getVoyageNo());
        }

        //船舶ID
        if(bmVesselVoyage.getVesselId() != null){
            queryWrapper.eq(BmVesselVoyage::getVesselId,bmVesselVoyage.getVesselId());
        }

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

        if (null != bmVesselVoyage.getBeginDate()) {
            queryWrapper.between(BmVesselVoyage::getBerthTime, bmVesselVoyage.getBeginDate(), bmVesselVoyage.getEndDate());
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getCargoName())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where cargo_name like '%"+ bmVesselVoyage.getCargoName() + "%'");
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getCustName())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where cust_name like '%"+ bmVesselVoyage.getCustName() + "%'");
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getBillNo())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where bill_no like '%"+ bmVesselVoyage.getBillNo() + "%'");
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getTradType())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where trad_type = '"+ bmVesselVoyage.getTradType() + "'");
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getCustomsNo())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where customs_no like '%"+ bmVesselVoyage.getCustomsNo() + "%'");
        }

        if (Validator.isNotEmpty(bmVesselVoyage.getListNumber())) {
            queryWrapper.inSql(BmVesselVoyage::getId, "select voyage_id from bm_vessel_cargo where list_number like '%"+ bmVesselVoyage.getListNumber() + "%'");
        }
        //净吨
        if(bmVesselVoyage.getNetTon() != null){
            queryWrapper.eq(BmVesselVoyage::getNetTon,bmVesselVoyage.getNetTon());
        }

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

        //船长
        if(bmVesselVoyage.getVesselLength() != null){
            queryWrapper.like(BmVesselVoyage::getVesselLength,bmVesselVoyage.getVesselLength());
        }

        //吃水
        if(bmVesselVoyage.getVesselDraft() != null){
            queryWrapper.like(BmVesselVoyage::getVesselDraft,bmVesselVoyage.getVesselDraft());
        }

        //载重吨
        if(bmVesselVoyage.getDwt() != null){
            queryWrapper.like(BmVesselVoyage::getDwt,bmVesselVoyage.getDwt());
        }

        //船舶动态类型
        if(Validator.isNotEmpty(bmVesselVoyage.getDynType())){
            queryWrapper.like(BmVesselVoyage::getDynType,bmVesselVoyage.getDynType());
        }

        //船舶动态
        if(Validator.isNotEmpty(bmVesselVoyage.getShipDyn())){
            queryWrapper.like(BmVesselVoyage::getShipDyn,bmVesselVoyage.getShipDyn());
        }

        //泊位ID
        if(bmVesselVoyage.getBerthId() != null){
            queryWrapper.eq(BmVesselVoyage::getBerthId,bmVesselVoyage.getBerthId());
        }

        //泊位名称
        if(Validator.isNotEmpty(bmVesselVoyage.getBerthName())){
            queryWrapper.like(BmVesselVoyage::getBerthName,bmVesselVoyage.getBerthName());
        }

        //来港目的
        if(Validator.isNotEmpty(bmVesselVoyage.getOpType())){
            queryWrapper.like(BmVesselVoyage::getOpType,bmVesselVoyage.getOpType());
        }

        //货物装卸计划量
        if(Validator.isNotEmpty(bmVesselVoyage.getCargoDesc())){
            queryWrapper.like(BmVesselVoyage::getCargoDesc,bmVesselVoyage.getCargoDesc());
        }


        //起运港
        if(bmVesselVoyage.getDeparturePort()!=null){
            queryWrapper.like(BmVesselVoyage::getDeparturePort,bmVesselVoyage.getDeparturePort());
        }

        //到达港
        if(bmVesselVoyage.getArrivalPort()!=null){
            queryWrapper.like(BmVesselVoyage::getArrivalPort,bmVesselVoyage.getArrivalPort());
        }

        //在泊时
        if(Validator.isNotEmpty(bmVesselVoyage.getOnBerth())){
            queryWrapper.eq(BmVesselVoyage::getOnBerth,bmVesselVoyage.getOnBerth());
        }

        //进引
        if(Validator.isNotEmpty(bmVesselVoyage.getInPilot())){
            queryWrapper.like(BmVesselVoyage::getInPilot,bmVesselVoyage.getInPilot());
        }

        //移引
        if(Validator.isNotEmpty(bmVesselVoyage.getRePilot())){
            queryWrapper.like(BmVesselVoyage::getRePilot,bmVesselVoyage.getRePilot());
        }

        //离引
        if(Validator.isNotEmpty(bmVesselVoyage.getUnPilot())){
            queryWrapper.like(BmVesselVoyage::getUnPilot,bmVesselVoyage.getUnPilot());
        }

        //代理
        if(Validator.isNotEmpty(bmVesselVoyage.getAgency())){
            queryWrapper.like(BmVesselVoyage::getAgency,bmVesselVoyage.getAgency());
        }

        //所属公司
        if(bmVesselVoyage.getDeptId() != null){
            queryWrapper.like(BmVesselVoyage::getDeptId,bmVesselVoyage.getDeptId());
        }

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

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



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

        }

}
