package com.tjk.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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.CertificateUpload;
import com.tjk.comm.ReadPro;
import com.tjk.dao.OrderMapper;
import com.tjk.dao.UserMapper;
import com.tjk.vo.OrderListVo;
import com.tjk.vo.OrderVo;
import com.tjk.entity.Address;
import com.tjk.entity.Attachment;
import com.tjk.entity.Bankcard;
import com.tjk.entity.Order;
import com.tjk.entity.OrderStatistics;
import com.tjk.entity.OrderStatus;
import com.tjk.entity.User;
import com.tjk.entity.UserOrderInvestor;

@Controller
public class OrderController extends UserBaseController{
	@Resource
	private OrderMapper orderMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private ReadPro readPro;
	
	//添加定单
	@RequestMapping("/api/order/add_order.do")
	public void addOrder(OrderVo orderVo, HttpServletRequest request, HttpServletResponse response, String mobile,Integer introducerUid, Integer orderMount, String userName, String description, Integer productId,Integer orgin){
		JsonEntity json = this.getJsonInstance();
		int maxId = orderMapper.findMaxId();
		int rs=200;
		orderVo.setOrderId(maxId);
		Order order = new Order();
		if(orgin == null){
			orgin=0;
		}
		if(introducerUid!=null&&introducerUid>0){
			order.setIntroducerUid(introducerUid);
		}else {
			Integer uid = this.validUser(request);
			
			if(uid>0){
				User user=userMapper.findUserByUid(uid);
				if(user.getRole()==1&&user.getIsVerify()==1){
					order.setIntroducerUid(uid);
				}else{
					order.setUid(uid);
				}
				
			}
		}
		if(rs==200){
			order.setOrderId(maxId + 1);
			order.setOrderCode(this.FormatOrderCode(maxId+1));
			order.setUserName(userName);
			order.setMobile(mobile);
			order.setOrderMount(orderMount);
			order.setProductId(productId);
			order.setOrgin(orgin);
			order.setDescription(description);
			order.setMajorStatus(1070);
			order.setMinorStatus(1075);
			OrderStatus orderStatus = new OrderStatus();
			orderStatus.setOrderId(order.getOrderId());
			orderStatus.setMajorStatus(1070);
			orderStatus.setMinorStatus(1075);
			order.setMinorStatusName(this.getTablefield2(order.getMinorStatus()));
			orderStatus.setDescription(order.getMinorStatusName());
			if(order.getMobile()==""){
				order.setMobile(null);
			}
			if (this.orderMapper.addUserOrder(order) != 1 || this.orderMapper.addUserOrderStatus(orderStatus) != 1) {
				rs=400;
			}
		}
		json.setStatus(rs);
		System.out.println(json.getStatus());
		json.flush(response);
	}	
	@RequestMapping("/api/order/get_orders.do")
	public void getOrders(HttpServletRequest request, HttpServletResponse response, OrderVo orderVo, Integer page,Integer productType,Integer status) {
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		OrderListVo vo = new OrderListVo();
		vo.setCurrentPage(page);
		vo.setProductType(productType);
		vo.setStatus(status);
		vo.setUid(uid);
		if(uid != 0) {
			User user = userMapper.findUserByUid(uid);
			List<Order>  list;
			if (user.getRole() == 1) {
				list = orderMapper.getMyCustomOrder(vo);
			} else {
				list = orderMapper.getMyOrder(vo);
			}
			if (list != null) {
				for (Order order: list) {					
					order.setMajorStatusName(this.getTablefield(order.getMajorStatus()));
					order.setMinorStatusName(this.getTablefield(order.getMinorStatus()));
				}
				json.setDatas(list);
			}
		} else {
			json.setStatus(311);
		}
		json.flush(response);
	}
	
