package com.ruoyi.web.controller.shipping.controller;

import java.io.*;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.service.ITCorpsService;
import com.ruoyi.basicData.service.ITGoodsService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.shipping.domain.TCntrno;
import com.ruoyi.shipping.domain.TWarehousebillsCntritems;
import com.ruoyi.shipping.excel.TWarehousebillsCntritemsExcel;
import com.ruoyi.shipping.service.ITWarehousebillsCntritemsService;
import com.ruoyi.warehouseBusiness.domain.TWarehouseBills;
import com.ruoyi.warehouseBusiness.service.ITWarehouseBillsService;
import com.sun.jna.platform.unix.solaris.LibKstat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 凯和订单Controller
 * 
 * @author ruoyi
 * @date 2021-04-08
 */
@Slf4j
@RestController
@RequestMapping("/khwarehouse/warehousebills")
public class KHTWarehousebillsController extends BaseController
{
    @Autowired
    private ITWarehouseBillsService tWarehousebillsService;
    @Autowired
    private ITCorpsService itCorpsService;
    @Autowired
    private ITGoodsService itGoodsService;
    @Autowired
    private ITWarehousebillsCntritemsService tWarehousebillsCntritemsService;
    @Value("${ruoyi.downloadPath}")
    private String downloadPath;

    /**
     * 查询凯和订单列表
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWarehouseBills tWarehousebills)
    {
        startPage();
        List<TWarehouseBills> list = tWarehousebillsService.selectTWarehousebillsList(tWarehousebills);
        return getDataTable(list);
    }

    /**
     * 导出凯和订单列表
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:export')")
    @Log(title = "凯和订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWarehouseBills tWarehousebills)
    {
        List<TWarehouseBills> list = tWarehousebillsService.selectTWarehousebillsList(tWarehousebills);
        ExcelUtil<TWarehouseBills> util = new ExcelUtil<TWarehouseBills>(TWarehouseBills.class);
        return util.exportExcel(list, "warehousebills");
    }

    /**
     * 获取凯和订单详细信息
     */
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:query')")
    @GetMapping(value = "/{fId}")
    public AjaxResult getInfo(@PathVariable("fId") Long fId)
    {
        return tWarehousebillsService.selectTWarehousebills(fId);
    }

