package com.hzs.scm.trans.controller.manage;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.constant.msg.ScmMsgConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.classify.BdSpecs;
import com.hzs.common.domain.sale.product.ext.BdProductBasExt;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
import com.hzs.common.domain.scm.purchase.ext.IcPurchaseInHExt;
import com.hzs.common.domain.scm.trans.ext.IcTransInBExt;
import com.hzs.common.domain.scm.trans.ext.IcTransInHExt;
import com.hzs.common.domain.scm.trans.ext.IcTransOutBExt;
import com.hzs.common.domain.scm.trans.ext.IcTransOutHExt;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.scm.pub.controller.ScmController;
import com.hzs.scm.pub.param.ScmApproveParam;
import com.hzs.scm.pub.service.IScmOrderApproveLogService;
import com.hzs.scm.purchase.param.PurchaseInParam;
import com.hzs.scm.trans.param.TransferItemParam;
import com.hzs.scm.trans.param.TransferParam;
import com.hzs.scm.trans.service.IIcTransInHService;
import com.hzs.scm.trans.service.IIcTransOutHService;
import com.hzs.scm.trans.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 调拨入库单表头 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2023-12-04
 */
@RestController
@RequestMapping("/manage/trans-in")
public class IcTransInHController extends ScmController {

    @Autowired
    private IIcTransOutHService transOutService;

    @Autowired
    private IIcTransInHService transInService;

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    /**
     * 查询列表
     *
     * @return transferParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.TRANSFER_IN, business = EOperationBusiness.TRANSFER_IN, method = EOperationMethod.SELECT)
    public TableDataInfo listTransIn(@RequestBody TransferParam transferParam) {
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        startPage();
        List<IcTransInHExt> transInExtList = transInService.queryDisTransferInInExtByCondition(transferParam);
        return packageTableDataInfo(transInExtList, packageScmReturnVo(transInExtList));
    }

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list-total")
    public TableDataInfo listTransInTotal(@RequestBody TransferParam transferParam) {
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        startPage();
        transferParam.setOrderState(EScmOrderStatus.APPROVE.getValue());
        List<IcTransInHExt> transInExtList = transInService.queryDisTransferInInExtByCondition(transferParam);
        return packageTableDataInfo(transInExtList, packageScmReturnVo(transInExtList));
    }

    private List<TransferInVo> packageScmReturnVo(List<IcTransInHExt> transInExtList) {
        List<TransferInVo> transferInList = new ArrayList<>();
        for (IcTransInHExt transInExt : transInExtList) {
            TransferInVo transferInVo = BeanUtil.copyProperties(transInExt, TransferInVo.class);
            List<IcTransInBExt> transInbiExtList = transInExt.getTransInbExtList();
            if (CollectionUtil.isNotEmpty(transInbiExtList)) {
                List<TransferInBVo> returnbVoList = BeanUtil.copyToList(transInbiExtList, TransferInBVo.class);
                transferInVo.setScmReturnbVoList(returnbVoList);
            }
            transferInList.add(transferInVo);
        }
        return transferInList;
    }

    /**
     * 分页查询会员某个时间段内的奖金汇总
     */
    @PostMapping("/export-list-total")
    @Log(module = EOperationModule.TRANSFER_IN, business = EOperationBusiness.TRANSFER_IN, method = EOperationMethod.EXPORT)
    public void exportListTransInTotal(HttpServletResponse response, TransferParam transferParam) {
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        transferParam.setOrderState(EScmOrderStatus.APPROVE.getValue());
        List<IcTransInHExt> transInExtList = transInService.queryDisTransferInInExtByCondition(transferParam);
        List<TransferExcelVO> transferExcelVoList = packageScmExportVo(transInExtList);
        ExcelUtil<TransferExcelVO> util = new ExcelUtil<>(TransferExcelVO.class);
        util.exportExcel(response, transferExcelVoList, "调拨入库导出");
    }

    private List<TransferExcelVO> packageScmExportVo(List<IcTransInHExt> transInExtList) {
        List<TransferExcelVO> transferExcelVoList = new ArrayList<>();
        for (IcTransInHExt transInExt : transInExtList) {
            List<IcTransInBExt> transInbExtList = transInExt.getTransInbExtList();
            for (IcTransInBExt transInBiExt : transInbExtList) {
                TransferExcelVO transferExcelVO = BeanUtil.copyProperties(transInExt, TransferExcelVO.class);
                setScmItemsExcel(transInBiExt, transferExcelVO);
                transferExcelVO.setBizDate(transInBiExt.getBizDate());
                transferExcelVO.setOutStorehouseName(transInBiExt.getOutStorehouseName());
                transferExcelVoList.add(transferExcelVO);
            }
        }
        return transferExcelVoList;
    }


