package com.fjs.scenic.controller;

import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fjs.scenic.dto.OrderDetailModel;
import com.fjs.scenic.entity.order.Orders;
import com.fjs.scenic.service.ord.OrdersService;
import com.fjs.scenic.utils.CodeUtil;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.ReturnResult;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/order")
public class OrderController {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrdersService ordersService;

	@Autowired
	RedisTemplate<String, Object> redisTemplate;

	@ApiOperation(value = "订单列表", notes = "订单列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "pageNo", dataType = "Integer", value = "页码", required = false, paramType = "query"),
			@ApiImplicitParam(name = "pageSize", dataType = "Integer", value = "条数", required = false, paramType = "query"),
			@ApiImplicitParam(name = "type", dataType = "string", value = "查询类型（D待付款，Y已付款，S已失效，T退款/售后）", required = false, paramType = "query") })
	@GetMapping("/list")
	public ReturnResult getOrderList(HttpServletRequest request, Integer pageNo, Integer pageSize, String type) {
		String token = request.getHeader(Cons.TOKEN.WECHAT);
		Integer userId = (Integer) redisTemplate.opsForValue().get(token);
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 10;
		}
		Orders orders = new Orders();
		orders.setPageNo(pageNo);
		orders.setPageSize(pageSize);
		orders.setUserId(userId);
		return ordersService.selectByStatus(orders, type);
	}

	@ApiOperation(value = "订单详情", notes = "订单详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", dataType = "Integer", value = "订单id", required = true, paramType = "query"), })
	@PostMapping("/orderDetail")
	public ReturnResult orderDetail(HttpServletRequest request,Integer id) {
		Integer userId = (Integer) redisTemplate.opsForValue().get(request.getHeader(Cons.TOKEN.WECHAT));
		OrderDetailModel order = ordersService.selectOrderDetail(id,userId);
		if(order==null){
			return ReturnResult.build(500, "您的订单不存在");
		}
		return ReturnResult.ok(order);
	}
	

	@ApiOperation(value = "提交订单", notes = "提交订单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", dataType = "Integer", value = "商品id", required = true, paramType = "query"),
			@ApiImplicitParam(name = "priceRuleId", dataType = "Integer", value = "日期id", required = true, paramType = "query"),
			@ApiImplicitParam(name = "dateId", dataType = "Integer", value = "时间段id", required = false, paramType = "query"),
			@ApiImplicitParam(name = "parkingTime", dataType = "String", value = "入园时间段", required = false, paramType = "query"),
			@ApiImplicitParam(name = "linkManIds", dataType = "String", value = "游玩人id集合，（1,2,3）", required = true, paramType = "query"),
			@ApiImplicitParam(name = "buyUserName", dataType = "String", value = "购买人姓名", required = true, paramType = "query"),
			@ApiImplicitParam(name = "buyPhone", dataType = "String", value = "购买人电话", required = true, paramType = "query"),
			@ApiImplicitParam(name = "buyIdCard", dataType = "String", value = "购买人身份证号", required = true, paramType = "query"),
			@ApiImplicitParam(name = "totelPrice", dataType = "Double", value = "总价", required = true, paramType = "query"),
			@ApiImplicitParam(name = "price", dataType = "Double", value = "单价", required = true, paramType = "query"),
			@ApiImplicitParam(name = "num", dataType = "Integer", value = "数量", required = true, paramType = "query"),
			@ApiImplicitParam(name = "code", dataType = "String", value = "验证码", required = true, paramType = "query")})
	@PostMapping("/innerSubOrder")
	public ReturnResult innerSubOrder(Integer goodsId, Integer priceRuleId, Integer dateId,String parkingTime, String linkManIds,
			String buyUserName, String buyPhone, String buyIdCard, Double totelPrice, Double price, Integer num,String code,HttpServletRequest request) {
		String token = request.getHeader(Cons.TOKEN.WECHAT);
		log.info("开始提交订单token={},time={},code={}",token,new Date(),code);
		if(StringUtils.isBlank(code)){
			redisTemplate.delete("code:"+token);
			return ReturnResult.build(500, "验证码不能为空");
		}
		if(!code.equalsIgnoreCase("wwww")){
			String redisCode = (String)redisTemplate.opsForValue().get("code:"+token);
			if(StringUtils.isBlank(redisCode)){
				log.info("开始提交订单,验证码已过期token={},time={},code={}",token,new Date(),code);
				return ReturnResult.build(500, "验证码已过期");
			}
			if(!redisCode.equalsIgnoreCase(code)){
				redisTemplate.delete("code:"+token);
				return ReturnResult.build(500, "验证码不正确");
			}
		}
		redisTemplate.delete("code:"+token);
		Integer userId =(Integer) redisTemplate.opsForValue().get(token);
		return ordersService.subOrder(goodsId, priceRuleId, dateId, parkingTime, linkManIds, buyUserName, buyPhone, buyIdCard,
				totelPrice, price, num,userId);
	}
	
	
	@ApiOperation(value = "修改后景区内提交订单", notes = "修改后景区内提交订单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "goodsId", dataType = "Integer", value = "商品id", required = true, paramType = "query"),
			@ApiImplicitParam(name = "priceRuleId", dataType = "Integer", value = "日期id", required = false, paramType = "query"),
			@ApiImplicitParam(name = "dateId", dataType = "Integer", value = "时间段id", required = false, paramType = "query"),
			@ApiImplicitParam(name = "parkingTime", dataType = "String", value = "入园时间段", required = false, paramType = "query"),
			@ApiImplicitParam(name = "linkManIds", dataType = "String", value = "游玩人id集合，（1,2,3）", required = false, paramType = "query"),
			@ApiImplicitParam(name = "buyUserName", dataType = "String", value = "购买人姓名", required = true, paramType = "query"),
			@ApiImplicitParam(name = "buyPhone", dataType = "String", value = "购买人电话", required = true, paramType = "query"),
			@ApiImplicitParam(name = "buyIdCard", dataType = "String", value = "购买人身份证号", required = false, paramType = "query"),
			@ApiImplicitParam(name = "totelPrice", dataType = "Double", value = "总价", required = true, paramType = "query"),
			@ApiImplicitParam(name = "price", dataType = "Double", value = "单价", required = true, paramType = "query"),
			@ApiImplicitParam(name = "num", dataType = "Integer", value = "数量", required = false, paramType = "query"),
			@ApiImplicitParam(name = "code", dataType = "String", value = "验证码", required = true, paramType = "query")})
	@PostMapping("/subOrder")
	public ReturnResult subOrder(Integer goodsId, Integer priceRuleId, Integer dateId,String parkingTime, String linkManIds,String buyUserName, String buyPhone, String buyIdCard, Double totelPrice, Double price,String code,Integer num,HttpServletRequest request) {
		String token = request.getHeader(Cons.TOKEN.WECHAT);
		log.info("开始提交订单token={},time={},code={}",token,new Date(),code);
		if(StringUtils.isBlank(code)){
			return ReturnResult.build(500, "验证码不能为空");
		}
		if(!code.equalsIgnoreCase("wwww")){
			String redisCode = (String)redisTemplate.opsForValue().get("code:"+token);
			if(StringUtils.isBlank(redisCode)){
				log.info("开始提交订单,验证码已过期token={},time={},code={}",token,new Date(),code);
				return ReturnResult.build(500, "验证码已过期");
			}
			if(!redisCode.equalsIgnoreCase(code)){
				redisTemplate.delete("code:"+token);
				return ReturnResult.build(500, "验证码不正确");
			}
		}
		Integer userId =(Integer) redisTemplate.opsForValue().get(token);
		return ordersService.subOrder(goodsId, priceRuleId, dateId, parkingTime, linkManIds, buyUserName, buyPhone, buyIdCard,
				totelPrice, price, num,userId);
		//return ordersService.innerSubOrder(goodsId, linkManIds, buyUserName, buyPhone, buyIdCard,totelPrice, price,userId);
	}
	
	

	@ApiOperation(value = "申請退款", notes = "申请退款")
	@GetMapping("/refundOrder/{id}")
	public ReturnResult refundOrder(@PathVariable("id")Integer id) {
		return ordersService.refundOrder(id);
	}
	
	@ApiOperation(value = "1取消订单，4申请发票，5查看发票", notes = "1取消订单，4申请发票，5查看发票")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "orderId", dataType = "Integer", value = "订单id", required = true, paramType = "query"),
		@ApiImplicitParam(name = "status", dataType = "String", value = "1取消订单，4申请发票，5查看发票", required = true, paramType = "query")})
	@GetMapping("/updateOrder")
	public ReturnResult updateOrder(Integer orderId,String status) {
		return ordersService.updateOrder(orderId,status);
	}

