package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.Client;
import cn.wise.sc.cement.business.entity.Project;
import cn.wise.sc.cement.business.exception.BusinessExceptionEnum;
import cn.wise.sc.cement.business.mapper.ClientMapper;
import cn.wise.sc.cement.business.mapper.ProjectMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.ProjectQuery;
import cn.wise.sc.cement.business.model.vo.ClientVo;
import cn.wise.sc.cement.business.model.vo.ProjectVo;
import cn.wise.sc.cement.business.service.IClientService;
import cn.wise.sc.cement.business.service.IProjectService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.wrapper.page.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-07
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

	@Resource
	private ProjectMapper projectMapper;
	@Resource
	private ClientMapper clientMapper;

	@Override
	public BaseResponse<IPage<ProjectVo>> getPage(PageQuery pageQuery, String code, Integer clientId, String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("code", code);
		params.put("clientId", clientId);
		params.put("name", name);
		Page<ProjectVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<ProjectVo> pages = projectMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	@Override
	public BaseResponse<List<ProjectVo>> getList() {
		List<ProjectVo> list = projectMapper.getList();
		return BaseResponse.okData(list);
	}

	@Override
	public BaseResponse<List<ProjectVo>> getProjectList(Integer clientId) {
		List<ProjectVo> list = projectMapper.getProjectList(clientId);
		return BaseResponse.okData(list);
	}

	@Override
	@Transactional
	public BaseResponse<Project> create(ProjectQuery query) {
		QueryWrapper<Project> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = projectMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg("项目名称已存在!");
		}
		Project create = new Project();
		BeanUtils.copyProperties(query, create);
		create.setStatus(1)
				.setCreateTime(LocalDateTime.now())
				.setRemark(null);
		projectMapper.insert(create);
		return BaseResponse.okData(create);
	}

	@Override
	@Transactional
	public BaseResponse<Project> update(ProjectQuery query) {
		//判断名字是否重复
		QueryWrapper<Project> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		qw.ne("id", query.getId());
		int count = projectMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg("项目名称已存在!");
		}
		Project update = new Project();
		BeanUtils.copyProperties(query, update);
		update.setId(query.getId());
		projectMapper.updateById(update);
		return BaseResponse.okData(update);
	}

	@Override
	@Transactional
	public BaseResponse<String> status(Integer status, Integer id) {
		if (status == null || id == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		Project project = projectMapper.selectById(id);
		if (project == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		project.setStatus(status);
		projectMapper.updateById(project);
		String result = "";
		if (project.getStatus() == 1) {
			result = "已启用";
		} else {
			result = "已禁用";
		}
		return BaseResponse.okData(result);
	}

	/**
	 * 根据项目名称返回项目信息
	 *
	 * @param name
	 * @return
	 */
	public BaseResponse<ProjectVo> getByName(String name) {
		ProjectVo projectVo = projectMapper.getByName(name);
		if (projectVo == null) {
			return BaseResponse.errorMsg("系统暂无本项目，需要创建");
		}
		return BaseResponse.okData(projectVo);
	}

	@Override
	public void export(String code, Integer clientId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("code", code);
		params.put("clientId", clientId);
		params.put("name", name);
		List<Map<String, Object>> list = projectMapper.exportList(params);

		if (!CollectionUtils.isEmpty(list)) {
			Map<String, Object> map = list.get(0);
			String[] headers = new String[map.size()];
			headers[0] = "序号";
			headers[1] = "项目名称";
			headers[2] = "项目编号";
			headers[3] = "所属单位";

			List<Object[]> datas = new ArrayList<>(list.size());
			for (Map<String, Object> m : list) {
				Object[] objects = new Object[headers.length];
				for (int j = 0; j < headers.length; j++) {
					String obj = m.get(headers[j]).toString();
					if (j == 0) {
						obj = obj.split("\\.")[0];
					}
					objects[j] = obj;
				}
				datas.add(objects);
			}
			ExcelUtil.excelExport(
					fileName == null || fileName.trim().length() <= 0 ? "项目" : fileName, headers,
					datas, response);
		}
	}

}
