package com.tjk.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tjk.comm.ReadPro;
import com.tjk.dao.OrderMapper;
import com.tjk.dao.ProductMapper;
import com.tjk.dao.UserMapper;
import com.tjk.vo.ProductQueryVo;
import com.tjk.vo.ProductListVo;
import com.tjk.entity.OrderStatistics;
import com.tjk.entity.ProductSampleEntity;
import com.tjk.entity.ProductCommission;
import com.tjk.entity.ProductBasic;
import com.tjk.entity.ProductIssue;
import com.tjk.entity.ProductPerformance;
import com.tjk.entity.ProductDescription;
import com.tjk.entity.ProductSubscribe;
import com.tjk.entity.User;


@Controller
public class ProductController extends UserBaseController{
	@Resource
	ProductMapper productMapper;
	@Resource
	OrderMapper orderMapper;
	@Resource
	ReadPro read;
	@Resource
	UserMapper userMapper;
	
	/**
	 * 查看基金产品
	 */
	@RequestMapping("/api/product/list.do")
	public void listProductBasic(HttpServletRequest request,HttpServletResponse response, Integer productType,Integer status, Integer page){
		ProductListVo vo = new ProductListVo();
		vo.setCurrentPage(page);
		vo.setProductType(productType);
		vo.setStatus(status);
		JsonEntity json = this.getJsonInstance();
		List<ProductSampleEntity> list = productMapper.getSampleEntity(vo);
		List<OrderStatistics> listAll = orderMapper.getOrderStatisticsList();
		for (ProductSampleEntity entity: list) {
			entity.setDurationName(this.getTablefield(entity.getDuration()));
			entity.setTypeName(this.getTablefield(entity.getProductType()));
			for(OrderStatistics o:listAll){
				if(o.getProductId()==entity.getProductId()){
					float _f = (float)((long)o.getOrderMount()*100)/(entity.getMaximumExpectedIssuance()<=0?10000:entity.getMaximumExpectedIssuance());
					_f = _f > 100 ? 100 : _f;
					entity.setAppointmentPercent(Float.valueOf(String.format("%.1f",_f)));
				}
			}
		}
		json.setDatas(list);
		json.flush(response);
	}
	/**
	 * 查看单支产品信息
	 * @param request
	 * @param response
	 * @param productId
	 */
	@RequestMapping("/api/product/product.do")
	public void listProduct(HttpServletRequest request,HttpServletResponse response,Integer productId){
				
		ProductBasic basic = productMapper.getProductBasic(productId);
		ProductIssue issue = productMapper.getProductIssue(productId);
		ProductDescription descri = productMapper.getProductDescription(productId);
		ProductSubscribe subscri = productMapper.getProductSubscribe(productId);
		List<ProductCommission> commis = productMapper.getProductCommission(productId);
		/*
		 * appointment 已预约
		 * payment 已付款
		 * _appointment 还可预约
		 * _payment 还可打款
		 * total 基金规模
		 * time 剩余抢购时间
		 */
		OrderStatistics orderStatistics = orderMapper.getOrderStatistics(productId);
		int appointment = orderStatistics.getOrderMount();
		int payment = orderStatistics.getActualMount();
		int orderCount = orderStatistics.getOrderCount();
		int total = 10000;
		if(issue!=null){
			if(issue.getMaximumExpectedIssuance()!=null){
				total = issue.getMaximumExpectedIssuance();	
			}
		}
		int _appointment = total-appointment;
		int _payment = total-payment;
		float appointmentPercent =Float.valueOf(String.format("%.1f", (float)appointment*100/total));
		
		_appointment = _appointment < 0 ? 0 : _appointment;
		_payment = _payment < 0 ? 0 : _payment;
		appointmentPercent = appointmentPercent > 100 ? 100 : appointmentPercent;
		appointmentPercent = appointmentPercent < 0 ? 0 : appointmentPercent;
		
		float paymentPercent =Float.valueOf(String.format("%.1f", (float)payment*100/total));
		Date date = null;
		String time = "";
		ProductIssue pi = productMapper.getProductIssue(productId);
		if(pi == null || pi.getEndDate()==null){
			time = "剩余0天0小时";
		}else{
			date=pi.getEndDate();
			time = getTime(date);
		}
		HashMap<String, Object> map= new HashMap<String,Object>();
		map.put("basic", basic);
		map.put("issue", issue);
		map.put("descri", descri);
		map.put("subscri", subscri);
		map.put("commis", commis);
		
		map.put("appointment", appointment);
		map.put("payment", payment);
		map.put("_appointment", _appointment);
		map.put("_payment", _payment);
		map.put("time", time);
		map.put("appointmentPercent", appointmentPercent);
		map.put("paymentPercent", paymentPercent);
		map.put("orderCount", orderCount);
		JsonEntity json = this.getJsonInstance();
		json.setData(map);
		json.flush(response);
	}
	