	@RequestMapping("/api/order/get_order.do")
	public void getOrder(HttpServletRequest request, HttpServletResponse response, Integer orderId, OrderVo orderVo) {
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if (uid > 0) {
			Order order = orderMapper.getOrderDetail(orderId);
			order.setMajorStatusName(this.getTablefield(order.getMajorStatus()));
			order.setMinorStatusName(this.getTablefield(order.getMinorStatus()));
			List<OrderStatus> orderStatus = orderMapper.getOrderStatus(orderId);
			if (orderStatus != null) {
				for (OrderStatus o: orderStatus) {
					o.setMajorStatusName(this.getTablefield(o.getMajorStatus()));
					o.setMinorStatusName(this.getTablefield(o.getMinorStatus()));
				}
			}
			HashMap<String, Object> map= new HashMap<String,Object>();
			map.put("orderStatus", orderStatus);
			json.setData(map);
			if (uid.equals(order.getUid()) || uid.equals(order.getIntroducerUid())) {
				List<Order> list = new ArrayList<Order>();
				list.add(order);
				json.setDatas(list);
			} else {
				json.setStatus(400);
			}
		} else {
			json.setStatus(311);
		}
		json.flush(response);
	}
	@RequestMapping("/api/order/get_order_statistics.do")
	public void getOrderStatistics(HttpServletRequest request, HttpServletResponse response, Integer productId) {
		JsonEntity json = this.getJsonInstance();
		OrderStatistics order = orderMapper.getOrderStatistics(productId);
		HashMap<String, Object> map= new HashMap<String,Object>();
		map.put("pdata", order);
		json.setData(map);
		json.flush(response);
	}
	//添加邮寄地址到订单
	@RequestMapping("/api/order/add_order_address.do")
	public void addOrderAddress(HttpServletRequest request, HttpServletResponse response, Integer orderId,Integer addressId,
			Integer majorStatus,Integer minorStatus){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			Order order=orderMapper.getOrderDetail(orderId);
			if(order!=null){
				Address address=userMapper.findAddressByAddressId(addressId);
				if(address!=null){
					order.setAddressId(addressId);
					order.setMajorStatus(majorStatus);
					order.setMinorStatus(minorStatus);
					
					if(orderMapper.addOrderAddress(order)!=1||modifyStatus(order)==400){
						json.setStatus(400);
					}
				}else{
					json.setStatus(309);
				}
			}else{
				json.setStatus(310);
			}
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	//添加银行卡到订单
	@RequestMapping("/api/order/add_order_bankcard.do")
	public void addOrderBankCard(HttpServletRequest request, HttpServletResponse response, Integer orderId,Integer bankCardId,
			Integer majorStatus,Integer minorStatus){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			Order order=orderMapper.getOrderDetail(orderId);
			if(order!=null){
				Bankcard bankcard=userMapper.findBankcardByCardId(bankCardId);
				if(bankcard!=null){
					order.setBankCardId(bankCardId);
					order.setMajorStatus(majorStatus);
					order.setMinorStatus(minorStatus);
					if(orderMapper.addOrderBank(order)!=1||modifyStatus(order)==400){
						json.setStatus(400);
					}
				}else{
					json.setStatus(309);
				}
			}else{
				json.setStatus(310);
			}
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	
	@RequestMapping("/api/order/modify_status.do")
	public void modifyStatus(HttpServletRequest request, HttpServletResponse response, Order order){
		JsonEntity json = this.getJsonInstance();
		int status = modifyStatus(order);
		if(status==400){
			json.setStatus(status);
		}
		json.flush(response);
	}
	@RequestMapping("/api/order/get_money.do")
	public void getMoney(HttpServletRequest request, HttpServletResponse response,Integer page){
		Integer uid = this.validUser(request);
		OrderListVo vo = new OrderListVo();
		vo.setCurrentPage(page);
		vo.setUid(uid);
		JsonEntity json = this.getJsonInstance();
		if (uid > 0) {
//			if (this.validVerify(uid, 1)) {//是否为认证理财师身份
				List<Order> list=orderMapper.getMoney(vo);
				json.setDatas(list);
//			} else {
//				json.setStatus(321);
//			}
		}else {
			json.setStatus(311);
		}
		json.flush(response);
		
	}
	
	//添加用户凭证
	@RequestMapping("/api/order/add_certificate.do")
	public void addCertificate(HttpServletRequest request, HttpServletResponse response,Integer flag,
			Integer orderId){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			CertificateUpload uploader = new CertificateUpload(request);
			uploader.uploadBase64("imgBase64");
			String uri = "/"+uploader.getUrl();
			String orginUri=uploader.getPhysicalPath();
			//图片保存成功后，方处理数据库更新操作
			if (uploader.getState().equals("SUCCESS")&&orderId!=null){
				Attachment atta=new Attachment();
				atta.setAttachmentType(3);
				atta.setOrginUri(orginUri);
				atta.setUri(uri);
				atta.setUid(uid);
				atta.setReserveId(flag);
				atta.setRelationId(orderId);
				if(flag==1){
					atta.setTitle(readPro.readProperties("reserve1"));
				}
				if(flag==2){
					atta.setTitle(readPro.readProperties("reserve2"));
				}
				if(flag==3){
					atta.setTitle(readPro.readProperties("reserve3"));
				}
				if(flag==4){
					atta.setTitle(readPro.readProperties("reserve4"));
				}
				if(flag==5){
					atta.setTitle(readPro.readProperties("reserve5"));
				}
				//判断此凭证是否已存在，存在则更新，否则添加
				if(orderMapper.findAttachment(atta)!=null){
					if(orderMapper.updateCertificate(atta)!=1){
						json.setStatus(400);
					}
				}else{
					if(orderMapper.addCertificate(atta)!=1){
						json.setStatus(400);
					}
				}
			}else{
				json.setStatus(400);
			}
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	//添加投资人
	@RequestMapping("api/order/add_investor.do")
	public void addInvestor(HttpServletRequest request, HttpServletResponse response,Integer orderId,
			String bankName){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			UserOrderInvestor investor=new UserOrderInvestor();
			investor.setOrderId(orderId);
			investor.setInvestorOpenbankName(bankName);
			//判断是否存在，存在则更新，否则添加
			if(orderMapper.findInvestor(orderId)!=null){
				if(orderMapper.updateInvestor(investor)!=1){
					json.setStatus(400);
				}
			}else{
				if(orderMapper.addInvesetor(investor)!=1){
					json.setStatus(400);
				}
			}
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	//根据reserveId查找凭证
	@RequestMapping("/api/order/find_certificate.do")
	public void findCertificate(HttpServletRequest request, HttpServletResponse response,Integer orderId,
			Integer reserveId){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			Attachment atta=new Attachment();
			atta.setUid(uid);
			atta.setReserveId(reserveId);
			atta.setRelationId(orderId);
			atta=orderMapper.findAttachment(atta);
			if(atta!=null){
				HashMap<String, Attachment> map=new HashMap<String, Attachment>();
				map.put("atta", atta);
				json.setData(map);
			}else{
				json.setStatus(324);
			}
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	
	//查找所有的订单凭证
	@RequestMapping("/api/order/find_all_certificate.do")
	public void findAllCertificate(HttpServletRequest request, HttpServletResponse response,Integer orderId){
		JsonEntity json = this.getJsonInstance();
		Integer uid = this.validUser(request);
		if(uid>0){
			List<Attachment> list=orderMapper.findAllAttachment(orderId);
			UserOrderInvestor investor=orderMapper.findInvestor(orderId);
			HashMap<String, String> map=new HashMap<String, String>();
			if (investor == null) {
				map.put("bankName", "");
			} else {
				map.put("bankName", investor.getInvestorOpenbankName());
			}
			json.setData(map);
			json.setDatas(list);
		}else{
			json.setStatus(311);
		}
		json.flush(response);
	}
	
	public int modifyStatus(Order order){
		order.setMinorStatusName(this.getTablefield2(order.getMinorStatus()));
		order.setDescription(order.getMinorStatusName());
		OrderStatus orderStatus = new OrderStatus();
		orderStatus.setOrderId(order.getOrderId());
		orderStatus.setMajorStatus(order.getMajorStatus());
		orderStatus.setMinorStatus(order.getMinorStatus());
		orderStatus.setDescription(order.getDescription());
		if(orderMapper.modifyUserOrder(order)!=1 || orderMapper.addUserOrderStatus(orderStatus)!=1){
			return 400;
		}
		return 200;
	}
}
