package com.hzs.scm.po.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.po.ext.PoOrderExt;
import com.hzs.common.domain.scm.po.ext.PoOrderItemsExt;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
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.po.param.PoOrderItemsParam;
import com.hzs.scm.po.param.PoOrderParam;
import com.hzs.scm.po.service.IPoOrderItemsService;
import com.hzs.scm.po.service.IPoOrderService;
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.po.vo.PoOrderBVo;
import com.hzs.scm.po.vo.PoOrderVo;
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-11-17
 */
@RestController
@RequestMapping("/manage/po")
public class PoOrderController extends ScmController {

    @Autowired
    private IPoOrderService poOrderService;

    @Autowired
    private IPoOrderItemsService poOrderItemsService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.PO_ORDER, business = EOperationBusiness.PO_ORDER, method = EOperationMethod.SELECT)
    public TableDataInfo listPoOrder(@RequestBody PoOrderParam poOrderParam) {
        startPage();
        poOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        List<PoOrderExt> poOrderExtList = poOrderService.queryPoOrderByCondition(poOrderParam);
        List<PoOrderVo> poOrderVoList = packageScmReturnVo(poOrderExtList);
        return packageTableDataInfo(poOrderExtList, poOrderVoList);
    }

    private List<PoOrderVo> packageScmReturnVo(List<PoOrderExt> poOrderExtList) {
        List<PoOrderVo> poOrderVoList = new ArrayList<>();
        for (PoOrderExt poOrderExt : poOrderExtList) {
            PoOrderVo poOrderVo = BeanUtil.copyProperties(poOrderExt, PoOrderVo.class);
            List<PoOrderItemsExt> poOrderItemsExtList = poOrderExt.getPoOrderItemsExtList();
            if (CollectionUtil.isNotEmpty(poOrderItemsExtList)) {
                List<PoOrderBVo> returnbVoList = BeanUtil.copyToList(poOrderItemsExtList, PoOrderBVo.class);
                poOrderVo.setScmReturnbVoList(returnbVoList);
            }
            poOrderVoList.add(poOrderVo);
        }
        return poOrderVoList;
    }

    /**
     * 查询待入库订单
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/store-list")
    public TableDataInfo queryToStorePoOrder(@RequestBody PoOrderParam poOrderParam) {
        startPage();
        poOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        List<PoOrderExt> poOrderExtList = poOrderService.queryPoOrderToStoreByCondition(poOrderParam);
        List<PoOrderVo> poOrderVoList = packageScmReturnVo(poOrderExtList);
        return packageTableDataInfo(poOrderExtList, poOrderVoList);
    }

    /**
     * 查询待入库订单的明细
     *
     * @return cubasdocParam 入参
     */
    @GetMapping("/list-detail/{pkId}")
    public TableDataInfo queryToPoOrderItems(@PathVariable Long pkId) {
        List<PoOrderItemsExt> poOrderItemsExtList = poOrderItemsService.queryListPoOrderItemsByPk(SecurityUtils.getPkCountry(), pkId);
        List<PoOrderBVo> scmReturnVoList = new ArrayList<>();
        for (PoOrderItemsExt poOrderItemsExt : poOrderItemsExtList) {
            scmReturnVoList.add(BeanUtil.copyProperties(poOrderItemsExt, PoOrderBVo.class));
        }
        return packageTableDataInfo(poOrderItemsExtList, scmReturnVoList);
    }

    /**
     * 查询待入库订单的明细
     *
     * @return cubasdocParam 入参
     */
    @GetMapping("/store-list-detail/{pkId}")
    public TableDataInfo queryToStorePoOrder(@PathVariable Long pkId) {
        List<PoOrderItemsExt> poOrderItemsExtList = poOrderItemsService.queryPoOrderItemsByPk(SecurityUtils.getPkCountry(), pkId);
        List<PoOrderBVo> scmReturnVoList = new ArrayList<>();
        for (PoOrderItemsExt poOrderItemsExt : poOrderItemsExtList) {
            scmReturnVoList.add(BeanUtil.copyProperties(poOrderItemsExt, PoOrderBVo.class));
        }
        return packageTableDataInfo(poOrderItemsExtList, scmReturnVoList);
    }

    /**
     * 新增采购入库
     *
     * @param poOrderParam 入参
     */
    @PostMapping("/insert")
    @Log(module = EOperationModule.PO_ORDER, business = EOperationBusiness.PO_ORDER, method = EOperationMethod.INSERT)
    public AjaxResult savePoOrder(@RequestBody PoOrderParam poOrderParam) {
        int pkCountry = SecurityUtils.getPkCountry();
        // 验证供应商
        String msg = validatePoOrderMsg(poOrderParam, pkCountry);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(TransactionUtils.getContent(msg));
        }
        // 计算价税合计、总数量
        poOrderParam.setPkCountry(pkCountry);
        poOrderService.insertSavePoOrderByOrderParam(poOrderParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /**
     * 修改采购入库
     *
     * @param poOrderParam 入参
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.PO_ORDER, business = EOperationBusiness.PO_ORDER, method = EOperationMethod.UPDATE)
    public AjaxResult updatePoOrder(@RequestBody PoOrderParam poOrderParam) {
        if (poOrderParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        int pkCountry = SecurityUtils.getPkCountry();
        // 验证订单状态 只有保存状态的采购订单可以进行修改
        PoOrderExt poOrderExt = poOrderService.queryPoOrderById(poOrderParam.getPkId(), EScmOrderStatus.SAVE.getValue());
        if (poOrderExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.PO_ORDER_NOT_EXIST));
        }
        String msg = validatePoOrderMsg(poOrderParam, pkCountry);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(TransactionUtils.getContent(msg));
        }
        // 计算价税合计、总数量
        poOrderParam.setPkCountry(pkCountry);
        poOrderService.updatePorOrderByOrderParam(poOrderExt, poOrderParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /*
     * @description: 验证订单相关信息
     * @author: sui q
     * @date: 2023/11/21 11:43
     * @param: null null
     **/
    private String validatePoOrderMsg(PoOrderParam poOrderParam, int pkCountry) {
        Set<Integer> storehouseIdSet = new HashSet<>();
        if (validatePoOrderParam(poOrderParam, storehouseIdSet)) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        // 验证供应商
        String msg = validateCuBasDoc(poOrderParam.getPkCubasdoc(), pkCountry);
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证采购组织
        msg = validateSysCorp(poOrderParam.getPkCorp(), pkCountry);
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证仓库，根据采购组织验证
        msg = validateStorehouse(storehouseIdSet, pkCountry, poOrderParam.getPkCorp());
        if (ObjectUtil.isNotEmpty(msg)) {
            return msg;
        }
        // 验证产品，根据产品
        // 验证规格、规格分类 需要根据产品查询 处理specsName
        String message = validateProductBas(poOrderParam.getPoOrderItemsParamList());
        if (ObjectUtil.isNotEmpty(message)) {
            return message;
        }
        return null;
    }

    private Boolean validatePoOrderParam(PoOrderParam poOrderParam, Set<Integer> storehouseIdSet) {
        // 验证 供应商、采购组织不能为空
        if (poOrderParam.getPkCubasdoc() == null || poOrderParam.getPkCorp() == null || CollectionUtil.isEmpty(poOrderParam.getPoOrderItemsParamList())) {
            return Boolean.TRUE;
        }
        // 验证 采购订单明细字段不能为空
        for (PoOrderItemsParam poOrderItemsParam : poOrderParam.getPoOrderItemsParamList()) {
            if (poOrderItemsParam.getPkProductBas() == null || poOrderItemsParam.getPkStorehouse() == null ||
                    poOrderItemsParam.getPkUnit() == null ||
                    poOrderItemsParam.getNnum() == null || poOrderItemsParam.getNorigprice() == null ||
                    CollectionUtil.isEmpty(poOrderItemsParam.getScmItemSpecsList())) {
                return Boolean.TRUE;
            }
            // 验证产品id 仓库id
            storehouseIdSet.add(poOrderItemsParam.getPkStorehouse());
            if (poOrderItemsParam.getNtaxrate() == null) {
                poOrderItemsParam.setNtaxrate(BigDecimal.ZERO);
            }
            if (poOrderItemsParam.getIsGift() == null) {
                poOrderItemsParam.setIsGift(EYesNo.NO.getIntValue());
            }
        }
        return Boolean.FALSE;
    }

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

}