    /**
     * 新增凯和订单
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:add')")
    @Log(title = "凯和订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWarehouseBills tWarehousebills)
    {
        return toAjax(tWarehousebillsService.insertTWarehousebills(tWarehousebills));
    }

    /**
     * 凯和订单计划暂存
     * @param tWarehousebills
     * @param tWarehousebillsCntr
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:tSPlantMessage')")
    @Log(title = "凯和订单", businessType = BusinessType.INSERT)
    @PostMapping("/tSPlantMessage")
    public AjaxResult TSPlantMessage(@RequestParam String tWarehousebills,
                                 @RequestParam String tWarehousebillsCntr)
    {
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        if (StringUtils.isEmpty(tWarehousebillsCntr)){
            return AjaxResult.error("未找到订单明细表数据,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.TSPlantMessage(tWarehousebills,tWarehousebillsCntr,
                billsType,loginUser);
    }
    /**
     * 凯和订单计划提交
     * @param tWarehousebills
     * @param tWarehousebillsCntr
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:submitPlantMessage')")
    @Log(title = "凯和订单", businessType = BusinessType.INSERT)
    @PostMapping("/submitPlantMessage")
    public AjaxResult submitPlantMessage(@RequestParam(value = "tWarehousebills") String tWarehousebills,
                                 @RequestParam(value = "tWarehousebillsCntr") String tWarehousebillsCntr)
    {
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        if (StringUtils.isEmpty(tWarehousebillsCntr)){
            return AjaxResult.error("未找到订单明细表数据,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.submitPlantMessage(tWarehousebills,tWarehousebillsCntr,
                billsType,loginUser);
    }
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:tSMakingMessage')")

    /**
     * 凯和订单配船暂存
     * @param tWarehousebills
     * @param tWarehousebillsCntritems
     * @return
     */
    @Log(title = "凯和订单", businessType = BusinessType.INSERT)
    @PostMapping("/tSMakingMessage")
    public AjaxResult TSMakingMessage(@RequestParam String tWarehousebills,
                                         @RequestParam String tWarehousebillsCntritems)
    {
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        if (StringUtils.isEmpty(tWarehousebillsCntritems)){
            return AjaxResult.error("未找到订单明细表数据,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.TSMakingMessage(tWarehousebills,tWarehousebillsCntritems,
                billsType,loginUser);
    }

    /**
     * 凯和订单配船提交
     * @param tWarehousebills
     * @param tWarehousebillsCntritems
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:submitMakingMessage')")
    //@Log(title = "凯和订单", businessType = BusinessType.INSERT)
    @PostMapping("/submitMakingMessage")
    public AjaxResult submitMakingMessage(@RequestParam String tWarehousebills,
                                      @RequestParam String tWarehousebillsCntritems)
    {
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        if (StringUtils.isEmpty(tWarehousebillsCntritems)){
            return AjaxResult.error("未找到订单明细表数据,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.submitMakingMessage(tWarehousebills,tWarehousebillsCntritems,
                billsType,loginUser);
    }


    /**
     * 修改凯和订单
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:edit')")
    //@Log(title = "凯和订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWarehouseBills tWarehousebills)
    {
        return toAjax(tWarehousebillsService.updateTWarehousebills(tWarehousebills));
    }

    /**
     * 删除凯和订单
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:remove')")
    @Log(title = "凯和订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fIds}")
    public AjaxResult remove(@PathVariable Long[] fIds)
    {
        return toAjax(tWarehousebillsService.deleteTWarehousebills(fIds));
    }
    @Log(title = "凯和订单查询客户名称", businessType = BusinessType.DELETE)
    @PostMapping("/getClientName")
    public AjaxResult getClientName(TCorps tCorps){
        /*LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        tCorps.setfTel(loginUser.getUser().getPhonenumber());*/
        List<Map<String, Object>> clientName = itCorpsService.getClientName(tCorps);
        return AjaxResult.success(clientName);
    }
    @Log(title = "凯和订单查询商品名称", businessType = BusinessType.DELETE)
    @PostMapping("/getGoodName")
    public AjaxResult getGoodName(){
        List<Map<String, Object>> goodName = itGoodsService.getGoodName();
        return AjaxResult.success(goodName);
    }
   // @Log(title = "凯和网页版订单查询详情", businessType = BusinessType.DELETE)
    @PostMapping("/webVersionOrder")
    public TableDataInfo webVersionOrder(@RequestBody(required = false) TWarehouseBills tWarehouseBills){
        startPage();
        List<TWarehouseBills> warehouseBills = tWarehousebillsService.webVersionOrder(tWarehouseBills);
        return getDataTable(warehouseBills);
    }
    //@Log(title = "凯和网页版订单查询", businessType = BusinessType.DELETE)
    @GetMapping("/webVersionOrderMessage")
    public TableDataInfo webVersionOrderMessage(TWarehouseBills tWarehouseBills){
        startPage();
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        List<Map<String,Object>> warehouseBills = tWarehousebillsService.webVersionOrderMessage(loginUser,tWarehouseBills);
        return getDataTable(warehouseBills);
    }
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:ruoYiVersionOrderList')")
    @Log(title = "凯和若依订单查询", businessType = BusinessType.DELETE)
    @GetMapping("/ruoYiVersionOrderList")
    public TableDataInfo ruoYiVersionOrderList(TWarehouseBills tWarehouseBills){
        startPage();
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        List<Map<String,Object>> warehouseBills = tWarehousebillsService.ruoYiVersionOrderList(loginUser,tWarehouseBills);
        return getDataTable(warehouseBills);
    }
    //@PreAuthorize("@ss.hasPermi('warehouse:warehousebills:webVersionOrderDetails')")
    @Log(title = "凯和若依订单详情", businessType = BusinessType.DELETE)
    @PostMapping("/webVersionOrderDetails")
    public TableDataInfo webVersionOrderDetails(@RequestBody TWarehouseBills tWarehouseBills){
        startPage();
        List<TWarehouseBills> warehouseBills = tWarehousebillsService.webVersionOrderDetails(tWarehouseBills);
        return getDataTable(warehouseBills);
    }

