/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.springblade.business.entity.FixedFlow;
import org.springblade.business.entity.FixedFlowLink;
import org.springblade.business.service.IFixedFlowLinkService;
import org.springblade.business.vo.FixedFlowVO;
import org.springblade.business.mapper.FixedFlowMapper;
import org.springblade.business.service.IFixedFlowService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2022-07-01
 */
@Service
@AllArgsConstructor
public class FixedFlowServiceImpl extends BaseServiceImpl<FixedFlowMapper, FixedFlow> implements IFixedFlowService {

	private final IFixedFlowLinkService fixedFlowLinkService;

	@Override
	public IPage<FixedFlowVO> selectFixedFlowPage(FixedFlowVO vo) {
		IPage<FixedFlowVO> iPage = Condition.getPage(vo.getQuery(vo.getCurrent(), vo.getSize()));
		long current = (vo.getCurrent() - 1) * vo.getSize();
		//统计
		Integer count = this.baseMapper.countFixedFlow(vo);
		//查询分页数据
		List<FixedFlow> result = this.baseMapper.selectFixedFlowPage(current, vo.getSize(), vo);
		List<FixedFlowVO> resultVO = JSONArray.parseArray(JSONObject.toJSONString(result), FixedFlowVO.class);
		//查询环节信息
		resultVO.forEach(vos -> {
			List<FixedFlowLink> links = this.fixedFlowLinkService.selectFixedFlowLink(vos.getId().toString());
			if(links != null && links.size() > 0){
				//拼接环节
				StringBuilder linkJoin = new StringBuilder();
				links.forEach(link -> linkJoin.append(",").append(link.getFixedFlowLinkUserName()));
				//去掉第一个逗号
				vos.setLinkUserJoinString(linkJoin.toString().substring(1));
			}
		});
		//设置总数
		iPage.setTotal(count);

		return iPage.setRecords(resultVO);
	}

}