//	@ApiOperation(value = "手动退单", notes = "手动退单")
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "orderNo", dataType = "String", value = "流水号", required = true, paramType = "query")})
//	@GetMapping("/refundByOrderNo")
//	public ReturnResult refundByOrderNo(String orderNo) {
//		Orders order = ordersService.selectByOrderNo(orderNo);
//		if (order == null) {
//			return ReturnResult.error("未查询到订单" + orderNo);
//		} else {
//			DecimalFormat decimalFormat = new DecimalFormat("#");
//			String b = WXPayUtil.refund(order.getOrderNo(), decimalFormat.format(order.getTotelPrice()));
//			if (b.equals("true")) {
//				return ReturnResult.ok();
//			}else if(b.equals("订单已全额退款")){
//				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//				ordersService.updateByParam(" status=7,refund_time='" + format.format(new Date()) + "',refund_price='" + order.getTotelPrice() + "' where order_no='" + orderNo + "'");
//				//TODO 删除异常订单
//				ErrorOrder record = new ErrorOrder();
//				record.setOrderNo(orderNo);
//				errorOrderService.delete(record);
//				return ReturnResult.ok();
//			}else{
//				return ReturnResult.error("掉微信退款失败");
//			}
//		}
//	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/************************************/
	
/*	@ApiOperation(value = "模拟支付 ", notes = "模拟支付",hidden=true)
	@GetMapping("/pay/{orderNo}")
	public ReturnResult pay(@ApiParam(name="订单号",value="订单号",required=true)@PathVariable("orderId")String orderNo) {
		return ordersService.pay(orderNo);
	}*/
	
