package cn.com.countrygarden.bi.main.service.mediaResource.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.ranges.RangeException;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageRowBounds;

import cn.com.countrygarden.bi.main.constant.mediaResource.MediaResourceConstant;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.dao.mediaResource.AdvertisingResourcesMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.AdvertistingReserveMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.BasicInfoMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.MediaCycleLogMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.MediaOrderBillMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.ScheduleBasicInfoMapper;
import cn.com.countrygarden.bi.main.dto.AdvertisingResourcesDto;
import cn.com.countrygarden.bi.main.dto.DictionaryDto;
import cn.com.countrygarden.bi.main.dto.ReserveMediaDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.mediaResource.AdvertisingResources;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaCycle;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaCycleLog;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaOrder;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaOrderBill;
import cn.com.countrygarden.bi.main.model.mediaResource.MediaOrderParam;
import cn.com.countrygarden.bi.main.model.mediaResource.ReserveMsg;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.mediaResource.AdvertistingReserveService;
import cn.com.countrygarden.bi.main.service.mediaResource.MediaCommonService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.PageUtil;
import cn.com.countrygarden.bi.main.util.SnowflakeUtil;
import freemarker.template.utility.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Service
@Transactional
@SuppressWarnings("all")
public class AdvertistingReserveServiceImpl implements AdvertistingReserveService{
	
	@Autowired
	private AdvertistingReserveMapper mapper;
	@Autowired
	private AccessTokenService accessTokenService;
	@Autowired
    private TbSysUserService tbSysUserService;
	@Autowired
	private ScheduleBasicInfoMapper scheduleBasicInfoMapper;
	@Autowired
	private MediaCommonService mediaCommonService;
	@Autowired
	private BasicInfoMapper basicInfoMapper;
	@Autowired
	private MediaOrderBillMapper mediaOrderBillMapper;
	@Autowired
	private MediaCycleLogMapper mediaCycleLogMapper;
	/**
     * 部门：软件研发中心
     * 功能：获取字典值
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/3
     */
	@Override
	public List<Map<String,String>> getDicItem(DictionaryDto dto){
		return mapper.getDicItem();
	}
	/**
     * 部门：软件研发中心
     * 功能：获取媒体列表
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/3
     */
	@Override
	public PageData findPage(String accessToken,AdvertisingResourcesDto dto) {
		/*TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(),MediaResourceConstant.roleCode);
		if (count==0) {
			String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
			organCode = "01".equals(organCode)?null:organCode;
			dto.setOrganCode(organCode);
			//dto.setCreateBy(user.getUserCode());
		}*/
		dto.setPageIndex(dto.getPageIndex()==null?1:dto.getPageIndex());
		dto.setPageSize(dto.getPageSize()==null?10:dto.getPageSize());
		int pageOffset = PageUtil.getPageOffset(dto.getPageIndex(),dto.getPageSize());
		dto.setPageOffset(pageOffset);
		List<MediaOrderParam> list = mapper.findAdvertisingPage(dto);
		List<MediaOrderParam> newList =new ArrayList<MediaOrderParam>();
		for(MediaOrderParam obj:list) {
			if(obj.getMediaType()!=null && !"".equals(obj.getMediaType())) {
				String type = MediaResourceConstant.MEDIA_TYPE.DES.getOrDefault(Integer.parseInt(obj.getMediaType()), "");
				obj.setMediaType(type);
			}
			if(obj.getMediaForm()!=null && !"".equals(obj.getMediaForm())) {
				String form = MediaResourceConstant.MEDIA_FORM.DES.getOrDefault(Integer.parseInt(obj.getMediaForm()), "");
				 obj.setMediaForm(form);
			}
			if(obj.getMediaStatusStr()!=null && !"".equals(obj.getMediaStatusStr())) {
				 String status = MediaResourceConstant.MEDIA_STATUS.DES.getOrDefault(Integer.parseInt(obj.getMediaStatusStr()), "");
				 obj.setMediaStatusStr(status);
			}
			 newList.add(obj);
		}
		long total = mapper.findAdvertisingCount(dto);
		PageRowBounds pageRowBounds = new PageRowBounds(dto.getPageIndex(), dto.getPageSize());
	    pageRowBounds.setTotal(total);
	    pageRowBounds.setCount(true);
        PageData pageData = new PageData(newList, pageRowBounds);
        return pageData;
	}
	
