package com.bs.jxc.controller;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.common.constant.Constants;
import com.bs.common.utils.ServletUtils;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.sql.SqlUtil;
import com.bs.jxc.domain.CkBillCargo;
import com.bs.jxc.domain.CkCargoStock;
import com.bs.jxc.domain.CmBerth;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
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.CmCargo;
import com.bs.jxc.service.ICmCargoService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 货物信息Controller
 *
 * @author bs
 * @date 2023-07-10
 */
@Api(tags = "货物信息")
@RestController
@RequestMapping("/jxc/cargo")
public class CmCargoController extends BaseController {
    @Resource
    private ICmCargoService cmCargoService;

    /**
     * 分页查询货物信息列表
     */
    @ApiOperation("分页查询货物信息列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CmCargo cmCargo) {
        Integer pageNum = ServletUtils.getParameterToInt("pageNum");
        Integer pageSize =  ServletUtils.getParameterToInt("pageSize");
        String orderByColumn = ServletUtils.getParameter("orderByColumn");
        String isAsc = ServletUtils.getParameter("isAsc");
        MPJLambdaWrapper<CmCargo> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.selectAll(CmCargo.class)
                    .selectAs(CkBillCargo::getUpdateTime,CmCargo::getDataUpdateTime)
                    .disableSubLogicDel()
                    .leftJoin(CkBillCargo.class, CkBillCargo::getCargoId, CmCargo::getId);
         if (Validator.isNotEmpty(isAsc) && "ASC".equals(isAsc) && !"dataUpdateTime".equals(orderByColumn)) {
            queryWrapper.orderByAsc("t." + StringUtils.toUnderScoreCase(orderByColumn));
        } else if (Validator.isNotEmpty(isAsc) && "DESC".equals(isAsc) && !"dataUpdateTime".equals(orderByColumn)) {
            queryWrapper.orderByDesc("t." + StringUtils.toUnderScoreCase(orderByColumn));
        }
        conditionByMPJ(queryWrapper,cmCargo);
        List<CmCargo> list = cmCargoService.list(queryWrapper);
        List<CmCargo> filteredList = new ArrayList<>(list.stream()
                .collect(Collectors.toMap(CmCargo::getId,
                        Function.identity(),
                        (existing, replacement) -> {
                            if (existing.getDataUpdateTime() == null) {
                                return replacement;
                            } else if (replacement.getDataUpdateTime() == null) {
                                return existing;
                            } else if (existing.getDataUpdateTime().compareTo(replacement.getDataUpdateTime()) < 0) {
                                return existing;
                            } else {
                                return replacement;
                            }
                        },
                        LinkedHashMap::new))
                .values());
        if (Validator.isNotEmpty(isAsc) && "ASC".equals(isAsc) && "dataUpdateTime".equals(orderByColumn)) {
            filteredList.sort(Comparator.comparing(CmCargo::getDataUpdateTime, Comparator.nullsLast(Comparator.naturalOrder())));
        } else if (Validator.isNotEmpty(isAsc) && "DESC".equals(isAsc) && "dataUpdateTime".equals(orderByColumn)) {
            filteredList.sort(Comparator.comparing(CmCargo::getDataUpdateTime, Comparator.nullsLast(Comparator.reverseOrder())));
        }
        Integer start =  (pageNum -1 ) * pageSize;
        List<CmCargo> result = filteredList.stream()
                .skip(start)
                .limit(pageSize)
                .collect(Collectors.toList());

        TableDataInfo data = getDataTable(result);
        data.setTotal(filteredList.size());
        return data;
    }

