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.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
import com.hzs.common.domain.scm.trans.TransferOrderItems;
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.pub.controller.ScmController;
import com.hzs.scm.trans.param.QueryStoreParam;
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.ITransferOrderItemsService;
import com.hzs.scm.trans.service.ITransferOrderService;
import com.hzs.scm.trans.vo.TransferOrderBVo;
import com.hzs.scm.trans.vo.TransferOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

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

    @Autowired
    private ITransferOrderService transferOrderService;

    @Autowired
    private ITransferOrderItemsService transferOrderItemsService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.TRANSFER_ORDER, business = EOperationBusiness.TRANSFER_ORDER, method = EOperationMethod.SELECT)
    public TableDataInfo listTransferOrder(@RequestBody TransferParam transferParam) {
        startPage();
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        List<TransferOrderExt> transferOrderExtList = transferOrderService.queryTransferOrderByCondition(transferParam);
        return packageTableDataInfo(transferOrderExtList, packageScmReturnVo(transferOrderExtList));
    }

    private List<TransferOrderVo> packageScmReturnVo(List<TransferOrderExt> transferOrderExtList) {
        List<TransferOrderVo> transferOrderList = new ArrayList<>();
        for (TransferOrderExt transferOrderExt : transferOrderExtList) {
            TransferOrderVo transferOrderVo = BeanUtil.copyProperties(transferOrderExt, TransferOrderVo.class);
            List<TransferOrderItems> transferOrderItemsList = transferOrderExt.getTransferOrderItemsList();
            if (CollectionUtil.isNotEmpty(transferOrderItemsList)) {
                List<TransferOrderBVo> returnbVoList = BeanUtil.copyToList(transferOrderItemsList, TransferOrderBVo.class);
                transferOrderVo.setScmReturnbVoList(returnbVoList);
            }
            transferOrderList.add(transferOrderVo);
        }
        return transferOrderList;
    }

    /**
     * 查询待出库的调拨订单
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/trans-list")
    public TableDataInfo queryToStoreTransferOrder(@RequestBody TransferParam transferParam) {
        startPage();
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        List<TransferOrderExt> transferOrderExtList = transferOrderService.queryTransferOrderToStoreByCondition(transferParam);
        return packageTableDataInfo(transferOrderExtList, packageScmReturnVo(transferOrderExtList));
    }

    /**
     * 查询待入库订单的明细
     *
     * @return cubasdocParam 入参
     */
    @GetMapping("/trans-list-detail/{pkId}")
    public TableDataInfo queryToStoreDetailTransferOrder(@PathVariable Long pkId) {
        List<TransferOrderItems> transferOrderItemsList = transferOrderItemsService.queryTransferOrderItemsByPk(SecurityUtils.getPkCountry(), pkId);
        List<TransferOrderBVo> scmReturnVoList = new ArrayList<>();
        for (TransferOrderItems transferOrderItems : transferOrderItemsList) {
            scmReturnVoList.add(BeanUtil.copyProperties(transferOrderItems, TransferOrderBVo.class));
        }
        return packageTableDataInfo(transferOrderItemsList, scmReturnVoList);
    }

    /**
     * 新增采购入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/insert")
    @Log(module = EOperationModule.TRANSFER_ORDER, business = EOperationBusiness.TRANSFER_ORDER, method = EOperationMethod.INSERT)
    public AjaxResult saveTransferOrder(@RequestBody TransferParam transferParam) {
        // 验证供应商
        // 计算价税合计、总数量
        String msg = validateTransferOrderMsg(transferParam);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(msg);
        }
        transferOrderService.insertSaveTransferOrderByOrderParam(transferParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /**
     * 修改采购入库
     *
     * @param transferParam 入参
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.TRANSFER_ORDER, business = EOperationBusiness.TRANSFER_ORDER, method = EOperationMethod.UPDATE)
    public AjaxResult updateTransferOrder(@RequestBody TransferParam transferParam) {
        if (transferParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        // 验证订单状态 只有保存状态的采购订单可以进行修改
        TransferOrderExt transferOrderExt = transferOrderService.queryTransferOrderById(transferParam.getPkId(), EScmOrderStatus.SAVE.getValue());
        if (transferOrderExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_ORDER_NOT_EXIST));
        }
        // 计算价税合计、总数量
        String msg = validateTransferOrderMsg(transferParam);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(msg);
        }
        transferOrderService.updateTransferOrderByOrderParam(transferOrderExt, transferParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /*
     * @description: 验证订单相关信息
     * @author: sui q
     * @date: 2023/11/21 11:43
     * @param: null null
     **/
    private String validateTransferOrderMsg(TransferParam transferParam) {
        transferParam.setPkCountry(SecurityUtils.getPkCountry());
        Map<Integer, List<QueryStoreParam>> storehouseIdMap = new HashMap<>();
        if (validateTransferOrderParam(transferParam, storehouseIdMap)) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        // 验证采购组织
        String msg = validateSysCorp(transferParam.getPkCorp(), transferParam.getPkCountry());
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证仓库，根据采购组织验证
        msg = validateStorehouse(storehouseIdMap);
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证产品，根据产品
        // 验证规格、规格分类 需要根据产品查询 处理specsName
        String message = validateProductBas(transferParam.getTransferItemParamList());
        if (ObjectUtil.isNotEmpty(message)) {
            return message;
        }
        return null;
    }

    private Boolean validateTransferOrderParam(TransferParam transferParam, Map<Integer, List<QueryStoreParam>> storehouseIdMap) {
        // 验证 供应商、采购组织不能为空
        if (transferParam.getPkCorp() == null || transferParam.getPkInCorp() == null || transferParam.getPkInCountry() == null ||
                transferParam.getTransType() == null) {
            return Boolean.TRUE;
        }
        // 验证 采购订单明细字段不能为空
        for (TransferItemParam transferItemParam : transferParam.getTransferItemParamList()) {
            if (transferItemParam.getPkStorehouse() == null ||
                    transferItemParam.getPkUnit() == null ||
                    transferItemParam.getNnum() == null || transferItemParam.getNorigprice() == null ||
                    CollectionUtil.isEmpty(transferItemParam.getScmItemSpecsList())) {
                return Boolean.TRUE;
            }
            if (storehouseIdMap.containsKey(transferParam.getPkCountry())) {
                List<QueryStoreParam> storehouseIdSet = storehouseIdMap.get(transferParam.getPkCountry());
                QueryStoreParam queryStoreParam = new QueryStoreParam();
                queryStoreParam.setPkCorp(transferParam.getPkCorp());
                queryStoreParam.setPkStorehouse(transferItemParam.getPkStorehouse());
                storehouseIdSet.add(queryStoreParam);
            } else {
                List<QueryStoreParam> queryStoreParamList = new ArrayList<>();
                QueryStoreParam queryStoreParam = new QueryStoreParam();
                queryStoreParam.setPkCorp(transferParam.getPkCorp());
                queryStoreParam.setPkStorehouse(transferItemParam.getPkStorehouse());
                queryStoreParamList.add(queryStoreParam);
                storehouseIdMap.put(transferParam.getPkCountry(), queryStoreParamList);
            }
            if (storehouseIdMap.containsKey(transferParam.getPkInCountry())) {
                List<QueryStoreParam> storehouseIdSet = storehouseIdMap.get(transferParam.getPkInCountry());
                QueryStoreParam queryStoreParam = new QueryStoreParam();
                queryStoreParam.setPkCorp(transferParam.getPkInCorp());
                queryStoreParam.setPkStorehouse(transferItemParam.getPkInStorehouse());
                storehouseIdSet.add(queryStoreParam);
            } else {
                List<QueryStoreParam> queryStoreParamList = new ArrayList<>();
                QueryStoreParam queryStoreParam = new QueryStoreParam();
                queryStoreParam.setPkCorp(transferParam.getPkInCorp());
                queryStoreParam.setPkStorehouse(transferItemParam.getPkInStorehouse());
                queryStoreParamList.add(queryStoreParam);
                storehouseIdMap.put(transferParam.getPkInCountry(), queryStoreParamList);
            }
            if (transferItemParam.getNtaxrate() == null) {
                transferItemParam.setNtaxrate(BigDecimal.ZERO);
            }
        }
        return Boolean.FALSE;
    }

    /**
     * 删除采购入库
     *
     * @param pkId 主键
     */
    @DeleteMapping("/{pkId}")
    @Log(module = EOperationModule.TRANSFER_ORDER, business = EOperationBusiness.TRANSFER_ORDER, method = EOperationMethod.DELETE)
    public AjaxResult delete(@PathVariable Long pkId) {
        // 验证是否存在订单，订单状态是否是保存状态
        if (pkId == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        // 验证订单状态 只有保存状态的采购订单可以进行修改
        TransferOrderExt transferOrderExt = transferOrderService.queryDisTransferOrderById(pkId, EScmOrderStatus.SAVE.getValue());
        if (transferOrderExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.TRANSFER_ORDER_NOT_EXIST));
        }
        transferOrderService.deleteTransferOrder(pkId, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

}
