package com.sifang.modules.order.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.order.dao.*;
import com.sifang.modules.order.entity.*;

import com.sifang.modules.order.utils.Target;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.supply.order.constant.ApplyOrderConstants;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.util.CrmUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 反馈Service
 * @author Ivan
 * @version 2017-05-13
 */
@Component
public class OrderFeedbackService extends BaseService {

	@Autowired
	private OrderFeedbackDao orderFeedbackDao;

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private OrderOperationInfoDao infoDao;

	@Autowired
	private CrmOrderDispatchDao disDao;

	@Autowired
	private SiteOrderDispatchDao siteDisDao;

	private Logger logger = Logger.getLogger(OrderFeedbackService.class);
	
	public OrderFeedback get(String id) {
		return orderFeedbackDao.get(id);
	}
	
	public void save(OrderFeedback orderFeedback) {
		orderFeedbackDao.save(orderFeedback);
	}

	/**
	 * 过程反馈
	*/
	@Transactional(rollbackFor=Exception.class)
	public Result processFeedback(String orderId,String remarks,String imgs,String serviceMeasures){

		Result result = new Result();
		try {
			User user = UserUtils.getUser();
			String name = CrmUtils.getUserXM(user);
			CrmOrder or = orderDao.get(orderId);
			or.setLatestProcessTime(new Date());
			or.setLatestProcess(name+ "过程反馈,反馈内容:"+remarks);
			or.setServiceMeasures(serviceMeasures);
			orderDao.save(or);

			OrderFeedback back = new OrderFeedback();
			back.setFeedback(remarks);
			back.setFeedbackTime(new Date());
			back.setOrderId(orderId);
			Record rd = CrmUtils.getByUserId(user);
			if(rd != null){
				back.setFeedbackId(rd.getStr("id"));
				back.setFeedbackName(rd.getStr("name"));
			}
			back.setFeedbackImg(imgs);
			back.setRemarks(remarks);
			back.setSiteId(or.getSiteId());
			back.setFeedbackType(ApplyOrderConstants.FEEDBACK_PROCESS);
			orderFeedbackDao.save(back);
			result.setCode("200");
		}catch (Exception e){
			result.setCode("505");
			throw e;
		}

		return result;
	}
	/**
	 * 反馈封单完成
	*/
	@Transactional(rollbackFor=Exception.class)
	public Result feedbackSealingSheet(String orderId,String remarks,String imgs,String serviceMeasures){
		Result result = new Result();
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		Date time = new Date();
		try {
			//修改order表信息
			CrmOrder or = orderDao.get(orderId);
			logger.info("feedbackSealingSheet 反馈封单 orderId :"+orderId +"status、siteStatus : "+ or.getStatus() +" / "+or.getSiteStatus() );
			if(StringUtil.isBlank(or.getApplianceBarcode())){
				//机身条码为空
				return Result.fail("303","不满足反馈封单条件");
			}
			//服务商下状态为4、5、6才可以反馈封单
			if(!CrmOrder.FOUR.equals(or.getSiteStatus()) && !CrmOrder.FIVE.equals(or.getSiteStatus()) && !CrmOrder.SIX.equals(or.getSiteStatus())){
				logger.info("feedbackSealingSheet 反馈封单 不满足反馈封单条件  :"+orderId +"status、siteStatus : "+ or.getStatus() +" / "+or.getSiteStatus() +"user "+user.getId());
				return Result.fail("505","不满足反馈封单条件");
			}
			or.setLatestProcessTime(new Date());
			or.setLatestProcess(name+ "反馈封单,反馈内容:"+remarks);
			if(or.getSiteProcessTime() == null){
				or.setSiteProcessTime(time);
				or.setDropInTime(time);
			}
			if(or.getDropInTime() == null){
				or.setDropInTime(time);
			}
			or.setServiceMeasures(serviceMeasures);
			or.setEndTime(time);
			or.setStatus(CrmOrder.ORDERTYPETHREE);
			or.setSiteStatus(ApplyOrderConstants.SITE_STATUS_FINISH);
			orderDao.save(or);

			//修改过程信息表
			Target ta = new Target();
			ta.setD(DateUtils.getDateTime());
			ta.setP(name);
			ta.setC(name+ "反馈封单,反馈内容:"+remarks);
			CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
			ta.setT(14);
			String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
			info.setProcessDetail(str);
			infoDao.save(info);
			//修改平台派工表
			CrmOrderDispatch dis = disDao.getByOrderId(orderId);
			dis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_FINISH);
			dis.setUpdateBy(user.getId());
			dis.setUpdateTime(time);
			dis.setEndTime(time);
			if(dis.getDropInTime() ==null){
				dis.setDropInTime(time);
			}
			disDao.save(dis);

			//修改服务商派工表
			SiteOrderDispatch diDis = siteDisDao.getByOrderId(orderId);
			if(diDis !=null){
				diDis.setStatus(ApplyOrderConstants.DISPATCH_STATUS_FINISH);
				diDis.setUpdateBy(user.getId());
				diDis.setUpdateTime(time);
				diDis.setEndTime(time);
				if(diDis.getDropInTime() ==null){
					diDis.setDropInTime(time);
				}
				diDis.setCompletionResult(ApplyOrderConstants.RESULT_ZERO);
				siteDisDao.save(diDis);
			}
			//新增反馈表信息
			OrderFeedback back = new OrderFeedback();
			back.setFeedback(remarks);
			back.setOrderId(orderId);
			back.setFeedbackTime(new Date());
			Record rd = CrmUtils.getByUserId(user);
			if(rd != null){
				back.setFeedbackId(rd.getStr("id"));
				back.setFeedbackName(rd.getStr("name"));
			}
			back.setFeedbackImg(imgs);
			back.setRemarks(remarks);
			back.setSiteId(or.getSiteId());
			back.setFeedbackType(ApplyOrderConstants.FEEDBACK_FINISH);
			orderFeedbackDao.save(back);
			result.setCode("200");
		}catch (Exception e){
			result.setCode("400");
			throw e;
		}
		return result;
	}

	/**
	 * 平台端和厂家端已完成工单可以进行反馈------反馈封单完成
	 */
	@Transactional(rollbackFor=Exception.class)
	public Result feedbackSealingSheetYwc(String orderId,String remarks,String imgs){
		Result result = new Result();
		User user = UserUtils.getUser();
		String name = CrmUtils.getUserXM(user);
		try {
			CrmOrder or = orderDao.get(orderId);
			//修改过程信息表
			Target ta = new Target();
			ta.setD(DateUtils.getDateTime());
			ta.setP(name);
			ta.setC(name+ "已完工工单反馈封单,反馈内容:"+remarks);
			CrmOrderOperationInfo info = infoDao.getOperaByOrderId(orderId);
			ta.setT(14);
			String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
			info.setProcessDetail(str);
			infoDao.save(info);

			//新增反馈表信息
			OrderFeedback back = new OrderFeedback();
			back.setFeedback(remarks);
			back.setOrderId(orderId);
			back.setFeedbackTime(new Date());
			Record rd = CrmUtils.getByUserId(user);
			if(rd != null){
				back.setFeedbackId(rd.getStr("id"));
				back.setFeedbackName(rd.getStr("name"));
			}
			back.setFeedbackImg(imgs);
			back.setRemarks(remarks);
			back.setSiteId(or.getSiteId());
			back.setFeedbackType("0");
			orderFeedbackDao.save(back);
			result.setCode("200");
		}catch (Exception e){
			result.setCode("400");
			throw e;
		}
		return result;
	}



	// 获取工单的所有反馈内容
	public Map<String, Object> getOrderFeedbackRecords(String orderId) {
		Map<String, Object> ret = Maps.newHashMap();
		List<Map<String, Object>> list = Lists.newArrayList();
		List<Record> rds = orderFeedbackDao.getOrderFeedbackRecords(orderId);
		List<Map<String, Object>> imgMaps = Lists.newArrayList();
		/*boolean imgurl = false;*/
		Map<String, Object> imgFlag= Maps.newHashMap();
		if (rds != null) {
			for (int i = 0; i < rds.size(); i++) {
				Map<String, Object> imgs = Maps.newHashMap();
				Record rd = rds.get(i);
				String fbTime = DateUtils.formatDateTime(rd.getDate("feedback_time"));
				imgs.put("fbImgTime", DateUtils.formatDate(rd.getDate("feedback_time"),"MM-dd HH:mm:ss"));
				if (StringUtils.isNotBlank(rd.getStr("feedback_img"))) {
					String[] str = rd.getStr("feedback_img").split(",");
					imgs.put("fbImgPath", str);
					imgFlag.put("fbImgPathFlag","true");
					/*imgurl = true;*/
				}
				//钢结构照片
				if(StringUtil.isNotBlank(rd.getStr("steel_structure_img"))){
					String[] str1 = rd.getStr("steel_structure_img").split(",");
					imgs.put("steelStructureImg",str1);
					imgFlag.put("steelStructureImgFlag","true");
				}
				//支架照片
				if(StringUtil.isNotBlank(rd.getStr("bracket_img"))){
					String[] str2 = rd.getStr("bracket_img").split(",");
					imgs.put("bracketImg",str2);
					imgFlag.put("bracketImgFlag","true");
				}
				//组件照片
				if(StringUtil.isNotBlank(rd.getStr("assembly_img"))){
					String[] str3 = rd.getStr("assembly_img").split(",");
					imgs.put("assemblyImg",str3);
					imgFlag.put("assemblyImgFlag","true");
				}
				//设备接线照片
				if(StringUtil.isNotBlank(rd.getStr("device_img"))){
					String[] str4 = rd.getStr("device_img").split(",");
					imgs.put("deviceImg",str4);
					imgFlag.put("deviceImgFlag","true");
				}
				//有无遮挡照片
				if(StringUtil.isNotBlank(rd.getStr("shelter_img"))){
					String[] str5 = rd.getStr("shelter_img").split(",");
					imgs.put("shelterImg",str5);
					imgFlag.put("shelterImgFlag","true");
				}
				//全景照片
				if(StringUtil.isNotBlank(rd.getStr("panorama_img"))){
					String[] str6 = rd.getStr("panorama_img").split(",");
					imgs.put("panoramaImg",str6);
					imgFlag.put("panoramaImgFlag","true");
				}
			/*	imgs.put("feedbackId", rd.getStr("id"));*/
				Map<String, Object> item = Maps.newHashMap();
				item.put("feedbackTime", fbTime);
				item.put("feedbackName", rd.getStr("feedback_name"));
				item.put("feedbackResults", rd.getStr("feedback"));
				list.add(item);
				imgMaps.add(imgs);
			}
		}
		ret.put("feedbackImgs", imgMaps);
		ret.put("feedbackResults", list);
		ret.put("imgFlag",imgFlag);
		/*ret.put("isbackImg", imgurl);*/
		return ret;
	}

	// 服务商获取工单的所有反馈内容
	public Map<String, Object> getServiceOrderFeedbackRecords(String orderId, String siteId) {
		Map<String, Object> ret = Maps.newHashMap();
		List<Map<String, Object>> list = Lists.newArrayList();
		List<Record> rds = orderFeedbackDao.getServiceOrderFeedbackRecords(orderId, siteId);
		List<Map<String, Object>> imgMaps = Lists.newArrayList();
		boolean imgurl = false;
		if (rds != null) {
			for (int i = 0; i < rds.size(); i++) {
				Map<String, Object> imgs = Maps.newHashMap();
				Record rd = rds.get(i);
				String fbTime = DateUtils.formatDateTime(rd.getDate("feedback_time"));
				imgs.put("fbImgTime", DateUtils.formatDate(rd.getDate("feedback_time"),"MM-dd HH:mm:ss"));
				if (StringUtils.isNotBlank(rd.getStr("feedback_img"))) {
					String[] str = rd.getStr("feedback_img").split(",");
					imgs.put("fbImgPath", str);
					imgurl = true;
				}
				imgs.put("feedbackId", rd.getStr("id"));
				Map<String, Object> item = Maps.newHashMap();
				item.put("feedbackTime", fbTime);
				item.put("feedbackName", rd.getStr("feedback_name"));
				item.put("feedbackResults", rd.getStr("feedback"));
				list.add(item);
				imgMaps.add(imgs);
			}
		}
		ret.put("feedbackImgs", imgMaps);
		ret.put("feedbackResults", list);
		ret.put("isbackImg", imgurl);
		return ret;
	}
}
