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.product.ext.BdProductBasExt;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
import com.hzs.common.domain.scm.trans.ext.IcTransOutBExt;
import com.hzs.common.domain.scm.trans.ext.IcTransOutHExt;
import com.hzs.common.domain.scm.trans.ext.TransferOrderExt;
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.ic.service.IIcBatchCodeService;
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.trans.param.TransferItemParam;
import com.hzs.scm.trans.param.TransferParam;
import com.hzs.scm.trans.service.IIcTransOutHService;
import com.hzs.scm.trans.service.ITransferOrderService;
import com.hzs.scm.trans.vo.TransferOrderBVo;
import com.hzs.scm.trans.vo.TransferOutBVo;
import com.hzs.scm.trans.vo.TransferOutExcelVO;
import com.hzs.scm.trans.vo.TransferOutVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

    @Autowired
    private IIcTransOutHService transOutService;

    @Autowired
    private ITransferOrderService transferOrderService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.TRANSFER_OUT, business = EOperationBusiness.TRANSFER_OUT, method = EOperationMethod.SELECT)
    public TableDataInfo listGeneralOut(@RequestBody TransferParam transferParam) {
        startPage();
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        List<IcTransOutHExt> transOutExtList = transOutService.queryDisTransferOutExtCondition(transferParam);
        return packageTableDataInfo(transOutExtList, packageScmReturnVo(transOutExtList));
    }

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

    private List<TransferOutExcelVO> packageScmExportVo(List<IcTransOutHExt> transInExtList) {
        List<TransferOutExcelVO> transferExcelVoList = new ArrayList<>();
        for (IcTransOutHExt transOutExt : transInExtList) {
            List<IcTransOutBExt> transOutbExtList = transOutExt.getTransOutbExtList();
            for (IcTransOutBExt transOutBiExt : transOutbExtList) {
                TransferOutExcelVO transferExcelVO = BeanUtil.copyProperties(transOutExt, TransferOutExcelVO.class);
                setScmItemsExcel(transOutBiExt, transferExcelVO);
                transferExcelVO.setInStorehouseName(transOutBiExt.getInStorehouseName());
                transferExcelVoList.add(transferExcelVO);
            }
        }
        return transferExcelVoList;
    }

    /**
     * 新增调拨入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/insert")
    @Log(module = EOperationModule.TRANSFER_OUT, business = EOperationBusiness.TRANSFER_OUT, method = EOperationMethod.INSERT)
    public AjaxResult saveGeneralOut(@RequestBody TransferParam transferParam) {
        String message = validateTransferOutParam(transferParam);
        if (ObjectUtil.isNotEmpty(message)) {
            return AjaxResult.error(TransactionUtils.getContent(message));
        }
        return AjaxResult.success();
    }

    /**
     * 修改调拨入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.TRANSFER_OUT, business = EOperationBusiness.TRANSFER_OUT, method = EOperationMethod.UPDATE)
    public AjaxResult updatePoOrder(@RequestBody TransferParam transferParam) {
        if (transferParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_OUT_NOT_EXIST));
        }
        String message = validateTransferOutParam(transferParam);
        if (ObjectUtil.isNotEmpty(message)) {
            return AjaxResult.error(TransactionUtils.getContent(message));
        }
        return AjaxResult.success();
    }

    /**
     * 查询待出库的调拨订单
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/trans-out-list")
    public TableDataInfo queryToStorePoOrder(@RequestBody TransferParam transferParam) {
        startPage();
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        transferParam.setOrderStatus(EScmOrderStatus.APPROVE.getValue());
        List<IcTransOutHExt> transoutExtList = transOutService.queryTransferOutToStoreByCondition(transferParam);
        return packageTableDataInfo(transoutExtList, packageScmReturnVo(transoutExtList));
    }

    private List<TransferOutVo> packageScmReturnVo(List<IcTransOutHExt> transoutExtList) {
        List<TransferOutVo> transferOrderList = new ArrayList<>();
        for (IcTransOutHExt transOutExt : transoutExtList) {
            TransferOutVo transferOutVo = BeanUtil.copyProperties(transOutExt, TransferOutVo.class);
            List<IcTransOutBExt> transOutbExtList = transOutExt.getTransOutbExtList();
            if (CollectionUtil.isNotEmpty(transOutbExtList)) {
                List<TransferOutBVo> returnbVoList = BeanUtil.copyToList(transOutbExtList, TransferOutBVo.class);
                transferOutVo.setScmReturnbVoList(returnbVoList);
            }
            transferOrderList.add(transferOutVo);
        }
        return transferOrderList;
    }

    /**
     * 删除调拨入库
     *
     * @param pkId 主键
     */
    @DeleteMapping("/{pkId}")
    @Log(module = EOperationModule.TRANSFER_OUT, business = EOperationBusiness.TRANSFER_OUT, method = EOperationMethod.DELETE)
    public AjaxResult delete(@PathVariable Long pkId) {
        if (pkId == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_OUT_NOT_EXIST));
        }
        IcTransOutHExt transOutExt = transOutService.queryDisTransferOutExtById(pkId, EScmOrderStatus.SAVE.getValue());
        if (transOutExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_OUT_NOT_EXIST));
        }
        transOutService.deleteTransferOut(pkId, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    private String validateTransferOutParam(TransferParam transferParam) {
        List<TransferItemParam> orderItemsParamList = new ArrayList<>();
        if (validateTransferOutFieldParam(transferParam, orderItemsParamList)) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        // 验证是否存在调拨订单, 调拨出库只能基于一个调拨订单进行调拨
        List<TransferOrderExt> transferOrderExtList = transferOrderService.queryTransferOrderByOrderItems(orderItemsParamList);
        if (transferOrderExtList == null) {
            return ScmMsgConstants.TRANSFER_ORDER_NOT_EXIST;
        }
        int size = 0;
        for (TransferOrderExt transferOrderExt : transferOrderExtList) {
            if (transferOrderExt.getTransferOrderItemsList() == null) {
                return ScmMsgConstants.TRANSFER_ORDER_NOT_EXIST;
            }
            size += transferOrderExt.getTransferOrderItemsList().size();
        }
        if (size != orderItemsParamList.size()) {
            return ScmMsgConstants.TRANSFER_ORDER_NOT_EXIST;
        }
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        // 验证采购组织
        String msg = validateSysCorp(transferParam.getPkCorp(), transferParam.getPkCountry());
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证调入采购组织
        msg = validateSysCorp(transferParam.getPkInCorp(), transferParam.getPkInCountry());
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证产品
        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;
        }
        if (validateBatchCodeByTransParam(transferParam, bdProductBasExtMap)) {
            return ScmMsgConstants.BATCH_CODE_NOT_EXIST;
        }
        if (transferParam.getPkId() == null) {
            transOutService.insertTransferOutByTransferParam(transferOrderExtList, transferParam, SecurityUtils.getUserId());
        } else {
            // 查询是否存在调拨出库
            IcTransOutHExt transOutExt = transOutService.queryDisTransferOutExtById(transferParam.getPkId(), EScmOrderStatus.SAVE.getValue());
            if (transOutExt == null) {
                return ScmMsgConstants.TRANSFER_OUT_NOT_EXIST;
            }
            transOutService.updateTransferOutByTransferParam(transferOrderExtList, transOutExt, transferParam, SecurityUtils.getUserId());
        }
        return null;
    }

    private Boolean validateTransferOutFieldParam(TransferParam transferParam, List<TransferItemParam> orderItemsParamList) {
        if (transferParam == null || transferParam.getOrderDate() == null ||
                CollectionUtil.isEmpty(transferParam.getTransferItemParamList())) {
            return Boolean.TRUE;
        }
        // 验证 采购订单明细字段不能为空
        for (TransferItemParam transferItemParam : transferParam.getTransferItemParamList()) {
            if (transferItemParam.getPkUnit() == null || transferItemParam.getPkProductBas() == null ||
                    transferItemParam.getPkTransfer() == null || transferItemParam.getPkTransferItems() == null ||
                    transferItemParam.getBizDate() == null || transferItemParam.getNnum() == null ||
                    transferItemParam.getPkStorehouse() == null || transferItemParam.getPkInStorehouse() == null) {
                return Boolean.TRUE;
            }
            orderItemsParamList.add(transferItemParam);
        }
        return Boolean.FALSE;
    }
}
