package com.hzs.scm.io.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.TransactionUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.scm.io.ext.IoOrderExt;
import com.hzs.common.domain.scm.io.ext.IoOrderItemsExt;
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.scm.io.param.IoOrderItemsParam;
import com.hzs.scm.io.param.IoOrderParam;
import com.hzs.scm.io.service.IIoOrderItemsService;
import com.hzs.scm.io.service.IIoOrderService;
import com.hzs.scm.io.vo.IoOrderBVo;
import com.hzs.scm.io.vo.IoOrderVo;
import com.hzs.scm.pub.controller.ScmController;
import com.hzs.scm.pub.param.ScmApproveParam;
import com.hzs.scm.pub.service.IScmOrderApproveLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 业务领用订单表头 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2024-04-22
 */
@RestController
@RequestMapping("/manage/io")
public class IoOrderController extends ScmController {

    @Autowired
    private IIoOrderService orderService;

    @Autowired
    private IIoOrderItemsService orderItemsService;

    @Autowired
    private IScmOrderApproveLogService scmOrderApproveLogService;

    @Autowired
    private UserTokenService userTokenService;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.IO_ORDER, business = EOperationBusiness.IO_ORDER, method = EOperationMethod.SELECT)
    public TableDataInfo listIoOrder(@RequestBody IoOrderParam ioOrderParam) {
        startPage();
        ioOrderParam.setPkCountry(SecurityUtils.getPkCountry());
        List<IoOrderExt> ioOrderExtList = orderService.queryIoOrderByCondition(ioOrderParam);
        List<IoOrderVo> orderVoList = packageScmReturnVo(ioOrderExtList);
        return packageTableDataInfo(ioOrderExtList, orderVoList);
    }

    private List<IoOrderVo> packageScmReturnVo(List<IoOrderExt> orderExtList) {
        List<IoOrderVo> ioOrderVoList = new ArrayList<>();
        for (IoOrderExt ioOrderExt : orderExtList) {
            IoOrderVo ioOrderVo = BeanUtil.copyProperties(ioOrderExt, IoOrderVo.class);
            List<IoOrderItemsExt> orderItemsExtList = ioOrderExt.getOrderItemsExtList();
            if (CollectionUtil.isNotEmpty(orderItemsExtList)) {
                List<IoOrderBVo> returnbVoList = BeanUtil.copyToList(orderItemsExtList, IoOrderBVo.class);
                ioOrderVo.setScmReturnbVoList(returnbVoList);
            }
            ioOrderVoList.add(ioOrderVo);
        }
        return ioOrderVoList;
    }

    /**
     * 查询订单的明细
     *
     * @return cubasdocParam 入参
     */
    @GetMapping("/list-detail/{pkId}")
    public TableDataInfo queryToIoOrderItems(@PathVariable Long pkId) {
        List<IoOrderItemsExt> orderItemsExtList = orderItemsService.queryListIoOrderItemsByPk(SecurityUtils.getPkCountry(), pkId);
        List<IoOrderBVo> scmReturnVoList = new ArrayList<>();
        for (IoOrderItemsExt orderItemsExt : orderItemsExtList) {
            scmReturnVoList.add(BeanUtil.copyProperties(orderItemsExt, IoOrderBVo.class));
        }
        return packageTableDataInfo(orderItemsExtList, scmReturnVoList);
    }


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

    /**
     * 修改采购入库
     *
     * @param ioOrderParam 入参
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.IO_ORDER, business = EOperationBusiness.IO_ORDER, method = EOperationMethod.UPDATE)
    public AjaxResult updateIoOrder(@RequestBody IoOrderParam ioOrderParam) {
        if (ioOrderParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent((MemberMsgConstants.REQUIRED_NOT_EMPTY)));
        }
        int pkCountry = SecurityUtils.getPkCountry();
        // 验证订单状态 只有保存状态的采购订单可以进行修改
        IoOrderExt ioOrderExt = orderService.queryIoOrderById(ioOrderParam.getPkId(), EScmOrderStatus.SAVE.getValue());
        if (ioOrderExt == null) {
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.IO_ORDER_NOT_EXIST));
        }
        String msg = validateIoOrderMsg(ioOrderParam, pkCountry);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(TransactionUtils.getContent(msg));
        }
        // 计算价税合计、总数量
        ioOrderParam.setPkCountry(pkCountry);
        orderService.updateIoOrderByOrderParam(ioOrderExt, ioOrderParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

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

    private Boolean validateIoOrderParam(IoOrderParam ioOrderParam, Set<Integer> storehouseIdSet) {
        // 验证 供应商、采购组织不能为空
        if (ioOrderParam.getPkPurpose() == null ||
                ioOrderParam.getPkCorp() == null || CollectionUtil.isEmpty(ioOrderParam.getOrderItemsParamList())) {
            return Boolean.TRUE;
        }
        // 验证 采购订单明细字段不能为空
        for (IoOrderItemsParam orderItemsParam : ioOrderParam.getOrderItemsParamList()) {
            if (orderItemsParam.getPkProductBas() == null || orderItemsParam.getPkUnit() == null || orderItemsParam.getNnum() == null ||
                    CollectionUtil.isEmpty(orderItemsParam.getScmItemSpecsList())) {
                return Boolean.TRUE;
            }
            // 验证产品id 仓库id
            if (orderItemsParam.getPkStorehouse() != null) {
                storehouseIdSet.add(orderItemsParam.getPkStorehouse());
            }
        }
        return Boolean.FALSE;
    }

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