package cn.service.atv.impl;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.facade.abs.IService;
import cn.common.page.response.Result;
import cn.component.rule.base.FillRuleUtil;
import cn.constant.CharsetKit;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.pojo.atv.AtvArea;
import cn.pojo.atv.AtvBoardCardFault;
import cn.pojo.atv.AtvBoardCardFaultFile;
import cn.pojo.atv.AtvBoardCardFaultHandle;
import cn.pojo.atv.AtvCountry;
import cn.pojo.atv.AtvLine;
import cn.pojo.atv.AtvTrain;
import cn.pojo.atv.vo.AtvDispatchPage;
import cn.pojo.entity.TSysUser;
import cn.service.atv.IAtvBoardCardFaultService;
import cn.service.util.UnifyFieldsUtil;
import cn.facade.util.UniAppPush;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.file.FileKit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** 板卡故障表 */
@Service
public class AtvBoardCardFaultImpl extends IService implements IAtvBoardCardFaultService 
{
	@Resource
	private FillRuleUtil ruleService;

	@Override
	public Long deleteFaultAndFile(Map<String,Object> whereMap)
	{
		Long num = daoService.executeSql("atv_delBoardCardFaultAndFile",whereMap);
		//删除图片文件，不检测是否成功
		String ids = TypeKit.objToStr(whereMap.get("id"));
		List<String> idList =Arrays.stream(ids.split(",")).collect(Collectors.toList());
		String filePath = fileService.getFileFullPath("archive");
		for(String id : idList) { 
			FileKit.delMultiFile(filePath,id + CharsetKit.SYMBOL_HIFEN);
		}
		return num;
	}
	@Override
	@Transactional
	public List<TSysUser> queryLineWorkers(String lineId)
	{
		QueryWrapper<AtvLine> queryWrapper = Wrappers.wrapper(AtvLine.class)
				.eq("id", lineId);
		AtvLine atvLine = daoService.findOne(queryWrapper);
		if (!IsKit.isEmpty(atvLine.getWorkers())) {
			List<TSysUser> loginUserList = sysBaseService.getUserListByNames(atvLine.getWorkers().split(","));
			return loginUserList;
		}
		return null;
	}