	/**
     * 部门：软件研发中心
     * 功能：订单预定
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/3
     */
	@Override
	public Result reserveMedia(String accessToken,ReserveMediaDto dto) {
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		Long  orderId = SnowflakeUtil.INSTANCE.getId();
		String listStr = dto.getList();
		JSONArray json = JSONArray.fromObject(listStr);
		List<ReserveMsg> msgList = new ArrayList<ReserveMsg>();
		List<MediaOrderBill> orderBillList = new ArrayList<MediaOrderBill>();
		for(int j=0;j<json.size();j++) {
			JSONObject jsonObj = json.getJSONObject(j);
			int betweenDay = mediaCommonService.dayDiff(DateUtil.parseDate(jsonObj.getString("billStartTime")),DateUtil.parseDate(jsonObj.getString("billEndTime")));
			int isExit=0;
			for(int i=0;i<betweenDay;i++) {
				Calendar calendar = Calendar.getInstance();
				Date date = DateUtil.parseDate(jsonObj.getString("billStartTime"));
		        calendar.setTime(date);
		        calendar.add(Calendar.DAY_OF_MONTH, +i);//+1今天的时间加一天
		        date = calendar.getTime();
		        MediaCycle cycleParm = new MediaCycle();
		        cycleParm.setCycleTime(date);
		        cycleParm.setMediaId(Long.parseLong(jsonObj.getString("mediaId")));
		        isExit += mapper.checkInSchdule(cycleParm);
		        if(isExit>0) {
		        	break;
		        }
			}  
			if(isExit>0) {
				ReserveMsg msg = new ReserveMsg();
	        	msg.setMsg("该资源已经被使用,请重新选择!");
	        	msg.setNum(j+1);
	        	msg.setDataId(jsonObj.getString("mediaCode"));
	        	msgList.add(msg);
			}
		}
		if(msgList!=null && msgList.size()>0) {
        	return new Result()
                    .setResultCode(501)
                    .setResultMsg("该资源已经被使用,请重新选择!")
                    .setData(msgList);
        }
		List<MediaCycleLog> logList = new ArrayList<MediaCycleLog>();
		for(int j=0;j<json.size();j++) {
			JSONObject job = json.getJSONObject(j);
			Long  orderBillId = SnowflakeUtil.INSTANCE.getId();
			int betweenDay = mediaCommonService.dayDiff(DateUtil.parseDate(job.getString("billStartTime")),DateUtil.parseDate(job.getString("billEndTime")));
			List<MediaCycle> recordList = new ArrayList<MediaCycle>();
			for(int i=0;i<betweenDay;i++) {
				Calendar calendar = Calendar.getInstance();
				Date date = DateUtil.parseDate(job.getString("billStartTime"));
		        calendar.setTime(date);
		        calendar.add(Calendar.DAY_OF_MONTH, +i);//+1今天的时间加一天
		        date = calendar.getTime();
	        	//保存排期表
		        MediaCycle cycle = new MediaCycle();
		        Long  cycleId = SnowflakeUtil.INSTANCE.getId();
	        	cycle.setCycleId(cycleId);
	        	cycle.setCycleTime(date);
	        	cycle.setCycleStatus(1);// 1预定
	        	if("null".equals(job.getString("commId"))) {
	        		cycle.setCommId(null);
	        	}else {
	        		cycle.setCommId(job.getString("commId"));
	        	}
	        	cycle.setOrganCode(job.getString("organCode"));
	        	cycle.setMediaId(Long.parseLong(job.getString("mediaId")));
	        	cycle.setIsDelete(0);
	        	cycle.setSort(0);//自增？
	        	cycle.setVersion(0);//自增？
	        	//mapper.insertCycle(cycle);
	        	recordList.add(cycle);
	        }
			if(recordList!=null && recordList.size()>0) {
				mapper.insertList(recordList);
			}
			//保存订单明细表
			MediaOrderBill orderBill = new MediaOrderBill();
			int sort = mapper.getMaxSort();
			orderBill.setOrderId(orderId);
			orderBill.setOrderBillId(orderBillId.toString());
			orderBill.setMediaId(job.getString("mediaId"));
			orderBill.setVersion(0);
			orderBill.setCreateBy(user.getUserCode());
			orderBill.setCreateTime(new Date());
			orderBill.setCreateByName(user.getUserName());
			orderBill.setModBy(user.getUserCode());
			orderBill.setModTime(new Date());
			orderBill.setModByName(user.getUserName());
			orderBill.setIsDelete(0);
			Date billStartTime = DateUtil.parseDate(job.getString("billStartTime"));
			Date billEndTime = DateUtil.parseDate(job.getString("billEndTime"));
			orderBill.setPrepareStartDate(billStartTime);
			orderBill.setPrepareEndDate(billEndTime);
			orderBill.setOrderBillStartDate(billStartTime);
			orderBill.setOrderBillEndDate(billEndTime);
			orderBill.setSort(sort+1);
			orderBill.setCycleStatus("1");//预定
			orderBillList.add(orderBill);
			//mapper.insertOrderBillDetail(orderBill);
			//保存变更记录表
	        MediaCycleLog log = new MediaCycleLog();
	        Long  cycleLogId = SnowflakeUtil.INSTANCE.getId();
	        log.setCycleLogId(cycleLogId);
	        if("null".equals(job.getString("commId"))) {
	        	log.setCommId(null);
        	}else {
        		log.setCommId(job.getString("commId"));
        	}
	        log.setCreateBy(user.getUserCode());
	        log.setCreateTime(new Date());
	        log.setCreateByName(user.getUserName());
	        log.setCycleStatus("1");
	        log.setStartDate(DateUtil.parseDate(dto.getBillStartTime()));
	        log.setEndDate(DateUtil.parseDate(dto.getBillEndTime()));
	        log.setMediaId(job.getString("mediaId"));
	        log.setOrderBillId(orderBill.getOrderBillId());
	        log.setOrganCode(job.getString("organCode"));
	        int logSort = mapper.getMaxLogSort();
	        log.setSort(logSort);
	        logList.add(log);
	        //mapper.insertCycleLog(log);
		}
		if(orderBillList!=null && orderBillList.size()>0) {
			mediaOrderBillMapper.insertList(orderBillList);
		}
		if(logList!=null && logList.size()>0) {
			mediaCycleLogMapper.insertList(logList);
		}
		//保存订单表
		MediaOrder orderInfo = new MediaOrder();
		int orderSort = mapper.getMaxOrderSort();
		if("".equals(dto.getCustomerId())) {
			dto.setCustomerId(null);
		}
		orderInfo.setOrderId(orderId);
		orderInfo.setCustomerId(dto.getCustomerId());
		String orderCode = "M"+DateUtil.simpleFormat1(new Date())+UUID.randomUUID().toString().substring(0, 4);
		orderInfo.setOrderCode(orderCode);
		orderInfo.setRemark(dto.getRemark());
	    orderInfo.setOrderStartDate(DateUtil.parseDate(dto.getBillStartTime()));
		orderInfo.setOrderEndDate(DateUtil.parseDate(dto.getBillEndTime()));
		orderInfo.setOrderStatus(0);//0 预定
		orderInfo.setSort(orderSort+1);
		orderInfo.setVersion(0);
		orderInfo.setIsDelete(0);
		orderInfo.setCreateBy(user.getUserCode());
		orderInfo.setCreateTime(new Date());
		orderInfo.setCreateByName(user.getUserName());
		orderInfo.setModBy(user.getUserCode());
		orderInfo.setModTime(new Date());
		orderInfo.setModByName(user.getUserName());
		String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
		orderInfo.setOrganCode(organCode);
		mapper.insertOrderInfo(orderInfo);
		return ResultGenerator.genSuccessResult();
	 }
	
