package com.hzs.scm.pub.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.SaOrderFieldConstants;
import com.hzs.common.core.constant.ScmFieldConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.domain.scm.pub.ScmOrderApproveLog;
import com.hzs.common.domain.scm.purchase.IcPurchaseInH;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.scm.pub.mapper.ScmOrderApproveLogMapper;
import com.hzs.scm.pub.param.ScmApproveParam;
import com.hzs.scm.pub.service.IScmOrderApproveLogService;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 供应链单据审批记录 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2023-11-24
 */
@Service
public class ScmOrderApproveLogServiceImpl extends ServiceImpl<ScmOrderApproveLogMapper, ScmOrderApproveLog> implements IScmOrderApproveLogService {

    @DubboReference
    private IApprovalServiceApi iApprovalServiceApi;

    @Override
    public void submitOrder(ScmApproveParam scmApproveParam, EApprovalBusiness approvalBusiness, EOrderPrefix orderPrefix, LoginUser loginUser) {
        // 本批订单修改记录编号
        String businessCode = CommonUtil.createSerialNumber(orderPrefix);
        ScmOrderApproveLog scmOrderApproveLog = packageScmOrderApproveLog(loginUser.getUserId(),
                approvalBusiness.getValue(), businessCode, scmApproveParam, EAgentApprovalStatus.UNAPPROVED.getValue());
        if (save(scmOrderApproveLog)) {
            R<String> resultR = iApprovalServiceApi.submitOrder(
                    ApprovalSubmitDTO.builder()
                            .eApprovalBusiness(approvalBusiness)
                            .businessCode(businessCode)
                            .signType(ESignType.getEnumByValue(scmApproveParam.getSignType()))
                            .userIdList(scmApproveParam.getUserIdList())
                            .sendIdList(scmApproveParam.getSendIdList())
                            .remark(scmApproveParam.getRemark())
                            .fileList(scmApproveParam.getFileList())
                            .signSource(ESignSource.MANAGE)
                            .build(),
                    loginUser,
                    null
            );
            if (resultR.isSuccess()) {
                return;
            }
            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + "：" + resultR.getMsg());
        }
    }

    @Override
    public List<ScmOrderApproveLog> queryScmOrderApproveLogByCondition(Long pkId, Integer auditType, String businessCode) {
        QueryWrapper<ScmOrderApproveLog> queryWrapper = new QueryWrapper<>();
        if(pkId != null) {
            queryWrapper.eq(SaOrderFieldConstants.PK_ORDER, pkId);
        }
        if(ObjectUtil.isNotEmpty(businessCode)){
            queryWrapper.eq(ScmFieldConstants.BUSINESS_CODE, businessCode);
        }
        queryWrapper.eq(SaOrderFieldConstants.ORDER_TYPE, auditType);
        queryWrapper.eq(ScmFieldConstants.APPROVAL_STATUS, EAgentApprovalStatus.UNAPPROVED.getValue());
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void updateScmOrderApproveStatus(Long pkId, Long pkMember, Integer approvalStatus) {
        UpdateWrapper<ScmOrderApproveLog> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(ScmFieldConstants.APPROVAL_STATUS, approvalStatus);
        updateWrapper.set(SystemFieldConstants.PK_MODIFIED, pkMember);
        updateWrapper.set(SystemFieldConstants.MODIFIED_TIME, DateUtils.currentDateTime());
        updateWrapper.eq(SystemFieldConstants.PK_ID, pkId);
        update(updateWrapper);
    }

    /**
     * 封装订单修改记录
     *
     * @param userId         用户ID
     * @param orderType     修改类型
     * @param businessCode   修改记录单号
     * @param billVo        订单
     * @param approvalStatus 审核状态
     * @return ScmOrderApproveLog
     */
    private ScmOrderApproveLog packageScmOrderApproveLog(Long userId, Integer orderType, String businessCode,
                                                         Object billVo, Integer approvalStatus) {
        ScmOrderApproveLog scmOrderApproveLog = new ScmOrderApproveLog();
        scmOrderApproveLog.setPkOrder(ReflectUtils.invokeGetter(billVo, SystemFieldConstants.PK_ID_VALUE));
        scmOrderApproveLog.setOrderType(orderType);
        scmOrderApproveLog.setPkCreator(userId);
        scmOrderApproveLog.setCreationTime(DateUtils.currentDateTime());
        scmOrderApproveLog.setPkModified(scmOrderApproveLog.getPkCreator());
        scmOrderApproveLog.setModifiedTime(scmOrderApproveLog.getCreationTime());
        scmOrderApproveLog.setPkCountry(ReflectUtils.invokeGetter(billVo, SystemFieldConstants.PK_COUNTRY_VALUE));
        scmOrderApproveLog.setApprovalStatus(approvalStatus);
        scmOrderApproveLog.setBusinessCode(businessCode);
        return scmOrderApproveLog;
    }
}
