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


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.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.scm.ic.IcBatchCode;
import com.hzs.common.domain.scm.ic.ext.IcBatchCodeExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.sale.product.IProductServiceApi;
import com.hzs.sale.product.dto.ProductDTO;
import com.hzs.scm.ic.param.BatchCodeParam;
import com.hzs.scm.ic.service.IIcBatchCodeService;
import com.hzs.scm.pub.controller.ScmController;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 批次号 前端控制器
 * </p>
 *
 * @author hzs
 * @since 2023-11-23
 */
@RestController
@RequestMapping("/manage/batch-code")
public class IcBatchCodeController extends ScmController {

    @Autowired
    private IIcBatchCodeService batchCodeService;

    @DubboReference
    private IProductServiceApi productServiceApi;

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/list")
    @Log(module = EOperationModule.BATCH_CODE, business = EOperationBusiness.BATCH_CODE, method = EOperationMethod.SELECT)
    public TableDataInfo listBatchCode(@RequestBody BatchCodeParam batchCodeParam) {
        startPage();
        batchCodeParam.setPkCountry(SecurityUtils.getPkCountry());
        List<IcBatchCodeExt> batchCodeList = batchCodeService.queryBatchCodeByCondition(batchCodeParam);
        return getDataTable(batchCodeList);
    }

    /**
     * 查询列表
     *
     * @return cubasdocParam 入参
     */
    @PostMapping("/refer")
    @Log(module = EOperationModule.BATCH_CODE, business = EOperationBusiness.BATCH_CODE, method = EOperationMethod.SELECT)
    public TableDataInfo referBatchCode(@RequestBody BatchCodeParam batchCodeParam) {
        if(batchCodeParam.getPkProduct() == null && batchCodeParam.getBatchCode() == null){
            return getDataTable(new ArrayList<>());
        }
        batchCodeParam.setPkCountry(SecurityUtils.getPkCountry());
        List<IcBatchCodeExt> batchCodeList = batchCodeService.queryBatchCodeByCondition(batchCodeParam);
        return getDataTable(batchCodeList);
    }

    /**
     * 新增采购入库
     *
     * @param batchCodeParam 批次号
     */
    @PostMapping("/insert")
    @Log(module = EOperationModule.BATCH_CODE, business = EOperationBusiness.BATCH_CODE, method = EOperationMethod.INSERT)
    public AjaxResult savePoOrder(@RequestBody BatchCodeParam batchCodeParam) {
        batchCodeParam.setPkCountry(SecurityUtils.getPkCountry());
        String msg = validateBatchCodeMsg(batchCodeParam);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(TransactionUtils.getContent(msg));
        }
        batchCodeService.insertBatchCode(batchCodeParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /*
     * @description: 验证订单相关信息
     * @author: sui q
     * @date: 2023/11/21 11:43
     * @param: null null
     **/
    private String validateBatchCodeMsg(BatchCodeParam batchCodeParam) {
        if (batchCodeParam.getPkProduct() == null || batchCodeParam.getBatchCode() == null ||
                batchCodeParam.getProductDate() == null|| batchCodeParam.getExpireDate() == null) {
            return MemberMsgConstants.REQUIRED_NOT_EMPTY;
        }
        // 验证产品，根据产品
        ProductDTO productDTO = productServiceApi.getProduct(batchCodeParam.getPkProduct()).getData();
        if(productDTO == null){
            return ScmMsgConstants.PRODUCT_NOT_EXIST;
        }
        // 验证批次号，批次号唯一
        List<IcBatchCodeExt> batchCodeList = batchCodeService.queryBatchCodeByCondition(batchCodeParam);
        if(CollectionUtil.isNotEmpty(batchCodeList)){
            if(batchCodeParam.getPkId() == null || !batchCodeParam.getPkId().equals(batchCodeList.get(0).getPkId())){
                return ScmMsgConstants.BATCH_CODE_HAS_EXIST;
            }
        }
        // 计算有效期
        long validPeriod = DateUtils.betweenSecond(batchCodeParam.getProductDate(), batchCodeParam.getExpireDate())/24/60/60;
        batchCodeParam.setValidPeriod((int) validPeriod);
        return null;
    }

    /**
     * 修改批次号
     *
     * @param  batchCodeParam 批次号
     */
    @PostMapping("/update")
    @Log(module = EOperationModule.BATCH_CODE, business = EOperationBusiness.BATCH_CODE, method = EOperationMethod.UPDATE)
    public AjaxResult updateAvailableNum(@RequestBody BatchCodeParam batchCodeParam) {
        if (batchCodeParam.getPkId() == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.REQUIRED_NOT_EMPTY));
        }
        IcBatchCode batchCode= batchCodeService.getById(batchCodeParam.getPkId());
        if(batchCode == null){
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.SELECT_BATCH_CODE_NOT_EXIST));
        }
        String msg = validateBatchCodeMsg(batchCodeParam);
        if (ObjectUtil.isNotEmpty(msg)) {
            return AjaxResult.error(msg);
        }
        batchCodeService.updateBatchCode(batchCode, batchCodeParam, SecurityUtils.getUserId());
        return AjaxResult.success();
    }

    /**
     * 删除批次号
     *
     * @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));
        }
        IcBatchCode batchCode= batchCodeService.getById(pkId);
        if(batchCode == null){
            return AjaxResult.error(TransactionUtils.getContent(ScmMsgConstants.SELECT_BATCH_CODE_NOT_EXIST));
        }
        batchCodeService.deleteBatchCode(pkId, SecurityUtils.getUserId());
        return AjaxResult.success();
    }
}