	/**
     * 部门：软件研发中心
     * 功能：取消预定
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/4
     */
	@Override
	public int cancelOrder(String accessToken,ReserveMediaDto mediaDto) {
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		List<MediaCycleLog> logList = new ArrayList<MediaCycleLog>();
		List<String> orderList = mediaDto.getOrderIdStr();
		for(String orderId:orderList) {
			//订单状态置为已终止
			AdvertisingResourcesDto obj = new AdvertisingResourcesDto();
			obj.setOrderId(orderId);
			obj.setOrderStatus("3");
			obj.setModBy(user.getUserCode());
			obj.setModTime(new Date());
			obj.setModByName(user.getUserName());
			mapper.updateOrderStatus(obj);
			//明细置为未使用
			obj.setCycleStatus("0");
			mapper.updateOrderBillStatus(obj);
			//释放资源
			mapper.delCycleMedia(obj);
			//获取订单明细   存储纪录表使用
			logList = mapper.getOrderBillDetail(obj);
		}
		for(MediaCycleLog log:logList) {
			Long  cycleLogId = SnowflakeUtil.INSTANCE.getId();
			log.setCreateBy(user.getUserCode());
			log.setCreateByName(user.getUserName());
			log.setCreateTime(new Date());
			log.setCycleStatus("0");
			log.setCycleLogId(cycleLogId);
		}
		//保存排期纪录表
		if(logList!=null && logList.size()>0) {
			mediaCycleLogMapper.insertList(logList);
		}
		return 0 ;
	}
	/**
     * 部门：软件研发中心
     * 功能：获取媒体导出信息
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/4
     */
	@Override
	public List<Map<String,Object>> findMediaOutPage(String accessToken,AdvertisingResourcesDto dto){
		/*TbSysUser user = findErpUser(accessToken);
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(),MediaResourceConstant.roleCode);
		if (count==0) {
			String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
			dto.setOrganCode(organCode);
			dto.setCreateBy(user.getUserCode());
		}*/
		List<Map<String,Object>> list = mapper.findMediaOutPage(dto);
		List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
		for(Map<String, Object> obj:list) {
			if(obj.get("mediaType")!=null&&!"".equals(obj.get("mediaType").toString())) {
				String type = MediaResourceConstant.MEDIA_TYPE.DES.getOrDefault(Integer.parseInt(obj.get("mediaType").toString()), "");
				obj.put("mediaType", type);
			}
			if(obj.get("mediaForm")!=null&&!"".equals(obj.get("mediaForm").toString())) {
				String form = MediaResourceConstant.MEDIA_FORM.DES.getOrDefault(Integer.parseInt(obj.get("mediaForm").toString()), "");
				obj.put("mediaForm", form);
			}
			if(obj.get("mediaStatus")!=null&&!"".equals(obj.get("mediaStatus").toString())) {
				String mediaStatus = MediaResourceConstant.MEDIA_STATUS.DES.getOrDefault(Integer.parseInt(obj.get("mediaStatus").toString()), "");
				obj.put("mediaStatus", mediaStatus);
			}
			newList.add(obj);
		}
		return newList;
	}
	
	
	/**
     * 部门：软件研发中心
     * 功能：打印
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/5
     */
	@Override
	public List<Map<String, Object>> printing(AdvertisingResourcesDto dto){
		List<Map<String, Object>> mapList =new ArrayList<Map<String, Object>>();
		List<String> ids = dto.getIds();
		for(String id:ids) {
			dto.setOrderId(id.toString());
			Map<String, Object> map = new HashMap<String, Object>();
			List<MediaOrderParam> list = mapper.getCancelOrderListForPrint(dto);
			MediaOrderParam info = mapper.getCancelOrderInfo(dto);
			MediaOrderParam value = new MediaOrderParam();
			value.setOrderCode(info.getOrderCode());
			value.setOrderStartDate(info.getOrderStartDate());
			value.setOrderEndDate(info.getOrderEndDate());
			value.setRemark(info.getRemark());
			value.setCustomerName(info.getCustomerName());
			value.setContactPhone(info.getContactPhone());
			if(info!=null) {
				if(info.getCustomerType()!=null && !"".equals(info.getCustomerType())) {
					String customerType = MediaResourceConstant.CUSTOMER_TYPE.DES.getOrDefault(Integer.parseInt(info.getCustomerType()), "");
					value.setCustomerType(customerType);
				}
			}
			List<MediaOrderParam> newList =new ArrayList<MediaOrderParam>();
			for(MediaOrderParam obj:list) {
				if(obj.getMediaType()!=null && !"".equals(obj.getMediaType())) {
					String type = MediaResourceConstant.MEDIA_TYPE.DES.getOrDefault(Integer.parseInt(obj.getMediaType()), "");
					obj.setMediaType(type);
				}
				if(obj.getMediaForm()!=null && !"".equals(obj.getMediaForm())) {
					String form = MediaResourceConstant.MEDIA_FORM.DES.getOrDefault(Integer.parseInt(obj.getMediaForm()), "");
					 obj.setMediaForm(form);
				}
				if(obj.getCycleStatus()!=null && !"".equals(obj.getCycleStatus())) {
					 String status = MediaResourceConstant.CYCLE_STATUS.DES.getOrDefault(Integer.parseInt(obj.getCycleStatus()), "");
					 obj.setCycleStatus(status);
				}
				 newList.add(obj);
			}
			map.put("list", list);
			map.put("info", value);
			mapList.add(map);
		}
		return mapList;
	}
	
