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

import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.mapper.*;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.*;
import cn.wise.sc.cement.business.model.vo.*;
import cn.wise.sc.cement.business.service.IEquipmentService;
import cn.wise.sc.cement.business.service.ISysUserMessageService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.util.weixin.Global;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
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-09-01
 */
@Service
public class EquipmentServiceImpl extends ServiceImpl<EquipmentMapper, Equipment> implements IEquipmentService {

	@Resource
	private EquipmentMapper equipmentMapper;
	@Autowired
	private ISysUserService userService;
	@Resource
	private EquipmentTestMapper testMapper;
	@Autowired
	private CommonServiceImpl commonService;
	@Resource
	private EquipmentTroubleshootingMapper troubleshootingMapper;
	@Resource
	private EquipmentScrapMapper scrapMapper;
	@Resource
	private EquipmentUseMapper useMapper;
	@Resource
	private SysApprovalMapper sysApprovalMapper;
	@Autowired
	private ISysUserMessageService userMessageService;
	@Autowired
	private WeiXinService weiXinService;

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

	/**
	 * 设备列表导出
	 *
	 * @param brand
	 * @param supplierId
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void export(String brand, Integer supplierId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		List<Map<String, Object>> list = equipmentMapper.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] = "位置";
			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 brand
	 * @param supplierId
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void exportTest(String brand, Integer supplierId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		List<Map<String, Object>> list = equipmentMapper.exportTestList(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] = "校检日期";
			headers[7] = "期间核查日期";
			headers[8] = "实施结果";

			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
	 */
	@Override
	@Transactional
	public BaseResponse<Equipment> create(EquipmentQuery query) {
		if (StringUtils.isEmpty(query.getName())) {
			return BaseResponse.errorMsg("设备名称不能为空!");
		}
		QueryWrapper<Equipment> qw = new QueryWrapper<>();
		qw.eq("name", query.getName());
		int count = equipmentMapper.selectCount(qw);
		if (count > 0) {
			return BaseResponse.errorMsg(query.getName() + "已存在");
		}
		Equipment equipment = new Equipment();
		BeanUtils.copyProperties(query, equipment);
		equipment.setStatus(1).setCreateTime(LocalDateTime.now());
		equipmentMapper.insert(equipment);
		return BaseResponse.okData(equipment);
	}

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

	/**
	 * 获取设备详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public BaseResponse<EquipmentVo> getDetail(Integer id) {
		EquipmentVo equipmentVo = equipmentMapper.getDetail(id);
		if (equipmentVo == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		return BaseResponse.okData(equipmentVo);

	}

	/**
	 * 设备检定 保存设备检定表信息和附件表信息，附件表的entity_type为3
	 *
	 * @param query （不传id为添加记录，传id为修改记录）
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> test(EquipmentTestQuery query) {
		if (query == null || query.getEquipmentId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
//		EquipmentVo equipmentVo = equipmentMapper.getDetail(query.getEquipmentId());
		Equipment equipment = equipmentMapper.selectById(query.getEquipmentId());
		if (equipment == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		EnclosureQuery enclosureQuery = query.getEnclosureQuery();
		EquipmentTest equipmentTest = new EquipmentTest();
		BeanUtils.copyProperties(query, equipmentTest);
		equipmentTest.setUserId(userService.getLoginUser().getId())
				.setEnclosureUrl(enclosureQuery.getEnclosureUrl())
				.setAlias(enclosureQuery.getAlias())
				.setExtName(enclosureQuery.getExtName())
				.setCreateTime(LocalDateTime.now());
		testMapper.insert(equipmentTest);
		equipment.setTestDate(equipmentTest.getTestDate());
		equipment.setCheckDate(equipmentTest.getCheckDate());
		equipment.setPeriodDate(equipmentTest.getPeriodDate());
		equipment.setTryResult(equipmentTest.getTryResult());
		equipment.setEnclosureUrl(enclosureQuery.getEnclosureUrl());
		equipment.setAlias(enclosureQuery.getAlias());
		equipment.setExtName(enclosureQuery.getExtName());
		equipmentMapper.updateById(equipment);
		return BaseResponse.okData("检定完成");
	}



	/**
	 * 判断设备检定是否到期，如果到期，提醒检定人员 每天早上6点
	 * @return
	 */
	@Override
	@Scheduled(cron = "0 0 6 * * *")
	public BaseResponse<String> checktestDate(){
		//消息推送
		List<Integer> approvalIdList = sysApprovalMapper.getApprovalId("设备检定");
		if (approvalIdList == null) {
			return BaseResponse.errorMsg("设备检定信息错误");
		}
		String userIds = "";
		for(Integer testEQId : approvalIdList ){
			SysUser testEQUser = userService.getById(testEQId);
			if(testEQUser == null){
				return BaseResponse.errorMsg("设备检定信息错误");
			}
			if(StringUtils.isNotBlank(testEQUser.getWxId())){
				userIds = userIds.equals("")?testEQUser.getWxId():userIds+"|"+testEQUser.getWxId();
			}
		}
		QueryWrapper<Equipment> qw = new QueryWrapper<>();
		qw.eq("status",1);
		List<Equipment> equipmentList = equipmentMapper.selectList(qw);
		//当前日期
		LocalDate nowDate = LocalDate.now();
		for(Equipment eq : equipmentList ){
			//检定到期日期 = 上次检定日期+周期的值 - 7  （提前一周提醒）
			if(eq.getTestDate() != null && eq.getTestCycle() != null){
				LocalDate expireDate =  eq.getTestDate().plusYears(Long.valueOf(eq.getTestCycle())).minusWeeks(1);
				//如果当前日期等于检定到期日期 或者 当前日期大于检定到期日期，提示设备检定人员检定设备
				if(expireDate.isEqual(nowDate) || expireDate.isBefore(nowDate)){
					//发送企业微信消息内容
					String content="你好！名称："+eq.getName()+"，编号："+eq.getCode()+"的设备近期需要进行设备检定，如果已经检定完毕请前往\n" +
							Global.systemUrl+"更新检定记录。";
					System.out.println("**************************content**********************");
					System.out.println(content);
					weiXinService.sendTextMessage(userIds, content);
				}
			}
		}
		return BaseResponse.okMsg("成功");
	}