    /**
     * 查询货物信息列表
     */
    @ApiOperation("查询货物信息列表")
    @GetMapping("/list")
    public AjaxResult list(CmCargo cmCargo) {
        LambdaQueryWrapper<CmCargo> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cmCargo);
        List<CmCargo> list = cmCargoService.list(queryWrapper);
        return success(list);
    }

    /**
     * 查询货主下货物信息列表（库存大于0）
     */
    @ApiOperation("查询货主下货物信息列表")
    @GetMapping("/custCargoList")
    public AjaxResult custCargoList(CmCargo cmCargo) {
        List<CmCargo> list = cmCargoService.custCargoList(cmCargo);
        return success(list);
    }

    /**
     * 导出货物信息列表
     */
    @ApiOperation("导出货物信息列表")
    @Log(title = "货物信息导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmCargo cmCargo) {
        MPJLambdaWrapper<CmCargo> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.selectAll(CmCargo.class)
                .selectAs(CkBillCargo::getUpdateTime,CmCargo::getDataUpdateTime)
                .disableSubLogicDel()
                .leftJoin(CkBillCargo.class, CkBillCargo::getCargoId, CmCargo::getId);
        conditionByMPJ(queryWrapper,cmCargo);
        List<CmCargo> list = cmCargoService.list(queryWrapper);
        List<CmCargo> filteredList = new ArrayList<>(list.stream()
                .collect(Collectors.toMap(CmCargo::getId,
                        Function.identity(),
                        (existing, replacement) -> {
                            if (existing.getDataUpdateTime() == null) {
                                return replacement;
                            } else if (replacement.getDataUpdateTime() == null) {
                                return existing;
                            } else if (existing.getDataUpdateTime().compareTo(replacement.getDataUpdateTime()) < 0) {
                                return existing;
                            } else {
                                return replacement;
                            }
                        },
                        LinkedHashMap::new))
                .values());
        ExcelUtil<CmCargo> util = new ExcelUtil<CmCargo>(CmCargo. class);
        util.exportExcel(response, filteredList, "货物信息数据");
    }

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

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

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

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

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

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

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

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


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

    /**
     * 新增货物信息
     */
    @ApiOperation("新增货物信息")
    @Log(title = "货物信息新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CmCargo cmCargo) {

//        CmCargo cmCargo1 = cmCargoService.getOne(new LambdaQueryWrapper<CmCargo>().eq(CmCargo::getHsCode,cmCargo.getHsCode()));
//        if(cmCargo1!=null){
//            return error("HS编号已经存在，请重新输入");
//        }

        return toAjax(cmCargoService.save(cmCargo));
    }

    /**
     * 修改货物信息
     */
    @ApiOperation("修改货物信息")
    @Log(title = "货物信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CmCargo cmCargo) {
//        CmCargo cmCargo1= cmCargoService.getOne(new LambdaQueryWrapper<CmCargo>().eq(CmCargo::getHsCode,cmCargo.getHsCode()).ne(CmCargo::getId,cmCargo.getId()));
//        if(cmCargo1!=null){
//            return error("HS编号已经存在，请重新输入");
//        }

        return toAjax(cmCargoService.updateById(cmCargo));
    }

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

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




        //HS编号
        if(Validator.isNotEmpty(cmCargo.getHsCode())){
            queryWrapper.like(CmCargo::getHsCode,cmCargo.getHsCode());
        }

        //项号
        if(Validator.isNotEmpty(cmCargo.getGdsSeqno())){
            queryWrapper.like(CmCargo::getGdsSeqno,cmCargo.getGdsSeqno());
        }

        if(Validator.isNotEmpty(cmCargo.getEmsNo())){
            queryWrapper.eq(CmCargo::getEmsNo,cmCargo.getEmsNo());
        }


        //商品名称
        if(Validator.isNotEmpty(cmCargo.getCargoName())){
            queryWrapper.like(CmCargo::getCargoName,cmCargo.getCargoName());
        }

        //规格类型品质
        if(Validator.isNotEmpty(cmCargo.getCargoSpec())){
            queryWrapper.like(CmCargo::getCargoSpec,cmCargo.getCargoSpec());
        }

        //原产国
        if(Validator.isNotEmpty(cmCargo.getOriginCountry())){
            queryWrapper.like(CmCargo::getOriginCountry,cmCargo.getOriginCountry());
        }

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

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



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

        }

    /**
     * 条件设置
     */
    private void conditionByMPJ (MPJLambdaWrapper<CmCargo> queryWrapper,CmCargo cmCargo){




        //HS编号
        if(Validator.isNotEmpty(cmCargo.getHsCode())){
            queryWrapper.like(CmCargo::getHsCode,cmCargo.getHsCode());
        }

        //项号
        if(Validator.isNotEmpty(cmCargo.getGdsSeqno())){
            queryWrapper.like(CmCargo::getGdsSeqno,cmCargo.getGdsSeqno());
        }

        if(Validator.isNotEmpty(cmCargo.getEmsNo())){
            queryWrapper.eq(CmCargo::getEmsNo,cmCargo.getEmsNo());
        }


        //商品名称
        if(Validator.isNotEmpty(cmCargo.getCargoName())){
            queryWrapper.like(CmCargo::getCargoName,cmCargo.getCargoName());
        }

        //规格类型品质
        if(Validator.isNotEmpty(cmCargo.getCargoSpec())){
            queryWrapper.like(CmCargo::getCargoSpec,cmCargo.getCargoSpec());
        }

        //原产国
        if(Validator.isNotEmpty(cmCargo.getOriginCountry())){
            queryWrapper.like(CmCargo::getOriginCountry,cmCargo.getOriginCountry());
        }

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

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



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

    }

}