	@Override
	@Transactional
	public Result<?> dispatch(AtvDispatchPage atvDispatchPage)
	{
		QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
				.eq("id", atvDispatchPage.getBoardCardFaultId());
		AtvBoardCardFault atvBoardCardFault = daoService.findOne(queryWrapper);

		if (atvBoardCardFault == null) {
			return Result.warnMsg("未找到故障单");
		}
		if (atvBoardCardFault.getFaultStatus() != 3) {
			return Result.warnMsg("已上报状态无法派单");
		}

		atvBoardCardFault.setFaultStatus(4);
		atvBoardCardFault.setWorkerUserId(atvDispatchPage.getWorkerUserId());
		atvBoardCardFault.setWorkerUserName(atvDispatchPage.getWorkerUserName());
		daoService.update(atvBoardCardFault);

		AtvBoardCardFaultHandle atvBoardCardFaultHandle = new AtvBoardCardFaultHandle();
		atvBoardCardFaultHandle.setBoardCardFaultId(atvDispatchPage.getBoardCardFaultId());
		atvBoardCardFaultHandle.setFaultStatus(4);
		atvBoardCardFaultHandle.setRemarks(atvDispatchPage.getRemarks());
		atvBoardCardFaultHandle.setSendUserId(atvDispatchPage.getWorkerUserId());
		//LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Map<String, Object> userMap = UnifyFieldsUtil.getUserMap();
		atvBoardCardFaultHandle.setHandleUserId(UnifyFieldsUtil.getUserId_s());
		atvBoardCardFaultHandle.setHandleUserName(UnifyFieldsUtil.getUserName());
		atvBoardCardFaultHandle.setHandleUserPhone(TypeKit.objToStr(userMap.get("phonenumber")));
		TSysUser userBean = sysBaseService.getUserByName(atvDispatchPage.getWorkerUserId());
		if(IsKit.isNotNullOrEmpty(userBean)) {
			atvBoardCardFaultHandle.setSendUserName(userBean.getNickName());
			atvBoardCardFaultHandle.setSendUserPhone(userBean.getPhonenumber());
		}
		daoService.save(atvBoardCardFaultHandle);

		//派单推送
		String title = "新的故障工单";
		String text = buildMsg(atvBoardCardFault);
		//LoginUser
		TSysUser loginUser = sysBaseService.getUserByName(atvBoardCardFault.getWorkerUserId());
		if (loginUser.getClientId() != null && !loginUser.getClientId().equals("")) {
			UniAppPush.pushMessageToSingle(loginUser.getClientId(), title, text);
		}
		return Result.okMsg("派单成功!");
	}
	@Override
	public void saveMain(AtvBoardCardFault atvBoardCardFault, List<AtvBoardCardFaultFile> atvBoardCardFaultFileList)
	{
		//依照定义好的编码规则，产生字段的值
		String sn = ruleService.executeRule("fault_sn_rule",atvBoardCardFault.getSn()).toString();
		//设置故障编号
		atvBoardCardFault.setSn(sn);
		//写atv_board_card_fault  save
		daoService.save(atvBoardCardFault);

		//写atv_board_card_fault_fil
		if (atvBoardCardFaultFileList != null && atvBoardCardFaultFileList.size() > 0) {
			for (AtvBoardCardFaultFile entity : atvBoardCardFaultFileList) {
				//外键设置
				entity.setBoardCardFaultId(atvBoardCardFault.getId());
				entity.setFaultStatus(1);
				daoService.save(entity);
			}
		}
		Map<String, Object> whereMap = new HashMap<>();
		whereMap.put("id", atvBoardCardFault.getLineId());

		List<?> entityList = daoService.getEntityList("atv_line",whereMap,AtvLine.class);
		AtvLine atvLine = new AtvLine(); 
		if(IsKit.isNotNullOrEmpty(entityList)) {
			atvLine= (AtvLine) entityList.get(0);
		}
		if(IsKit.isNotNullOrEmpty(atvLine)) 
		{
			if(IsKit.isNotNullOrEmpty(atvLine.getWorkers())) {
				String title = "新的故障工单";
				String text = buildMsg(atvBoardCardFault);
				String[] usernames = atvLine.getWorkers().split(",");
				/**向所有人员发短信*/
		        List<TSysUser> loginUserList = sysBaseService.getUserListByNames(usernames);
	            for (TSysUser loginUser : loginUserList) {
	                if (loginUser.getClientId() != null && !loginUser.getClientId().equals("")) {
	                    try {
	                        UniAppPush.pushMessageToSingle(loginUser.getClientId(), title, text);
	                    } catch (Exception e) {
	                        LogKit.info(e.getMessage());
	                    }
	                }
	            }
			}			
		}
	}

	@Override
	public void updateMain(AtvBoardCardFault atvBoardCardFault, List<AtvBoardCardFaultFile> atvBoardCardFaultFileList)
	{
		daoService.update(atvBoardCardFault);
		if (atvBoardCardFaultFileList != null && atvBoardCardFaultFileList.size() > 0) {
			for (AtvBoardCardFaultFile entity : atvBoardCardFaultFileList) {
				entity.setBoardCardFaultId(atvBoardCardFault.getId());
				entity.setFaultStatus(1);
				daoService.saveOrUpdate(entity);
			}
		}
	}
	//派单推送消息构造
	private String buildMsg(AtvBoardCardFault atvBoardCardFault) 
	{
		String msg = "";
		QueryWrapper<AtvLine> queryWrapper = Wrappers.wrapper(AtvLine.class)
				.eq("id", atvBoardCardFault.getLineId()); 
		AtvLine atvLine = daoService.findOne(queryWrapper);

		if(IsKit.isNotNullOrEmpty(atvLine)) 
		{ 
			QueryWrapper<AtvCountry> queryCountry = Wrappers.wrapper(AtvCountry.class)
					.eq("id", atvBoardCardFault.getCountryId()); 
			AtvCountry atvCountry = daoService.findOne(queryCountry);

			QueryWrapper<AtvArea> queryArea = Wrappers.wrapper(AtvArea.class)
					.eq("id", atvBoardCardFault.getAreaId()); 
			AtvArea atvArea = daoService.findOne(queryArea);

			QueryWrapper<AtvTrain> queryTrain = Wrappers.wrapper(AtvTrain.class)
					.eq("id", atvBoardCardFault.getTrainId()); 
			AtvTrain atvTrain = daoService.findOne(queryTrain);

			msg = atvCountry.getName() + "-" + atvArea.getName() + "-" + atvLine.getName() + "-" + atvTrain.getSn() + "车";
		}			
		return msg;
	}
}