	/**
	 * 查看单支产品的路演信息中所有的图片，用于图片预览功能
	 * @param request
	 * @param response
	 * @param productId
	 */
	@RequestMapping("/api/product/get_roadshow_images.do")
	public void getProductRoadShow(HttpServletRequest request,HttpServletResponse response,Integer productId){
		ProductDescription descri = productMapper.getProductDescription(productId);
		List<String> list = new ArrayList<String>(); 
		if (descri != null && descri.getRoadshowInfo() != null) {
			String IMGURL_REG = "(<img[^>]*?[/]{0,1}>)";  
			java.util.regex.Pattern p_image = java.util.regex.Pattern.compile(IMGURL_REG,java.util.regex.Pattern.CASE_INSENSITIVE|java.util.regex.Pattern.MULTILINE);
			java.util.regex.Matcher m_image = p_image.matcher(descri.getRoadshowInfo());  
			while(m_image.find()){  
				list.add(m_image.group());
			}
		} 
		JsonEntity json = this.getJsonInstance();
		json.setDatas(list);
		if (list.size() == 0) {
			json.setStatus(400);
		}
		json.flush(response);
	}
	
	/**
	 * 产品预约页需要的数据
	 */
	@RequestMapping("/api/product/appointment.do")
	public void toAppointment(HttpServletRequest request,HttpServletResponse response,Integer productId){
		ProductBasic basic = productMapper.getProductBasic(productId);
		HashMap<String, Object> map= new HashMap<String,Object>();
		Integer uid = this.validUser(request);
		User user = new User();
		if(uid!=null&&uid!=0){
			user = userMapper.findUserByUid(uid);
			map.put("user", user);
		}else{
			user=null;
			map.put("user", user);
		}
		map.put("basic", basic);
		JsonEntity json = this.getJsonInstance();
		json.setData(map);
		json.flush(response);
	}
	@RequestMapping("/api/product/subscribe.do")
	public void getSubscribe(HttpServletRequest request,HttpServletResponse response,Integer productId,Integer uid){
		ProductBasic basic = productMapper.getProductBasic(productId);
		HashMap<String, Object> map= new HashMap<String,Object>();
		User user = new User();
		if(uid!=null&&uid!=0){
			user = userMapper.findUserByUid(uid);
			map.put("user", user);
		}else{
			user=null;
			map.put("user", user);
		}
		map.put("basic", basic);
		JsonEntity json = this.getJsonInstance();
		json.setData(map);
		json.flush(response);
	}
	
	/**
	 * 查看基金表现
	 * 基金净值历史数据
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/api/product/performance.do")
	public void getProductPerformance(HttpServletRequest request,HttpServletResponse response,
			Integer productId, Integer last, Integer hs){
		ProductQueryVo vo = new ProductQueryVo();
		vo.setLast(last);
		vo.setHs(hs);
		vo.setProductId(productId);
		List<ProductPerformance> list = productMapper.getProductPerformance(vo);
		//获取同一时间范围内的沪深300指数
		com.tjk.entity.PerformanceQuery pq = new com.tjk.entity.PerformanceQuery();
		
		HashMap<String, Object> map= new HashMap<String,Object>();
		List pdata = new ArrayList();
		List hsdata = new ArrayList();
		if(list!=null&&list.size()!=0){
			pq.setExpiryDateStart(list.get(0).getExpiryDate());
			pq.setExpiryDateEnd(list.get(list.size()-1).getExpiryDate());
			for(ProductPerformance p:list){
				List l = new ArrayList();
				if(p.getExpiryDate()==null){
					p.setExpiryDate(new Date());
				}
				l.add(p.getExpiryDate().getTime());
				l.add(p.getNetValue());
				pdata.add(l);
			}
			map.put("pdata", pdata);
		}else{
			List l = new ArrayList();
			l.add(new Date().getTime());
			l.add(1);
			pdata.add(l);
			map.put("pdata", pdata);
		}
		List<ProductPerformance> _tmp = productMapper.getHSPerformance(pq);
		List<ProductPerformance> hsList = com.tjk.comm.FundsPerformance.getHS300(_tmp, list);
		if(hsList!=null){
			for(ProductPerformance p:hsList){
				List l = new ArrayList();
				if(p.getExpiryDate()==null){
					p.setExpiryDate(new Date());
				}
				l.add(p.getExpiryDate().getTime());
				l.add(p.getNetValue());
				hsdata.add(l);
			}
			map.put("hsdata", hsdata);
		}else{
			map.put("hsdata", null);
		}
		JsonEntity json = this.getJsonInstance();
		json.setData(map);
		json.flush(response);
	}
	/**
	 * 查看产品返佣比例
	 * @param request
	 * @param response
	 * @param productId
	 */
	@RequestMapping("/api/product/commission.do")
	public void listProductCommission(HttpServletRequest request,HttpServletResponse response,Integer productId){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		HashMap<String, Object> map= new HashMap<String,Object>();
		if (uid > 0) {
			if (this.validVerify(uid, 1)) {//是否为认证理财师身份
				List<ProductCommission> list=productMapper.getProductCommission(productId);
				map.put("commis", list);
				json.setData(map);
			} else {
				json.setStatus(321);
			}
		}else {
			json.setStatus(311);
		}
		json.flush(response);
	}

	public String getTime(Date date){
		Calendar c = Calendar.getInstance();
		Calendar c1 = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String s = format.format(date) + " 00:00:00";
		try {
			date = format.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		date.getTime();
		c1.setTime(date);
		int day = c1.get(Calendar.DAY_OF_YEAR)-c.get(Calendar.DAY_OF_YEAR);
		int hours = c.get(Calendar.HOUR_OF_DAY)-c1.get(Calendar.HOUR_OF_DAY);
		if(day<0){
			return "抢购已结束";
		}
		return "剩余"+day+"天"+hours+"小时";
	}
	
	
}
