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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.PlanEquipmentMaintain;
import cn.wise.sc.cement.business.entity.PlanEquipmentPurchase;
import cn.wise.sc.cement.business.enumation.FileExt;
import cn.wise.sc.cement.business.mapper.PlanEquipmentMaintainMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.PlanEquipmentMaintainQuery;
import cn.wise.sc.cement.business.model.query.PlanEquipmentPurchaseQuery;
import cn.wise.sc.cement.business.model.query.PlanFinishQuery;
import cn.wise.sc.cement.business.model.vo.PlanEquipmentMaintainVo;
import cn.wise.sc.cement.business.model.vo.PlanEquipmentPurchaseVo;
import cn.wise.sc.cement.business.service.IPlanEquipmentMaintainService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.util.WordUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
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.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-09-28
 */
@Service
public class PlanEquipmentMaintainServiceImpl extends ServiceImpl<PlanEquipmentMaintainMapper, PlanEquipmentMaintain> implements IPlanEquipmentMaintainService {

	@Resource
	private PlanEquipmentMaintainMapper equipmentMaintainMapper;
	@Autowired
	private ISysUserService userService;

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

	/**
	 * 设备维护计划列表导出
	 *
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void export(String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		List<Map<String, Object>> list = equipmentMaintainMapper.exportList(params);

		if (!com.baomidou.mybatisplus.core.toolkit.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] = "执行人";
			headers[7] = "完成情况";

			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);
		}
	}

	/**
	 * 创建
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<PlanEquipmentMaintain> create(PlanEquipmentMaintainQuery query) {
		LoginUser loginUser = userService.getLoginUser();
		if (loginUser == null) {
			return BaseResponse.errorMsg("请登录用户");
		}
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("产品名称不能为空!");
		}
		QueryWrapper<PlanEquipmentMaintain> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = equipmentMaintainMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		PlanEquipmentMaintain pep = new PlanEquipmentMaintain();
		BeanUtils.copyProperties(query, pep);
		pep.setUserId(loginUser.getId())
				.setStatus(0)
				.setCreateTime(LocalDateTime.now());
		equipmentMaintainMapper.insert(pep);
		return BaseResponse.okData(pep);
	}

	/**
	 * 修改
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<PlanEquipmentMaintain> update(PlanEquipmentMaintainQuery query) {
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("产品名称不能为空!");
		}
		QueryWrapper<PlanEquipmentMaintain> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		qw.ne("id", query.getId());
		int count = equipmentMaintainMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		PlanEquipmentMaintain pep = equipmentMaintainMapper.selectById(query.getId());
		BeanUtils.copyProperties(query, pep);
		equipmentMaintainMapper.updateById(pep);
		return BaseResponse.okData(pep);
	}

	/**
	 * 获取详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public BaseResponse<PlanEquipmentMaintainVo> getDetail(Integer id) {
		if (id == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		PlanEquipmentMaintain pep = equipmentMaintainMapper.selectById(id);
		if (pep == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		PlanEquipmentMaintainVo planEquipmentMaintainVo = equipmentMaintainMapper.getDetail(id);
		return BaseResponse.okData(planEquipmentMaintainVo);
	}

	/**
	 * 维护完成
	 *
	 * @param query
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> finish(PlanFinishQuery query) {
		if (query == null || query.getId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		PlanEquipmentMaintain pep = equipmentMaintainMapper.selectById(query.getId());
		if (pep == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		pep.setImplementation(query.getImplementation());
		pep.setStatus(1); //维护完成
		equipmentMaintainMapper.updateById(pep);
		return BaseResponse.okData("维护完成");
	}

	/**
	 * 删除
	 *
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> delete(Integer id) {
		PlanEquipmentMaintain pep = equipmentMaintainMapper.selectById(id);
		if (pep == null) {
			return BaseResponse.errorMsg("数据错误!");
		}
		equipmentMaintainMapper.deleteById(id);
		return BaseResponse.okData("删除成功");
	}

	/**
	 * 设备维护计划列表导出(word)
	 * @param name
	 * @param fileName
	 * @param response
	 */
	public void exportWord(String name, String fileName,HttpServletResponse response) {

		Date start = DateUtil.beginOfYear(DateUtil.date());
		Date end = DateUtil.endOfYear(DateUtil.date());
		Map<String, Object> map = new HashMap<>(3);
		map.put("start", start);
		map.put("end", end);
		map.put("name", name);
		List<PlanEquipmentMaintainVo> list = equipmentMaintainMapper.exportWordList(map);

		if (CollectionUtil.isEmpty(list)) {
			log.debug("设备维护计划为空!");
			return;
		}

//		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		list.forEach(arg -> {
			if (StrUtil.isEmpty(arg.getRemark())) {
				arg.setRemark("");
			}
			if (StrUtil.isEmpty(arg.getImplementation())) {
				arg.setImplementation("");
			}
//			arg.setCreateTimeStr(arg.getCreateTime().format(dateTimeFormatter));
		});
		Map<String, Object> params = new HashMap<>(5);
		params.put("list", list);
		params.put("fileNo", "41-4051-2001");
		params.put("year", DateUtil.year(DateUtil.date()));

		WordUtil.writeWordReport(fileName, "设备维护计划.ftl", params, response, FileExt.DOC);

	}
}