	/**
	 * 设备检定分页查询
	 *
	 * @param pageQuery
	 * @param equipmentId
	 * @return
	 */
	@Override
	public BaseResponse<IPage<EquipmentTestVo>> getTestPage(PageQuery pageQuery, Integer equipmentId) {
		Map<String, Object> params = new HashMap<>();
		params.put("equipmentId", equipmentId);
		Page<EquipmentTestVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<EquipmentTestVo> pages = testMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 设备检定详情
	 *
	 * @param id 设备检定表id
	 * @return
	 */
	@Override
	public BaseResponse<EquipmentTestVo> getTestDetail(Integer id) {
		EquipmentTestVo equipmentTestVo = testMapper.getTestDetail(id);
		if (equipmentTestVo == null || equipmentTestVo.getId() == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		List<EntityEnclosure> entityEnclosureList = commonService.getEnclosureList
				(EntityEnclosure.EntityType.EQUIPMENT_TEST, equipmentTestVo.getId());

		List<EnclosureQuery> enclosureQueryList = new ArrayList<>();
		for (EntityEnclosure entityEnclosure : entityEnclosureList) {
			EnclosureQuery enclosureQuery = new EnclosureQuery();
			enclosureQuery.setAlias(entityEnclosure.getAlias())
					.setEnclosureUrl(entityEnclosure.getEnclosureUrl())
					.setExtName(entityEnclosure.getExtName());
			enclosureQueryList.add(enclosureQuery);
		}

		return BaseResponse.okData(equipmentTestVo);
	}

	/**
	 * 设备故障维修登记
	 *
	 * @param query （不传id为添加记录，传id为修改记录）
	 * @return
	 */
	@Transactional
	@Override
	public BaseResponse<String> troubleshooting(EquipmentTroubleshootingQuery query) {
		if (query == null || query.getEquipmentId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		EquipmentVo equipmentVo = equipmentMapper.getDetail(query.getEquipmentId());
		if (equipmentVo == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		EquipmentTroubleshooting equipmentTroubleshooting = new EquipmentTroubleshooting();
		BeanUtils.copyProperties(query, equipmentTroubleshooting);
		if (query.getId() == null) {
			equipmentTroubleshooting.setUserId(userService.getLoginUser().getId())
					.setCreateTime(LocalDateTime.now());
			troubleshootingMapper.insert(equipmentTroubleshooting);
		} else {
			troubleshootingMapper.updateById(equipmentTroubleshooting);
		}
		return BaseResponse.okData("故障维修登记完成");
	}

	/**
	 * 设备故障维修登记分页查询
	 *
	 * @param pageQuery
	 * @param name
	 * @return
	 */
	@Override
	public BaseResponse<IPage<EquipmentTroubleshootingVo>> getTroubleshootingPage(PageQuery pageQuery,
	                                                                              String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		Page<EquipmentTroubleshootingVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<EquipmentTroubleshootingVo> pages = troubleshootingMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 设备维修列表导出
	 *
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void exportTroubleshooting(String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("name", name);
		List<Map<String, Object>> list = troubleshootingMapper.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] = "故障描述";
			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 id 设备故障维修登记表id
	 * @return
	 */
	@Override
	public BaseResponse<EquipmentTroubleshootingVo> getTroubleshootingDetail(Integer id) {
		EquipmentTroubleshootingVo equipmentTroubleshootingVo = troubleshootingMapper.getTroubleshootingDetail(id);
		if (equipmentTroubleshootingVo == null || equipmentTroubleshootingVo.getId() == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		return BaseResponse.okData(equipmentTroubleshootingVo);
	}

	/**
	 * 设备报废申请
	 *
	 * @param query
	 * @return
	 */
	@Override
	public BaseResponse<String> scrap(EquipmentScrapQuery query) {
		if (query == null || query.getEquipmentId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		EquipmentVo equipmentVo = equipmentMapper.getDetail(query.getEquipmentId());
		if (equipmentVo == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		QueryWrapper<EquipmentScrap> esWrapper = new QueryWrapper<>();
		esWrapper.eq("equipment_id", equipmentVo.getId());
		EquipmentScrap es = scrapMapper.selectOne(esWrapper);
		if (es != null) {
			return BaseResponse.errorMsg("此设备已经申请报废!");
		}
		EquipmentScrap equipmentScrap = new EquipmentScrap();
		BeanUtils.copyProperties(query, equipmentScrap);
		if (query.getId() == null) {
			equipmentScrap.setUserId(userService.getLoginUser().getId())
					.setStatus(0)
					.setCreateTime(LocalDateTime.now());
			scrapMapper.insert(equipmentScrap);
		} else {
			scrapMapper.updateById(equipmentScrap);
		}
		return BaseResponse.okData("设备报废申请完成");
	}

	/**
	 * 报废审批
	 *
	 * @param query
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<String> scrapApproval(EquipmentScrapApprovalQuery query) {
		if (query.getId() == null) {
			return BaseResponse.errorMsg("参数错误!");
		}
		EquipmentScrap equipmentScrap = scrapMapper.selectById(query.getId());
		if (equipmentScrap == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		equipmentScrap.setStatus(query.getIsAgree());
		equipmentScrap.setOpinion(query.getAuditReason());

		scrapMapper.updateById(equipmentScrap);
		if (query.getIsAgree() == 1) {
			Equipment equipment = equipmentMapper.selectById(equipmentScrap.getEquipmentId());
			if (equipment == null) {
				return BaseResponse.errorMsg("信息错误!");
			}
			equipment.setStatus(3);//报废状态
			equipmentMapper.updateById(equipment);
		}
		return BaseResponse.okData("审批完成");
	}

	/**
	 * 报废申请列表
	 *
	 * @param pageQuery
	 * @param brand
	 * @param supplierId
	 * @param name
	 * @return
	 */
	@Override
	public BaseResponse<IPage<EquipmentScrapVo>> getScrapApprovalPage(PageQuery pageQuery,
	                                                                  String brand, Integer supplierId, String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		params.put("name", name);
		Page<EquipmentScrapVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<EquipmentScrapVo> pages = scrapMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 报废申请列表导出
	 *
	 * @param brand
	 * @param supplierId
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void exportScrapApproval(String brand, Integer supplierId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		params.put("name", name);
		List<Map<String, Object>> list = scrapMapper.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] = "报废原因";
			headers[7] = "申请人";
			headers[8] = "报废申请日期";
			headers[9] = "申请结果";
			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 id 设备报废表id
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<EquipmentScrapVo> getscrapApprovalDetail(Integer id) {
		EquipmentScrapVo equipmentScrapVo = scrapMapper.getScrapDetail(id);
		if (equipmentScrapVo == null || equipmentScrapVo.getId() == null) {
			return BaseResponse.errorMsg("信息错误!");
		}
		return BaseResponse.okData(equipmentScrapVo);
	}

	/**
	 * 设备使用记录分页
	 *
	 * @param pageQuery
	 * @param brand
	 * @param supplierId
	 * @param name
	 * @return
	 */
	@Override
	public BaseResponse<IPage<EquipmentUseVo>> getUsePage(PageQuery pageQuery,
	                                                      String brand, Integer supplierId, String name) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		params.put("name", name);
		Page<EquipmentUseVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<EquipmentUseVo> pages = useMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	/**
	 * 设备使用记录导出
	 *
	 * @param brand
	 * @param supplierId
	 * @param name
	 * @param fileName
	 * @param response
	 */
	@Override
	public void exportUse(String brand, Integer supplierId, String name, String fileName, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
		params.put("brand", brand);
		params.put("supplierId", supplierId);
		params.put("name", name);
		List<Map<String, Object>> list = scrapMapper.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] = "参与项目";
			headers[7] = "项目编号";
			headers[8] = "检测项";
			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);
		}
	}

}