    /**
     * 船运订单维护提单号和费用信息
     * @param tWarehousebills
     * @param tWarehousebillsCntritems
     * @param tWarehousebillsfeesCr
     * @param tWarehousebillsfeesDr
     * @return
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:ruoYiUpdateOrderMessage')")
    //@Log(title = "凯和若依订单维护", businessType = BusinessType.DELETE)
    @PostMapping("/ruoYiUpdateOrderMessage")
    public AjaxResult ruoYiUpdateOrderMessage(@RequestParam(value = "tWarehousebills") String tWarehousebills,
                                              @RequestParam(value = "tWarehousebillsCntr",required = false) String tWarehousebillsCntr,
                                                @RequestParam(value = "tWarehousebillsCntritems",required = false) String tWarehousebillsCntritems,
                                                          @RequestParam("tWarehousebillsfeesCr") String tWarehousebillsfeesCr,
                                              @RequestParam("tWarehousebillsfeesDr") String tWarehousebillsfeesDr){
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.ruoYiUpdateOrderMessage(tWarehousebills,tWarehousebillsCntr,tWarehousebillsCntritems,
                tWarehousebillsfeesCr,tWarehousebillsfeesDr,loginUser,billsType);

    }

    /**
     * 船运订单提交审核
     * @param tWarehousebills
     * @param tWarehousebillsCntritems
     * @param tWarehousebillsfeesCr
     * @param tWarehousebillsfeesDr
     * @return
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:ruoYiSubmitMessage')")
    //@Log(title = "凯和若依订单提交", businessType = BusinessType.DELETE)
    @PostMapping("/ruoYiSubmitMessage")
    public AjaxResult ruoYiSubmitMessage(@RequestParam(value = "tWarehousebills") String tWarehousebills,
                                         @RequestParam(value = "tWarehousebillsCntr",required = false) String tWarehousebillsCntr,
                                              @RequestParam(value = "tWarehousebillsCntritems",required = false) String tWarehousebillsCntritems,
                                              @RequestParam("tWarehousebillsfeesCr") String tWarehousebillsfeesCr,
                                              @RequestParam("tWarehousebillsfeesDr") String tWarehousebillsfeesDr){
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.ruoYiSubmitMessage(tWarehousebills,tWarehousebillsCntr,tWarehousebillsCntritems,
                tWarehousebillsfeesCr,tWarehousebillsfeesDr,loginUser,billsType);

    }
    @PostMapping("/updateOrderMessage")
    public AjaxResult updateOrderMessage(@RequestBody TWarehouseBills tWarehouseBills){
        if (StringUtils.isEmpty(tWarehouseBills.getfMblno())){
            return AjaxResult.error("提单号不能为空,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.updateOrderMessage(tWarehouseBills);

    }
    /**
     * 凯和商务版导入【箱信息】Excel
     */
    @PostMapping(value = "/importCreateNew")
    public AjaxResult importCreateCompanyMsg(@RequestParam("file") MultipartFile file)throws Exception
    {
        return tWarehousebillsService.importCreateCompanyMsg(file);
    }

    /**
     * 凯和商务端新的上传方式
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/importCreate")
    public AjaxResult importCreateCompanyMsgNew(@RequestParam("file") MultipartFile file,
                                                @RequestParam("fId") Long fId)throws Exception
    {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
//        try {
            AjaxResult ajaxResult = tWarehousebillsService.importCreateCompanyMsgNew(file, loginUser,fId);
            return ajaxResult;
//        }catch (Exception e){
//            return AjaxResult.error("导入失败");
//        }
    }
    /**
     * 下载箱信息导入模板
     */
    @GetMapping("/importTCntrnoTemplate")
    public AjaxResult importTCntrnoTemplate()
    {
        ExcelUtil<TWarehousebillsCntritemsExcel> util = new ExcelUtil<TWarehousebillsCntritemsExcel>(TWarehousebillsCntritemsExcel.class);
        return util.importTemplateExcel("商务版箱信息数据模板");
    }
    @GetMapping("/download")
    public AjaxResult download(String fileName) {
        String filePath = RuoYiConfig.getDownloadPath() + fileName;
        File file = new File(filePath);
        if (!file.exists()){
            AjaxResult ajaxResult = this.importTCntrnoTemplate();
            String code = ajaxResult.get("code").toString();
            if ("500".equals(code)) {
                return AjaxResult.error("下载摸版失败");
            }
        }
        String path = downloadPath+fileName;
        return AjaxResult.success("success",path);
    }