    /**
     * 新增调拨入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/insert")
    @Log(module = EOperationModule.TRANSFER_IN, business = EOperationBusiness.TRANSFER_IN, method = EOperationMethod.INSERT)
    public AjaxResult saveTransIn(@RequestBody TransferParam transferParam) {
        String message = validateTransferParam(transferParam);
        if (ObjectUtil.isNotEmpty(message)) {
            return AjaxResult.error(TransactionUtils.getContent(message));
        }
        // 审核通过后需要关闭调拨订单 回写调拨订单累计入库数量
        return AjaxResult.success();
    }

    private String validateTransferParam(TransferParam transferParam) {
        List<TransferItemParam> transferItemParams = new ArrayList<>();
        if (validateTransferInParam(transferParam, transferItemParams)) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        transferParam.setPkCountry(SecurityUtils.getPkCountry());

        // 验证是否存在调拨出库单,根据调拨出库单生成表头 表体信息
        List<IcTransOutHExt> transOutExtList = transOutService.queryTransferOutByOrderItems(transferItemParams);
        if (transOutExtList == null || transOutExtList.size() == 0) {
            return ScmMsgConstants.TRANSFER_OUT_NOT_EXIST;
        }
        // 验证产品
        Map<String, BdSpecs> specsMap = new HashMap<>();
        String message = validateProduct(transferParam.getTransferItemParamList(), specsMap);
        if (ObjectUtil.isNotEmpty(message)) {
            return message;
        }
//        Set<Integer> idList = transferParam.getTransferItemParamList().stream().map(TransferItemParam::getPkProductBas).collect(Collectors.toSet());
//        Map<Integer, BdProductBasExt> bdProductBasExtMap = getBdProductBasExtMap(idList);
//        if (bdProductBasExtMap == null){
//            return ScmMsgConstants.PRODUCT_NOT_EXIST;
//        }
        // 判断是否有批次，有批次需要验证批次
        IcTransOutHExt transOutExt = transOutExtList.get(0);
        transferParam.setPkCorp(transOutExt.getPkCorp());
        message = validateProductBatchCode(transferParam.getTransferItemParamList(), specsMap);
        if (ObjectUtil.isNotEmpty(message)) {
            return message;
        }
//        if (validateBatchCodeByTransParam(transferParam, bdProductBasExtMap)){
//            return ScmMsgConstants.BATCH_CODE_NOT_EXIST;
//        }
        if (transferParam.getPkId() == null) {
            transInService.insertSaveTransferInByTransferOrder(transOutExtList, transferParam, SecurityUtils.getUserId());
        } else {
            // 查询是否存在调拨入库单
            IcTransInHExt transInExt = transInService.queryTransferInInhExtById(transferParam.getPkId(), EScmOrderStatus.SAVE.getValue(), SecurityUtils.getPkCountry());
            if (transInExt == null) {
                return ScmMsgConstants.TRANSFER_IN_NOT_EXIST;
            }
            transInService.updateSaveTransferInByPoOrder(transOutExtList, transInExt, transferParam, SecurityUtils.getUserId());
        }
        return null;
    }

    private Boolean validateTransferInParam(TransferParam transferParam, List<TransferItemParam> transferItemParams) {
        if (transferParam == null || CollectionUtil.isEmpty(transferParam.getTransferItemParamList())) {
            return Boolean.TRUE;
        }
        // 验证 调拨订单明细字段不能为空
        for (TransferItemParam transferItemParam : transferParam.getTransferItemParamList()) {
            if (transferItemParam.getPkUnit() == null || transferItemParam.getPkProductBas() == null ||
                    transferItemParam.getPkTransferOut() == null || transferItemParam.getPkTransferOutB() == null ||
                    transferItemParam.getBizDate() == null || transferItemParam.getNnum() == null ||
                    /*transferItemParam.getPkStorehouse() == null ||*/ transferItemParam.getPkOutStorehouse() == null ||
                    transferItemParam.getScmItemSpecsList() == null || transferItemParam.getScmItemSpecsList().size() == 0) {
                return Boolean.TRUE;
            }
            transferItemParams.add(transferItemParam);
        }
        return Boolean.FALSE;
    }


    /**
     * 修改调拨入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.TRANSFER_IN, business = EOperationBusiness.TRANSFER_IN, method = EOperationMethod.UPDATE)
    public AjaxResult updateTransferIn(@RequestBody TransferParam transferParam) {
        if (transferParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_IN_NOT_EXIST));
        }
        String message = validateTransferParam(transferParam);
        if (ObjectUtil.isNotEmpty(message)) {
            return AjaxResult.error(TransactionUtils.getContent(message));
        }
        // 审核通过后需要关闭调拨订单 回写调拨订单累计入库数量
        return AjaxResult.success();
    }

    /**
     * 删除调拨订单
     *
     * @param pkId 主键
     */
    @DeleteMapping("/{pkId}")
    @Log(module = EOperationModule.TRANSFER_IN, business = EOperationBusiness.TRANSFER_IN, method = EOperationMethod.DELETE)
    public AjaxResult delete(@PathVariable Long pkId) {
        if (pkId == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_IN_NOT_EXIST));
        }
        IcTransInHExt transInExt = transInService.queryTransferInInhExtById(pkId, EScmOrderStatus.SAVE.getValue(), SecurityUtils.getPkCountry());
        if (transInExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_IN_NOT_EXIST));
        }
        transInService.deleteTransferInByPk(pkId, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

}
