package org.springblade.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springblade.business.entity.InformationQuery;
import org.springblade.business.vo.FileUserVO;
import org.springblade.business.vo.InformationQueryVO;
import org.springblade.business.mapper.InformationQueryMapper;
import org.springblade.business.service.IInformationQueryService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.manager.entity.WbsTreeContract;
import org.springblade.manager.feign.WbsTreeContractClient;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2022-06-08
 */
@Service
@AllArgsConstructor
public class InformationQueryServiceImpl extends BaseServiceImpl<InformationQueryMapper, InformationQuery> implements IInformationQueryService {

	private final WbsTreeContractClient wbsTreeContractClient;

	@Override
	public void saveOrUpdateInformationQueryData(BladeUser user, Long primaryKeyId, String fileName, Integer classify, Integer sourceType, Long dataId) {
		//判断当前填报节点下是否已经存在相应数据
		InformationQuery oldData = this.baseMapper.getInformationQueryByWbsId(primaryKeyId, classify);

		if(oldData != null){
			//存在记录，修改
			if(StringUtils.isNotEmpty(fileName)){
				oldData.setName(fileName);
			}

			//拼接填报人信息
			String fileUser = user.getUserId() + "-" + user.getUserName();
			if(StringUtils.isNotEmpty(oldData.getFileUserIdAndName())){
				if(!oldData.getFileUserIdAndName().contains(fileUser)){
					//不包含，拼接
					oldData.setFileUserIdAndName(oldData.getFileUserIdAndName() + "," + fileUser);
				}
			} else {
				oldData.setFileUserIdAndName(fileUser);
			}

			oldData.setUpdateTime(new Date());
			oldData.setUpdateUser(user.getUserId());
			//修改数据
			this.baseMapper.updateById(oldData);
		} else {
			//首先根据wbsId获取合同段ID和项目ID
			WbsTreeContract contractTree = this.wbsTreeContractClient.getContractWbsTreeByPrimaryKeyId(primaryKeyId);
			//新增基础数据
			InformationQuery newData = new InformationQuery();
			//设置文件题名
			newData.setName(fileName);
			//设置文件类型
			newData.setCategory(contractTree.getDeptCategory());
			//项目ID
			newData.setProjectId(Long.parseLong(contractTree.getProjectId()));
			//合同段ID
			newData.setContractId(Long.parseLong(contractTree.getContractId()));
			//施工资料还是质检资料
			newData.setClassify(classify);
			//节点ID
			newData.setWbsId(primaryKeyId);
			//是否是试验节点
			newData.setIsExperiment(contractTree.getIsExpernode());
			//数据ID
			newData.setDataId(dataId);
			//流程状态，默认未上报
			newData.setTaskStatus(0);
			//填报人ID及姓名
			newData.setFileUserIdAndName(user.getUserId() + "-" + user.getUserName());
			//数据源类型
			newData.setSourceType(sourceType);
			newData.setCreateUser(user.getUserId());
			newData.setCreateDept(user.getDeptId().contains(",") ? Long.parseLong(user.getDeptId().split(",")[0]) : Long.parseLong(user.getDeptId()));
			newData.setCreateTime(new Date());
			//保存数据
			this.baseMapper.insert(newData);
		}

	}

	@Override
	public List<Integer> getReportNumberByContractId(Integer classify, String contractId) {
		return this.baseMapper.getReportNumberByContractId(classify, contractId);
	}

	@Override
	public List<FileUserVO> queryFileUserByContractId(Integer classify, String contractId) {
		//获取当前合同段下有填报记录的填报人
		List<InformationQuery> fileUserResult = this.baseMapper.queryFileUserByContractId(classify, contractId);

		//获取填报人数据
		List<String> userList = new ArrayList<>();
		fileUserResult.forEach(user -> userList.add(user.getFileUserIdAndName()));
		//去重
		HashSet<String> hashSet = new HashSet<>(userList);
		//将原本拼接的字符串拆分为userId和userName
		List<FileUserVO> result = new ArrayList<>();
		hashSet.forEach(user -> {
			String[] array = user.split("-");
			result.add(new FileUserVO(array[0], array[1]));
		});

		return result;
	}

	@Override
	public IPage<InformationQueryVO> selectInformationQueryPage(IPage<InformationQueryVO> page, InformationQueryVO vo) {
		long current = (page.getCurrent() - 1L) * page.getSize();
		//获取总量
		Integer count = this.baseMapper.countInformationQuery(vo);
		//多节点查询
		if(vo.getWbsId() != null){
			vo.setWbsIds(JSONArray.parseArray(JSONObject.toJSONString(String.valueOf(vo.getWbsId()).split(",")), String.class));
		}

		if(StringUtils.isNotEmpty(vo.getBetweenTime())){
			String[] betweenTime;
			if(vo.getBetweenTime().contains("~")){
				String[] between = vo.getBetweenTime().split("~");
				betweenTime = new String[]{between[0], between[1]};
			} else {
				betweenTime = new String[]{vo.getBetweenTime(), DateUtils.formatDate(new Date(), "yyyy-MM-dd")};
			}
			vo.setStartTime(betweenTime[0]);
			vo.setEndTime(betweenTime[1]);
		}

		//获取数据
		List<InformationQuery> result = this.baseMapper.selectInformationQueryPage(current, page.getSize(), vo);
		//转换VO
		if(result != null && result.size() != 0){
			List<InformationQueryVO> voResult = JSONArray.parseArray(JSONObject.toJSONString(result), InformationQueryVO.class);
			//处理流程状态
			voResult.forEach(vor -> vor.setTaskStatusStr(new Integer("1").equals(vor.getTaskStatus()) ? "未上报" : new Integer("2").equals(vor.getTaskStatus()) ? "待审批" : "已审批"));

			page.setRecords(voResult);
			page.setTotal(count);

			return page;
		}

		return page.setRecords(null);
	}

}