    /**
     * 凯和获取提单号
     * @param tWarehousebills
     * @return
     */
    @Log(title = "凯和订单获取提单号", businessType = BusinessType.INSERT)
    @PostMapping("/getMblno")
    public AjaxResult getMblno(@RequestBody TWarehouseBills tWarehousebills)
    {
        return tWarehousebillsService.getMblno(tWarehousebills);
    }

    /**
     * 批量修改船名航次
     * @param tWarehousebills
     * @return
     */
    @PostMapping("/batchModifyingVesselVoyage")
    public AjaxResult batchModifyingVesselVoyage(@RequestBody TWarehouseBills tWarehousebills){
        if (tWarehousebills.getOrderId().length<1){
            return AjaxResult.error("请选择要修改的订单");
        }
        if (tWarehousebills.getfVslid() == null){
            return AjaxResult.error("请选择要修改为那条船");
        }
        if (tWarehousebills.getfVoyid() == null){
            return AjaxResult.error("请选择要修改为那个航次");
        }
        if (tWarehousebills.getfCargoPlanning() != null){
            return tWarehousebillsService.batchModifyingVesselVoyage(tWarehousebills.getOrderId(),tWarehousebills.getfVslid(),tWarehousebills.getfVoyid(),tWarehousebills.getfCargoPlanning());
        }else {
            return tWarehousebillsService.batchModifyingVesselVoyage(tWarehousebills.getOrderId(),tWarehousebills.getfVslid(),tWarehousebills.getfVoyid(),null);
        }
    }

    /**
     * 配船
     * @param tWarehousebills 主表
     * fCargoPlanning 是否配船(0 是 1 否) 默认为1
     * @return
     */
    @PostMapping("/cargoPlanning")
    public AjaxResult cargoPlanning(@RequestBody TWarehouseBills tWarehousebills){
        return tWarehousebillsService.batchModifyingVesselVoyage(tWarehousebills.getOrderId(),null,null,1L);
    }
    /**
     * 撤销费用请核
     * @param tWarehousebills
     * @param tWarehousebillsCntritems
     * @param tWarehousebillsfeesCr
     * @param tWarehousebillsfeesDr
     * @return
     */
    @PreAuthorize("@ss.hasPermi('warehouse:warehousebills:ruoYiSubmitMessage')")
    //@Log(title = "凯和若依订单提交", businessType = BusinessType.DELETE)
    @PostMapping("/cancellationFees")
    public AjaxResult cancellationFees(@RequestParam(value = "tWarehousebills") String tWarehousebills,
                                         @RequestParam(value = "tWarehousebillsCntr",required = false) String tWarehousebillsCntr,
                                         @RequestParam(value = "tWarehousebillsCntritems",required = false) String tWarehousebillsCntritems,
                                         @RequestParam("tWarehousebillsfeesCr") String tWarehousebillsfeesCr,
                                         @RequestParam("tWarehousebillsfeesDr") String tWarehousebillsfeesDr){
        if (StringUtils.isEmpty(tWarehousebills)){
            return AjaxResult.error("未找到订单主表信息,请确认");
        }
        String billsType = "KHDD";
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return tWarehousebillsService.cancellationFees(tWarehousebills,tWarehousebillsCntr,tWarehousebillsCntritems,
                tWarehousebillsfeesCr,tWarehousebillsfeesDr,loginUser,billsType);

    }
}
