package com.cool.bang.modules.approval.service.impl;

import com.cool.bang.common.base.BaseServiceImpl;
import com.cool.bang.common.constant.enums.StatusType;
import com.cool.bang.common.tools.number.IncrUtil;
import com.cool.bang.modules.approval.domain.po.ApprovalFlow;
import com.cool.bang.modules.approval.domain.po.ApprovalNode;
import com.cool.bang.modules.approval.mapper.ApprovalFlowMapper;
import com.cool.bang.modules.approval.mapper.ApprovalNodeMapper;
import com.cool.bang.modules.approval.service.IApprovalFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * 审批流程
 *
 * @author PeiZhi Guo
 * 2022-8-1 16:51
 */
@Service
public class ApprovalFlowServiceImpl extends BaseServiceImpl<ApprovalFlowMapper, ApprovalFlow> implements IApprovalFlowService {

    @Autowired
    protected ApprovalNodeMapper approvalNodeMapper;


    @Override
    public ApprovalFlow queryByFlowType(Integer type){
        return baseMapper.queryByFlowType(type);
    }


    @Transactional
    @Override
    public boolean save(ApprovalFlow approvalFlow) {
        // 初始化
        approvalFlow.insertConfigure();
        approvalFlow.setState(StatusType.DISABLE.ordinal());
        approvalFlow.setFlowNumber(IncrUtil.flowNumber());
        approvalFlow.setDelFlag(1);
        if ( super.save(approvalFlow)) {
            ApprovalFlow approvalFlow1 = baseMapper.queryByNumber(approvalFlow.getFlowNumber());
            ApprovalNode approvalNode = new ApprovalNode();
            // 生成一个两位的随机数
            Random random = new Random();
            // 将时间戳转换为字符串
            String timestampStr = Long.toString(System.currentTimeMillis());
            // 获取时间戳的前几位（去掉最后两位）
            String prefix = timestampStr.substring(0, timestampStr.length() - 2);
            // 拼接新的时间戳
            long outTradeNo = Long.parseLong(prefix + random.nextInt(100));
            approvalNode.setId(outTradeNo);
            approvalNode.setFlowId(approvalFlow1.getId());
            approvalNode.setNodeType(1);
            approvalNode.setNodeName("开始节点");
            approvalNode.setUserId(approvalFlow.getCreateBy());
            approvalNode.setUserName(approvalFlow.getCreateName());
            approvalNode.setDelFlag(1);
            approvalNode.setNumber(1);
            approvalNode.setRemark("开始节点");
            return approvalNodeMapper.insert(approvalNode)>0;
        }
        return false;
    }

    @Override
    public boolean updateState(Integer state, Long id) {
        ApprovalFlow flow = baseMapper.selectById(id);
        if (state == StatusType.ENABLE.ordinal()) {
            int count = baseMapper.selectByExclude(flow.getFlowType());
            if (count > 0) {
                return false;
            }
        }
        flow.setState(state);
        return baseMapper.update(flow) > 0;
    }
}
