package cn.com.countrygarden.bi.main.controller.mediaResource;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.com.countrygarden.bi.main.constant.mediaResource.MediaResourceConstant;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultGenerator;
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.dto.mediaResource.MediaOrderDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.handler.mediaResource.MediaOrderExportHandle;
import cn.com.countrygarden.bi.main.model.ExeclTemplateConstant;
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.mediaResource.MediaOrderService;
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.DownloadExeclTemplate;
import cn.com.countrygarden.bi.main.util.ExcelUtil;

@RestController
@RequestMapping("/api/reserve")
public class AdvertistingReserveController {
	@Autowired
	private AdvertistingReserveService service;
	@Autowired
    private MediaCommonService mediaCommonService;
	@Autowired
    private TbSysUserService tbSysUserService;
	@Autowired
    private MediaOrderService mediaOrderService;
	@Autowired
	private MediaOrderExportHandle mediaOrderExportHandle;
	@Autowired
	private ReserveSchdule reserveSchdule;
	/**
     * 部门：软件研发中心
     * 功能：获取字典值
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2019/1/8
     */
	@GetMapping("/getDicItem")
	public Result getDicItem(DictionaryDto dto) {
		try {
			return ResultGenerator.genSuccessResult(service.getDicItem(dto));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("获取下拉列表错误！");
		}
	}
	/**
     * 部门：软件研发中心
     * 功能：获取媒体列表
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/3
     */
	@PostMapping("/findPage")
	public Result findAdvertisingPage(HttpServletRequest request,AdvertisingResourcesDto dto) {
		try {
			String accessToken = request.getParameter("AccessToken");
			return ResultGenerator.genSuccessResult(service.findPage(accessToken,dto));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("获取列表错误！");
		}
	}
	/**
     * 部门：软件研发中心
     * 功能：媒体预定
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/3
     */
	@PostMapping("/reserveMedia")
	public Result reserveMedia(HttpServletRequest request,ReserveMediaDto dto) {
		try {
			String accessToken = request.getParameter("AccessToken");
			return service.reserveMedia(accessToken,dto);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("资源预定错误！");
		}
	}
	/**
     * 部门：软件研发中心
     * 功能：取消预定
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/4
     */
	@PostMapping("/cancelOrder")
	public Result cancelOrder(HttpServletRequest request,ReserveMediaDto dto) {
		try {
			String accessToken = request.getParameter("AccessToken");
			return ResultGenerator.genSuccessResult(service.cancelOrder(accessToken,dto));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("获取列表错误！");
		}
	}
	/**
     * 部门：软件研发中心
     * 功能：导出媒体资源信息
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/4
     */
	@GetMapping("/exportMeida")
	public void exportMeida(HttpServletRequest request,HttpServletResponse response,AdvertisingResourcesDto dto) {
		try {
			String accessToken = request.getParameter("AccessToken");
			if (StringUtils.hasText(dto.getDownloadTemplate())) {
				DownloadExeclTemplate.downloadTemplate(response, ExeclTemplateConstant.mediaResourcesTemplate);
			}else {
				String fileName="媒体信息"+ DateUtil.simpleFormat(new Date());
				String[] title = {"物业区域","物业项目","媒体类型","媒体形式","媒体编号","媒体位置1","媒体位置2",
						          "媒体规格(宽mm)","媒体规格(高mm)", "数量单位","单价单位","状态"};
				List<Map<String,Object>> exportData = service.findMediaOutPage(accessToken,dto);
				String[] fields = {"organName","commName","mediaType","mediaForm",
								   "mediaCode","siteOne","siteTwo","mediaWidth","mediaHeight",
								   "mediaUnit","priceUnit","mediaStatus"};
				ExcelUtil.exportExcel(fileName, "sheet1", null, title, exportData, response, fields);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	} 
	/**
     * 部门：软件研发中心
     * 功能：导出订单信息
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/4
     */
	 @GetMapping("/exportOrderList")
	    public void export(MediaOrderDto param, HttpServletRequest request, HttpServletResponse response) {
	        String orderStartDateStr = param.getOrderStartDateStr();
	        if (StringUtils.hasText(orderStartDateStr)) {
	            param.setOrderStartDate(DateUtil.parseDate(orderStartDateStr));
	        }

	        String orderEndDateStr = param.getOrderEndDateStr();
	        if (StringUtils.hasText(orderEndDateStr)) {
	            param.setOrderEndDate(DateUtil.parseDate(orderEndDateStr));
	        }
	        // 非总部设置权限
	        boolean adminRole = mediaCommonService.isAdminRole();
	        if (!adminRole) {
	            param.setCreateBy(tbSysUserService.getCurrentSysUser().getUserCode());
	        }// 有顺序关系
	        // 执行状态
	        if (MediaResourceConstant.ORDER_STATUS_TYPE.RUN.equals(param.getOrderStatus())) {

	            param.setCurrentDate(new Date());
	            //dto.setOrderEndDate(new Date());
	        }
	        // 已完成状态
	        if (MediaResourceConstant.ORDER_STATUS_TYPE.DONE.equals(param.getOrderStatus())) {
	            Date date = DateUtil.parseDate(DateUtil.simpleFormat(new Date()));
	            Calendar calendar = Calendar.getInstance();
	            calendar.setTime(date);
	            calendar.add(Calendar.DAY_OF_MONTH, 0);//+1今天的时间加一天
	            Date time = calendar.getTime();
	            param.setOrderEndDate(time);
	            param.setOrderStatus(MediaResourceConstant.ORDER_STATUS_TYPE.RUN);
	        }

	        param.setPageSize(-1);
	        List<MediaOrderDto> list = mediaOrderService.selectList(param);

	        ServletOutputStream outputStream;
	        try {
	            outputStream = response.getOutputStream();
	        } catch (IOException e) {
	            e.printStackTrace();
	            throw new ServiceException("获取io流失败");
	        }
	        // 响应处理
	        response.setContentType("multipart/form-data");
	        String fileName = "export.xlsx";
	        try {
	            fileName = URLEncoder.encode("订单明细" + ".xlsx", "UTF-8");
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
	        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
	        mediaOrderExportHandle.exportItemForPre(list, "订单明细", outputStream);
	    }
	/**
     * 部门：软件研发中心
     * 功能：打印
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/5
     */
	@PostMapping("/printing")
	public Result printing(AdvertisingResourcesDto dto) {
		try {
			return ResultGenerator.genSuccessResult(service.printing(dto));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("获取打印信息错误！");
		}
	}
	/**
     * 部门：软件研发中心
     * 功能：获取资源状态
     * 描述：略
     * 作成者：wan.ly
     * 作成时间：2018/12/5
     */
	@PostMapping("/getMediaStatus")
	public Result getMediaStatus(AdvertisingResourcesDto dto) {
		try {
			return ResultGenerator.genSuccessResult(service.getMediaStatus(dto));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("获取日历信息错误！");
		}
	}
	
	@GetMapping("/reserveSchdule")
	public void reserveSchdule(AdvertisingResourcesDto dto) {
		try {
			reserveSchdule.cancelOrder();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@GetMapping("/findfindfin")
	public Result findfindfin(String startDate,String endDate,String mediaId) {
		try {
			//return ResultGenerator.genSuccessResult(service.verifyTimeQuantum(startDate,endDate,mediaId));
			return ResultGenerator.genSuccessResult(service.findOrderCode(startDate,endDate,mediaId));
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.genFailResult("查询订单号失败~");
		}
	}
}