	/**
     * 部门：软件研发中心
     * 功能：获取资源状态
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/5
     */
	
	
	@Override
	public List<Map<String, Object>> getMediaStatus(AdvertisingResourcesDto dto){
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		 List<Date> dateList = dto.getList();
		 MediaCycle cycle = new MediaCycle();
		 for(Date date:dateList) {
			 SimpleDateFormat sdf = new SimpleDateFormat("dd");
			 String lable =  sdf.format(date);
			 cycle.setCycleTime(DateUtil.parseDate(DateUtil.simpleFormat(date)));
			 cycle.setMediaId(Long.parseLong(dto.getMediaId()));
			 Map<String, Object> mapValue = new HashMap<String, Object>();
			 Map<String, Object> map =  mapper.getMediaStatus(cycle);
			 mapValue.put("label",lable);
			 mapValue.put("value",date);
			 if(map!=null&& map.size()>0) {
				 mapValue.put("type",map.get("cycleStatus"));
			 }else {
				 mapValue.put("type","0");//未使用
			 }
			 mapList.add(mapValue);
		 }
		 return mapList;
	}
	
	public TbSysUser findErpUser(String accessToken) {
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		return user;
	}
	
	public String checkMediaCycle(String orderId,String mediaId,String startTime,String endTime) {
		int betweenDay = mediaCommonService.dayDiff(DateUtil.parseDate(startTime),DateUtil.parseDate(endTime));
		for(int i=0;i<betweenDay;i++) {
			Calendar calendar = Calendar.getInstance();
			Date date = DateUtil.parseDate(startTime);
	        calendar.setTime(date);
	        calendar.add(Calendar.DAY_OF_MONTH, +i);//+1今天的时间加i天
	        date = calendar.getTime();
	        MediaOrderParam param = new MediaOrderParam();
	        param.setOrderIdStr(orderId);
	        param.setMediaId(mediaId);
	        param.setCycleTime(date);
	        int num = 0;//mapper.checkMediaCycle(param);
			if(num>0) {
				throw new ServiceException("该资源在此时间段内已被排期");
			}
		}
		return "";
	}
	@Override
	public List<String> findOrderCode(String startDate, String endDate, String mediaId) {
		return mapper.findOrderCode(startDate,endDate,Long.valueOf(mediaId));
	}
	
	@Override
	public boolean verifyTimeQuantum(String beginDate,String endDate,String mediaId) {
		int count = mapper.queryTimeQuantum(beginDate,endDate,Long.valueOf(mediaId));
		return count==0?true:false;
	}
}
