package com.fjhx.service.flow;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fjhx.base.Condition;
import com.fjhx.base.StorageBaseEntity;
import com.fjhx.entity.quality.QualityTesting;
import com.fjhx.params.JumpVo;
import com.fjhx.service.contract.ContractService;
import com.fjhx.service.quality.QualityTestingService;
import com.fjhx.utils.ExampleAbstract;
import com.fjhx.utils.FlowConstructor;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;

/**
 * 质检数量修正
 */
@Service
public class CheckQuantityCorrectFlowService {

    @Autowired
    private ContractService contractService;

    @Autowired
    private QualityTestingService qualityTestingService;

    private final FlowConstructor flowConstructor = FlowConstructor.init(new ExampleAbstract() {

        @Override
        public String getCode() {
            return "js_checkQuantityCorrect";
        }

        @Override
        public void end() {
            contractService.updateAdjustByQualityTestingId(getCacheData(Long.class));
        }

    });

    @Transactional(rollbackFor = Exception.class)
    public void create(Long qualityTestingId) {
        String title = Objects.requireNonNull(AuthUtil.getUser()).getUserName() + "的质检数量修正申请";
        flowConstructor.create(qualityTestingId, title, null, qualityTestingId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void jump(Condition condition) {
        JumpVo jumpVo = BeanUtil.toBean(condition, JumpVo.class);

        // 更新修正⽐例
        BigDecimal adjustRate = condition.getBigDecimal("adjustRate");
        if (adjustRate != null) {
            Long flowLinkNo = jumpVo.getFlowLinkNo();

            qualityTestingService.update(Wrappers.<QualityTesting>lambdaUpdate()
                    .eq(StorageBaseEntity::getId, flowLinkNo)
                    .set(QualityTesting::getAdjustRate, adjustRate)
                    .set(StorageBaseEntity::getUpdateTime, new Date())
                    .set(StorageBaseEntity::getUpdateUser, AuthUtil.getUserId())
            );
        }

        flowConstructor.jump(jumpVo);
    }

}