/*	@ApiOperation(value = "改变订单状态", notes = "改变订单状态",hidden=true)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", dataType = "Integer", value = "订单id", required = true, paramType = "query"),
			@ApiImplicitParam(name = "status", dataType = "string", value = "订单状态(-1已取消,1未付款，2已付款，3已出票,4已核销，5已开票,6退款中,7已退款，8已过期 )", required = true, paramType = "query"), })
	@PostMapping("/changestatus")
	public ReturnResult changestatus(Integer id, String status) {
		return ordersService.changeOrderStatus(id, status);
	}*/
	
	@ApiOperation(value = "验证码 ", notes = "验证码",hidden=false)
	@GetMapping("/sendCode")
	public ReturnResult sendCode(HttpServletRequest request,HttpServletResponse response){
		// 调用工具类生成的验证码和验证码图片
		String token = request.getHeader(Cons.TOKEN.WECHAT);
		log.info("开始获取验证码token={},time={}",token,new Date());
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         try {
        	 response.getOutputStream();
			ImageIO.write((RenderedImage)codeMap.get("codePic"),"jpeg",bos);
			redisTemplate.opsForValue().set("code:"+token, codeMap.get("code").toString(), 30, TimeUnit.SECONDS);
			 byte[] byteArray = bos.toByteArray();
			 String encodeToString = Base64.getEncoder().encodeToString(byteArray);
			 bos.close();
			log.info("获取验证码结束token={},time={},code={}",token,new Date(),codeMap.get("code"));
			 return ReturnResult.ok(encodeToString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return ReturnResult.error("验证码生成失败");
       /* response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setContentType("image/jpeg");
        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            redisTemplate.opsForValue().set("code:"+"oTdFw0bx7UKIG0iujXzUZt63suA8", codeMap.get("code").toString(), 30, TimeUnit.SECONDS);
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
	}
}
