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

import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.Team;
import cn.wise.sc.cement.business.entity.TeamGroup;
import cn.wise.sc.cement.business.exception.BusinessExceptionEnum;
import cn.wise.sc.cement.business.mapper.TeamMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.TeamQuery;
import cn.wise.sc.cement.business.model.vo.ClientVo;
import cn.wise.sc.cement.business.model.vo.TeamListVo;
import cn.wise.sc.cement.business.model.vo.TeamVo;
import cn.wise.sc.cement.business.service.ITeamService;
import cn.wise.sc.cement.business.util.ExcelUtil;
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 io.swagger.models.auth.In;
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;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-18
 */
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements ITeamService {

	@Resource
	private TeamMapper teamMapper;

	/**
	 * 分页查询
	 *
	 * @param pageQuery
	 * @param status
	 * @param groupName
	 * @param name
	 * @return
	 */
	@Override
	public BaseResponse<IPage<TeamVo>> getPage(PageQuery pageQuery, Integer status, String groupName, String name,
												Integer qualifications) {
		Map<String, Object> params = new HashMap<>();
		params.put("status", status);
		params.put("groupName", groupName);
		params.put("name", name);
		params.put("qualifications", qualifications);
		Page<TeamVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<TeamVo> pages = teamMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 新增检测项
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<Team> create(TeamQuery query) {
		Team create = new Team();
		if (query.getGroupId() == null) {
			return BaseResponse.errorMsg("请选择检测组");
		}
		if (query.getMethodId() == null) {
			return BaseResponse.errorMsg("请选择检依据");
		}
		if (query.getIsDisplay() == null) {
			return BaseResponse.errorMsg("请选择委托是否可见");
		}
		if (query.getIsDisplay() != 1 && query.getIsDisplay() != 0) {
			return BaseResponse.errorMsg("委托是否可见参数错误");
		}
		if (query.getHandleId() == null) {
			return BaseResponse.errorMsg("请选择处理项");
		}

		QueryWrapper<Team> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = teamMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		BeanUtils.copyProperties(query, create);
		//no_check 标识校核计算的时候不显示计算的结果，因为没有公式
		create.setStatus(1).setCreateTime(LocalDateTime.now()).setRemark("no_check");
		teamMapper.insert(create);
		return BaseResponse.okData(create);
	}

	/**
	 * 修改检测项
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<Team> update(TeamQuery query) {
		Team update = teamMapper.selectById(query.getId());
		if (update == null) {
			return BaseResponse.errorMsg("信息错误");
		}
		if (query.getGroupId() == null) {
			return BaseResponse.errorMsg("请选择检测组");
		}
		if (query.getMethodId() == null) {
			return BaseResponse.errorMsg("请选择检依据");
		}
		if (query.getHandleId() == null) {
			return BaseResponse.errorMsg("请选择处理项");
		}
		QueryWrapper<Team> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		qw.ne("id", query.getId());
		int count = teamMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		update.setGroupId(query.getGroupId())
				.setMethodId(query.getMethodId())
				.setCharge(query.getCharge())
				.setName(query.getName())
				.setIsDisplay(query.getIsDisplay())
				.setQualifications(query.getQualifications())
				.setHandleId(query.getHandleId());
		teamMapper.updateById(update);
		return BaseResponse.okData(update);
	}

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

	/**
	 * 检测项详情
	 *
	 * @param id
	 * @return
	 */
	public BaseResponse<TeamVo> getDetail(Integer id) {
		TeamVo teamVo = teamMapper.getDetail(id);
		if (teamVo == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		return BaseResponse.okData(teamVo);
	}

	/**
	 * 检测项列表
	 *
	 * @return
	 */
	@Override
	public BaseResponse<List<TeamListVo>> getList() {
		List<TeamListVo> list = teamMapper.getList();
		return BaseResponse.okData(list);
	}

	@Override
	public void export(Integer status, Integer gourpId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("status", status);
		params.put("gourpId", gourpId);
		params.put("name", name);
		List<Map<String, Object>> list = teamMapper.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] = "检测依据";
			headers[4] = "收费标准";
			headers[5] = "建议产值";
			headers[6] = "资质范围";
			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);
		}
	}

	/**
	 * 根据检测组id获取检测项信息
	 *
	 * @param id
	 * @return
	 */
	@Override
	public BaseResponse<List<String>> getByGroup(Integer id) {
		List<String> map = teamMapper.getByGroup(id);
		return BaseResponse.okData(map);
	}

}
