package com.lgx8.right.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.lgx8.common.PageArgument;
import com.lgx8.common.PageList;
import com.lgx8.common.entities.ProductImage;
import com.lgx8.common.servlet.BaseController;
import com.lgx8.common.util.FarewayUtil;
import com.lgx8.common.util.SendSms;
import com.lgx8.gateway.dao.IFareWayDao;
import com.lgx8.gateway.dao.IOrderProductDao;
import com.lgx8.gateway.dao.IProductDao;
import com.lgx8.gateway.dao.IShoppingInfoDao;
import com.lgx8.gateway.entities.Address;
import com.lgx8.gateway.entities.FareWay;
import com.lgx8.gateway.entities.OrderProduct;
import com.lgx8.gateway.entities.Orders;
import com.lgx8.gateway.entities.Product;
import com.lgx8.gateway.entities.ReturnRequest;
import com.lgx8.gateway.entities.ShoppingInfo;
import com.lgx8.gateway.service.IAddressService;
import com.lgx8.gateway.service.IOrderService;
import com.lgx8.management.dao.ICustmerXFDao;
import com.lgx8.management.dao.IDictionaryDao;
import com.lgx8.management.entities.Dictionary;
import com.lgx8.management.service.IAccountDetailService;
import com.lgx8.right.action.form.AccountDetailQueryForm;
import com.lgx8.right.common.EncryptUtil;
import com.lgx8.right.common.MemberURLConst;
import com.lgx8.right.common.StringUtil;
import com.lgx8.right.entities.RunTimeUser;
import com.lgx8.right.entities.User;
import com.lgx8.right.service.IUserCardService;
import com.lgx8.util.ImageUtils;
/**
* 处理会员业务的类
* */
@Controller
@SuppressWarnings("unchecked")
public class MemberController extends BaseController{
@Resource(name="orderService")
private IOrderService orderService;
@Resource(name="addressService")
private IAddressService addressService;
@Resource(name="userCardService")
public IUserCardService userCardService;
@Resource(name="custmerXFDao")
ICustmerXFDao custmerXFDao;
@Resource(name="")
IOrderProductDao orderProductDao;
@Resource(name="")
IProductDao productDao;
@Resource(name="accountDetailService")
IAccountDetailService accountDetailService;
@Resource(name="farewayDao")
IFareWayDao farewayDao;
@Resource(name="shoppingInfoDao")
IShoppingInfoDao shoppingInfoDao;
@Resource(name="dictionaryDao")
IDictionaryDao dictionaryDao;
/**
* 消费记录查询
* */
@RequestMapping(value="/member/consumptionQuery.do")
public ModelAndView query(HttpServletRequest request,HttpServletResponse response){
System.out.println("**************************8");
String st_time = request.getParameter("fromDate");
String ed_time = request.getParameter("endDate");
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
long memberId = currentUser.getId();
String hql =" from Custmerxf c ";
List parameter = new ArrayList();
if(st_time!=null&&st_time.length()!=0){
if(ed_time!=null&&ed_time.length()!=0){
hql += " where c.XFSJ>=str_to_date(?,'%Y-%m-%d %H:%i:%s') and c.XFSJ<=str_to_date(?,'%Y-%m-%d %H:%i:%s') ";
parameter.add(st_time);
parameter.add(ed_time);
}else{
hql += " where c.XFSJ>=str_to_date(?,'%Y-%m-%d %H:%i:%s') ";
parameter.add(st_time);
}
hql += " and c.xfhy.id= ?";
parameter.add(memberId);
}else{
if(ed_time!=null&&ed_time.length()!=0){
hql += " where c.XFSJ<=str_to_date(?,'%Y-%m-%d %H:%i:%s') ";
parameter.add(ed_time);
hql += " and c.xfhy.id= ?";
parameter.add(memberId);
}else{
hql += " where c.xfhy.id= ?";
parameter.add(memberId);
}
}
hql += " order by c.XFSJ desc";
PageList pageList = custmerXFDao.listCustmerXFByConditions(hql, parameter.toArray(), this.getPageInfo(request));
this.printJSON(response, pageList.toJSON());
return null;
}
/**
* 购物车
* */
@RequestMapping(value="/member/queryShoppCart.do")
public ModelAndView queryShoppCart(HttpServletRequest request,HttpServletResponse response){
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
String hql = " from Orders o where o.status="+ Orders.STATUS_CART +" and o.user.id = ?";
List<Orders> orderList = orderService.queryOrders(hql, new Object[]{currentUser.getId()});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
request.setAttribute("shopcarts", order);
}
return new ModelAndView(MemberURLConst.URL_SHOPCART);
}
private void printResult(HttpServletResponse response,String result){
PrintWriter pw;
try {
pw = response.getWriter();
pw.print(result);
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 清空购物车
* */
@RequestMapping(value="/member/clearShopCart.do")
public ModelAndView clearShopCart(HttpServletRequest request,HttpServletResponse response){
String orderId = request.getParameter("orderid");
if(!isNumber(orderId)){
this.printResult(response, "false");
return null;
}
String rd = request.getParameter("rd");
if(request.getSession().getAttribute("rd")==null||
!request.getSession().getAttribute("rd").equals(rd)){
request.getSession().setAttribute("rd", rd);
long oid = Long.parseLong(orderId.trim());
List<Orders> orderList = orderService.queryOrders("from Orders o where o.id=?", new Object[]{oid});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
order.setOrderProducts(new ArrayList<OrderProduct>());
orderService.updateOrder(order);
this.printResult(response, "ok");
return null;
}
}
this.printResult(response, "false");
return null;
}
@RequestMapping(value="/member/deleteOrderProduct.do")
public ModelAndView deleteOrderProduct(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------deleteOrderProduct------------------");
String orderProductId = request.getParameter("orderProductId");
String orderid = request.getParameter("orderid");
if(!isNumber(orderProductId)||!isNumber(orderid)){
printResult(response,"false");
return null;
}
String hql = " from Orders o where o.id = ?";
List<Orders> orderList = orderService.queryOrders(hql, new Object[]{Long.valueOf(orderid.trim())});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
int id = Integer.parseInt(orderProductId.trim());
OrderProduct op = order.getOrderProduct(id);
order.removeOrderProduct(id);
boolean ok = orderService.updateOrder(order);
orderProductDao.deleteOrderProduct(op);
if(ok){
printResult(response,"ok");
}else{
printResult(response,"false");
}
}
return null;
}
/**
* 订单查询
* */
@RequestMapping(value="/member/orderQuery.do")
public ModelAndView queryOrder(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------order------------------");
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
if(null==currentUser) {
this.printJSON(response, (new PageList()).toJSON());
return null;
}
String orderIdStr = request.getParameter("orderId");
if(orderIdStr==null||"".equals(orderIdStr.trim())){
String hql = " from Orders o where o.user.id = ? and o.status!="+Orders.STATUS_CART;
PageList pageList = orderService.queryOrders(hql, new Object[]{currentUser.getId()}, getPageInfo(request));
this.printJSON(response, pageList.toJSON());
return null;
}
if(!isNumber(orderIdStr)){
this.printJSON(response, (new PageList()).toJSON());
return null;
}
long id = Long.parseLong(orderIdStr.trim());
String hql = " from Orders o where o.user.id = ? and o.id=? and o.status!="+Orders.STATUS_CART;
PageList pageList = orderService.queryOrders(hql, new Object[]{currentUser.getId(),id}, getPageInfo(request));
this.printJSON(response, pageList.toJSON());
return null;
}
/**
* 计算运费
* */
@RequestMapping(value="/member/queryDelivery.do")
public ModelAndView queryDelivery(HttpServletRequest request,HttpServletResponse response){
String orderId = request.getParameter("orderId");
String addressId = request.getParameter("addressId");
String deliveryId = request.getParameter("deliveryId");
List<Orders> orders = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.parseLong(orderId.trim())});
if(null!=orders&&orders.size()>0){
Orders order = orders.get(0);
List<Address> addresses = addressService.getAddress("from Address a where a.id=?", new Object[]{Integer.parseInt(addressId.trim())});
if(null!=addresses&&addresses.size()>0){
Address addr = addresses.get(0);
order.setAddressprovince(addr.getProvince());
order.setAddresscity(addr.getCity());
order.setAddressregion(addr.getRegion());
order.setAddressname(addr.getAddress());
order.setAddresszipcode(addr.getZipcode());
order.setFareway(deliveryId);
double fare = FarewayUtil.getFare(order);
this.printResult(response, fare+"");
}
}
return null;
}
@RequestMapping(value="/member/gotoCheckout.do")
public ModelAndView gotoCheckout(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------confirmProduct------------------");
String strs[] = request.getParameterValues("orderProductId");
String orderid = request.getParameter("orderid");
List<Orders> orderList = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.valueOf(orderid)});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
List<OrderProduct> ops = order.getOrderProducts();
int totalAmount = 0;
double totalScore = 0.0;
if(null!=strs){
List<OrderProduct> tempList = new ArrayList<OrderProduct>();
for(int i=0;i<strs.length;i++){
OrderProduct op = parse(request,strs[i],ops);
if(null!=op){
tempList.add(op);
totalAmount += op.getAmount();
totalScore += op.getAmount()*op.getPrice();
}
}
order.setScore(totalScore);
//order.setStatus(Orders.STATUS_DEAL);
order.setOrderProducts(tempList);
boolean ok = orderService.updateOrder(order);
if(ok){
request.setAttribute("order",order);
Map<String, String> paramter = new HashMap<String, String>();
//查询用户的收货地址
String hql = " from Address a where a.user.id=?";
List<Address> addresses = addressService.getAddress(hql, new Object[]{RunTimeUser.getRunTimeUser(request).getId()});
request.setAttribute("addresses", addresses);
Address defaultAddress = getDefaultAddress(addresses);
request.setAttribute("currentAddress",defaultAddress);
List<FareWay> fws = getFareWays(tempList);
request.setAttribute("fareways",fws);
paramter.put("url", MemberURLConst.URL_CHECKOUT);
return new ModelAndView(MemberURLConst.URL_BASE,paramter); }
}
}
System.out.println("-----------------------------------------------------");
Map<String, String> paramter = new HashMap<String, String>();
paramter.put("url", MemberURLConst.URL_CHECKOUT);
return new ModelAndView(MemberURLConst.URL_BASE,paramter);
}
public List<FareWay> getFareWays(List<OrderProduct> ops){
List<FareWay> ways = new ArrayList<FareWay>();
if(null==ops)return ways;
Set<String> farewayId = new HashSet<String>();
Boolean flag1 = false;
Boolean flag2 = false;
Boolean flag3 = false;
for(int i=0;i<ops.size();i++){
Product product = ops.get(i).getProduct();
String fareWay = product.getFareway();
if(fareWay.contains("1"))
{
flag1 = true;
}
if("2".equals(fareWay.trim()))
{
flag2 = true;
}
if("3".equals(fareWay.trim()))
{
flag3 = true;
}
if(null!=fareWay&&!"".equals(fareWay.trim())){
String[] array = fareWay.split(";");
for(int j=0;j<array.length;j++){
if(!"".equals(array[j].trim()))farewayId.add(array[j].trim());
}
}
}
if(flag1&&(flag2||flag3))
{
farewayId.clear();
farewayId.add("1");
}
Iterator<String> it = farewayId.iterator();
while(it.hasNext()){
String id = it.next();
FareWay fw = farewayDao.getFareWayById(Integer.parseInt(id.trim()));
if(null!=fw)ways.add(fw);
}
return ways;
}
private Address getDefaultAddress(List<Address> addresses){
for(int i=0;i<addresses.size();i++){
if(1==addresses.get(i).getIsdefault())return addresses.get(i);
}
return null;
}
public OrderProduct parse(HttpServletRequest request,String orderProductId,List<OrderProduct> ops){
OrderProduct op = getOrderProduct(ops,orderProductId);
if(null!=op){
String amount = request.getParameter("amount"+orderProductId);
op.setAmount(Integer.parseInt(amount));
return op;
}
return null;
}
public OrderProduct getOrderProduct(List<OrderProduct> list,String id){
for(int i=0;i<list.size();i++){
OrderProduct op = list.get(i);
if((op.getId()+"").equals(id))return op;
}
return null;
}
@RequestMapping(value="/member/applyReturnProduct.do")
public ModelAndView applyReturnProduct(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------applyReturnProduct------------------");
return null;
}
@RequestMapping(value="/member/applyReturnOrder.do")
public ModelAndView applyReturnOrder(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------applyReturnOrder------------------");
return null;
}
private boolean isNumber(String orderStr){
if(orderStr==null)return false;
return orderStr.trim().matches("[\\d]+");
}
@RequestMapping(value="/member/collectionQuery.do")
public ModelAndView queryCollections(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------collection------------------");
return null;
}
/**
* 收货地址查询
* */
@RequestMapping(value="/member/addressQuery.do")
public ModelAndView showAddress(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------Address------------------");
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
String receiver = request.getParameter("receiver");
String mobile = request.getParameter("mobile");
if(null==currentUser) {
this.printJSON(response, (new PageList()).toJSON());
return null;
}
String hql = " from Address a where a.user.id = ?";
List list = new ArrayList();
list.add(currentUser.getId());
if(receiver!=null&&!"".equals(receiver.trim())){
hql += " and a.name like ?";
list.add("%"+receiver+"%");
}
if(mobile!=null&&!"".equals(mobile.trim())){
hql += " and a.tel like ?";
list.add("%"+mobile+"%");
}
PageList pageList = addressService.queryAddress(hql, list.toArray(), getPageInfo(request));
this.printJSON(response, pageList.toJSON());
return null;
}
/**
* 删除我的收货地址
* */
@RequestMapping(value="/member/deleteAddress.do")
public ModelAndView deleteAddress(HttpServletRequest request,HttpServletResponse response){
String addressId = request.getParameter("addressId");
boolean ok =false;
if(isNumber(addressId)){
ok = addressService.deleteAddress(Integer.parseInt(addressId.trim()));
}
Map<String,String> parameter = new HashMap<String, String>();
parameter.put("url", MemberURLConst.URL_ADDRESS);
return new ModelAndView(MemberURLConst.URL_BASE,parameter);
}
/**
* 添加我的收货地址/修改我的收获地址
* **/
@RequestMapping(value="/member/addAddress.do")
public ModelAndView addAddress(HttpServletRequest request,HttpServletResponse response){
String rd = request.getParameter("rd");
String cacheRd = (String) request.getSession().getAttribute("rd");
if(cacheRd==null||!cacheRd.equals(rd)){
String addressId = decodeParameter(request, "addressId");
Address addr = null;
boolean addFlag = true;
if(isNumber(addressId)){
addFlag = false;
int id = Integer.parseInt(addressId.trim());
List<Address> list = addressService.getAddress(" from Address a where a.id=?", new Object[]{id});
if(null!=list&&list.size()>0){
addr = list.get(0);
}
}else{
addFlag =true;
addr = new Address();
}
String isdefault = request.getParameter("isdefault");
if(null==isdefault||"".equals(isdefault.trim()))isdefault = "0";
String address = decodeParameter(request,"address");
String region =decodeParameter(request,"region");
String city = decodeParameter(request,"city");
String province = decodeParameter(request,"province");
String zipcode = decodeParameter(request,"zipcode");
String tel = decodeParameter(request,"tel");
String name = decodeParameter(request,"name");
String syn = decodeParameter(request,"syn");
Dictionary d0 = dictionaryDao.findByKindAndCode("province", province);
Dictionary d1 = dictionaryDao.findByKindAndCode("city", city);
Dictionary d2 = dictionaryDao.findByKindAndCode("county", region);
addr.setCity(d1 != null ? d1.getDETAIL():"");
addr.setAddress(address);
addr.setIsdefault(Integer.parseInt(isdefault.trim()));
addr.setName(name);
addr.setProvince(d0 != null ? d0.getDETAIL():"");
addr.setRegion(d2 != null ? d2.getDETAIL():"");
addr.setTel(tel);
addr.setZipcode(zipcode);
if(addFlag){
User user = userCardService.findUserById(RunTimeUser.getRunTimeUser(request).getId());
addr.setUser(user);
try{
boolean ok = addressService.addAddress(addr);
if(!ok){
request.setAttribute("errmsg", "收货地址修改失败");
request.setAttribute("url", MemberURLConst.URL_ADDRESS_ADD);
return new ModelAndView(MemberURLConst.URL_BASE);
}
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("errmsg", "收货地址修改失败");
request.setAttribute("url", MemberURLConst.URL_ADDRESS_ADD);
return new ModelAndView(MemberURLConst.URL_BASE);
}
if(!StringUtil.isNull(syn)){
JSONObject addrJson = new JSONObject();
try {
addrJson.put("id", addr.getId());
addrJson.put("address", addr.getAddress());
addrJson.put("province", addr.getProvince());
addrJson.put("city", addr.getCity());
addrJson.put("region", addr.getRegion());
addrJson.put("name", addr.getName());
addrJson.put("tel", addr.getTel());
addrJson.put("zipcode", addr.getZipcode());
} catch (JSONException e) {
e.printStackTrace();
}
this.printJSON(response, addrJson.toString());
}
}else{
try{
addressService.modifyAddress(addr);
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("errmsg", "收货地址修改失败");
request.setAttribute("url", MemberURLConst.URL_ADDRESS_ADD);
return new ModelAndView(MemberURLConst.URL_BASE);
}
}
request.getSession().setAttribute("rd",rd);
}
Map<String,String> paramter = new HashMap<String, String>();
paramter.put("url", MemberURLConst.URL_ADDRESS);
return new ModelAndView(MemberURLConst.URL_BASE,paramter);
}
private String decodeParameter(HttpServletRequest request ,String paramName){
if(paramName==null)return "";
String value = request.getParameter(paramName);
if(null==value)return "";
return value;
}
@RequestMapping(value="/member/modifyAddressIni.do")
public ModelAndView modifyAddressIni(HttpServletRequest request,HttpServletResponse response){
String addressId = request.getParameter("addressId");
if(isNumber(addressId)){
int id = Integer.parseInt(addressId.trim());
List<Address> list = addressService.getAddress(" from Address a where a.id=?", new Object[]{id});
if(null!=list&&list.size()>0){
Address address = list.get(0);
request.setAttribute("address", address);
request.setAttribute("url", MemberURLConst.URL_ADDRESS_ADD);
return new ModelAndView(MemberURLConst.URL_BASE);
}
}
return null;
}
/**
* 个人明细账户
* */
@RequestMapping(value="/member/accountDetailQuery.do")
public ModelAndView queryDetails(HttpServletRequest request,HttpServletResponse response){
System.out.println("****************queryDetails****************");
String fromDate = request.getParameter("fromDate");
String toDate = request.getParameter("toDate");
AccountDetailQueryForm form = new AccountDetailQueryForm();
form.setFromDate(fromDate);
form.setToDate(toDate);
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
PageArgument argment = this.getPageInfo(request);
PageList pageList = accountDetailService.queryAccountDetails(currentUser, argment, form);
this.printJSON(response, pageList.toJSON());
return null;
}
/**
* 修改个人密码
* */
@RequestMapping(value="/member/modifypwd.do")
public ModelAndView modifyLoginPasswd(HttpServletRequest request,HttpServletResponse response){
RunTimeUser currentUser = RunTimeUser.getRunTimeUser(request);
String paramId = request.getParameter("rd");
String rd = (String)request.getSession().getAttribute("rd");
if(rd!=null&¶mId.equals(rd)){
request.setAttribute("url", MemberURLConst.URL_PWD_MODIFY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
if(null==currentUser) {
return new ModelAndView("error");
}
String orignalPasswd = request.getParameter("orignalPasswd");
User authuser = userCardService.auth(new User(currentUser.getUsername(),orignalPasswd));
if(authuser==null){
request.setAttribute("url", MemberURLConst.URL_PWD_MODIFY);
request.setAttribute("errmsg", "原始密码不正确");
if (currentUser.getUsertype() != User.USER_TYPE_NORMAL) {
return new ModelAndView("/management/member/member_pwdmodify");
}else{
return new ModelAndView(MemberURLConst.URL_BASE);
}
}
String confirmPasswd = request.getParameter("confirmPasswd");
String newPwd = EncryptUtil.toMD5(confirmPasswd);
if(null!=newPwd){
newPwd = newPwd.toUpperCase();
}
authuser.setPassword(newPwd);
try{
userCardService.updateUser(authuser);
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("errmsg", "密码修改失败");
request.setAttribute("url", MemberURLConst.URL_PWD_MODIFY);
if (currentUser.getUsertype() != User.USER_TYPE_NORMAL) {
return new ModelAndView("/management/member/member_pwdmodify");
}else{
return new ModelAndView(MemberURLConst.URL_BASE);
}
}
RunTimeUser.getRunTimeUser(request).updateUser(authuser);
if (currentUser.getUsertype() != User.USER_TYPE_NORMAL) {
return new ModelAndView("/management/member/member_pwdmodify");
}
request.setAttribute("url", MemberURLConst.URL_PWD_MODIFY);
request.setAttribute("errmsg", "密码修改成功");
return new ModelAndView(MemberURLConst.URL_BASE);
}
@RequestMapping(value="/member/modifyPayPasswd.do")
public ModelAndView modifyPayPasswd(HttpServletRequest request,HttpServletResponse response){
return null;
}
/**
* 修改个人资料
* */
@RequestMapping(value="/member/modifyprofile.do")
public ModelAndView modifyProfile(HttpServletRequest request,HttpServletResponse response){
String email = request.getParameter("email");
String mobile = request.getParameter("mobile");
//String birthday = request.getParameter("birthday");
String truename = request.getParameter("truename");
String nickname = request.getParameter("nickname");
String sex = request.getParameter("sex");
String code = request.getParameter("validatecode");
if(null==code)code="";
String validateCode = (String) request.getSession().getAttribute("modifyinfo");
if(validateCode==null)validateCode="";
if("".equals(code.trim())||"".equals(validateCode.trim())){
request.setAttribute("errmsg", "手机验证码不正确");
request.setAttribute("url", MemberURLConst.URL_PERSONAL_MODIFY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
if(!code.trim().equals(validateCode.trim())){
request.setAttribute("errmsg", "手机验证码不正确");
request.setAttribute("url", MemberURLConst.URL_PERSONAL_MODIFY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
User user = userCardService.findUserById(RunTimeUser.getRunTimeUser(request).getId());
user.setEmail(email);
user.setMobile(mobile);
user.setTruename(truename);
user.setNickname(nickname);
user.setSex(Integer.parseInt(sex));
try{
userCardService.updateUser(user);
}catch (Exception e) {
request.setAttribute("errmsg", "个人资料修改失败");
request.setAttribute("url", MemberURLConst.URL_PERSONAL_MODIFY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
RunTimeUser.getRunTimeUser(request).updateUser(user);
request.getSession().setAttribute("cur", "li1");
return new ModelAndView(MemberURLConst.URL_BASE);
}
/**
* 提交订单 并跳转到支付方式选择页面
* */
@RequestMapping(value="/member/checkout.do")
public ModelAndView checkout(HttpServletRequest request,HttpServletResponse response){
//订单Id
String rd = request.getParameter("rd");
String oldrd = (String) request.getSession().getAttribute("rd");
//防止刷新重复提交
if(oldrd==null||!rd.equals(oldrd)){
request.getSession().setAttribute("rd", rd);
String orderId = request.getParameter("orderId");
ModelAndView shopcartView = new ModelAndView(MemberURLConst.URL_BASE);
if(isNumber(orderId)){
//配送方式Id
String deliveryId = request.getParameter("deliveryId");
String orderAddressId = request.getParameter("orderAddressId");
if(isNumber(deliveryId)&&isNumber(orderAddressId)){
List<Orders> orderList = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.parseLong(orderId.trim())});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
if(order.getStatus()>=Orders.STATUS_PAID){
//已付款
FareWay farway = farewayDao.getFareWayById(Integer.parseInt(deliveryId.trim()));
request.setAttribute("farway", farway);
request.setAttribute("order", order);
request.setAttribute("url", MemberURLConst.URL_ORDER_DETAIL);
return new ModelAndView(MemberURLConst.URL_BASE);
}
order.setConfirmtime(new Date());
Address addr = findAddressById(orderAddressId);
if(null!=addr){
order.setAdrreessname(addr.getName());
order.setAddresscity(addr.getCity());
order.setAddressname(addr.getAddress());
order.setAddressprovince(addr.getProvince());
order.setAddressregion(addr.getRegion());
order.setAddresstel(addr.getTel());
order.setAddresszipcode(addr.getZipcode());
}
order.setFareway(deliveryId);
String fare = request.getParameter("fare");
double farevalue =0.0;
if(fare==null)fare = "0";
try{
farevalue = Double.parseDouble(fare.trim());
}catch (Exception e) {
}
order.setFare(farevalue);
User user = userCardService.findUserById(RunTimeUser.getRunTimeUser(request).getId());
double balance = user.getCard().getScore();
List<OrderProduct> ops = judgeProductInventory(order);
this.orderService.updateOrder(order);
if(ops.size()>0){
//库存不足
StringBuffer sb = new StringBuffer();
for(int i=0;i<ops.size();i++){
sb.append(ops.get(i).getName()+"、");
}
sb.append("库存不足。");
request.setAttribute("errmsg", sb.toString());
request.setAttribute("url", "/member/queryShoppCart.do");
return shopcartView;
}else{
if(balance<order.getScore()){
//用户积分不够
request.setAttribute("errmsg", "对不起,您的积分不够。");
request.setAttribute("url", "/member/queryShoppCart.do");
return shopcartView;
}
//库存够
if(order.getFare()==0.00){
user.getCard().setScore(balance-order.getScore());
userCardService.updateUser(user);
order.setStatus(Orders.STATUS_PAID);
order.setPaytime(new Date());
orderService.updateOrder(order);
}else{
//调用支付宝接口
request.setAttribute("order", order);
try {
request.getRequestDispatcher("/payment.do").forward(request, response);
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
RunTimeUser.getRunTimeUser(request).updateUser(user);
FareWay farway = farewayDao.getFareWayById(Integer.parseInt(deliveryId.trim()));
request.setAttribute("farway", farway);
request.setAttribute("order", order);
request.setAttribute("url", MemberURLConst.URL_ORDER_DETAIL);
if("3".equals(deliveryId))
{
//交易完成,需要发送订单信息
List<OrderProduct> _ops = orderProductDao.findOrderProduct(order);
boolean flag = false;
for(OrderProduct _op : _ops)
{
if("1".equals(_op.getProduct().getCategory().getSendMsg()))
{
flag = true;
break;
}
}
String content = "";
int i=1;
for(OrderProduct _op : _ops)
{
if(_ops.size() == 1)
content += _op.getProduct().getName();
else
content +=i+"、"+ _op.getProduct().getName();
i++;
}
if(flag)
{
ShoppingInfo info = new ShoppingInfo();
info.setOrdersId(orderId);
info.setIsUsed(false);
info.setMobile(user.getMobile());
info.setOrderTime(order.getConfirmtime());
info.setTradeTime(new Date());
info.setTradeNode(System.currentTimeMillis()+"");
info.setContent(content);
this.shoppingInfoDao.createShoppingInfo(info);
//尊敬的乐共享会员,您已成功兑换***的体验*次,请体验时出示此信息。祝您体验愉快!客服电话400-8866756
//尊敬的会员,您在乐共享商城兑换的***订单号为*****,请您凭本信息兑换领取,感谢您对乐共享的支持。 【乐共享】
if(!StringUtil.isEmptyStr(user.getMobile()))
{
SendSms.sendSms(user.getMobile(), "尊敬的会员,您在乐共享商城兑换的"+content +"订单号为"+orderId+",请您凭本信息兑换领取,感谢您对乐共享的支持。");
}
// info.setMerchant(merchant)
}
}
return new ModelAndView(MemberURLConst.URL_BASE);
}
}
}
}
}
return null;
}
/**
* 判断购物车库存量
* */
private List<OrderProduct> judgeProductInventory(Orders order){
List<OrderProduct> orderPrducts = order.getOrderProducts();
List<OrderProduct> resultList = new ArrayList<OrderProduct>();
if(null!=orderPrducts&&orderPrducts.size()>0){
for(int i=0;i<orderPrducts.size();i++){
OrderProduct op = orderPrducts.get(i);
if(!judgeOrderproduct(op)){
resultList.add(op);
}
}
}
return resultList;
}
/**
* 判断购物车中某一商品的库存
* */
private boolean judgeOrderproduct(OrderProduct op){
Product product = productDao.getProductById(op.getProduct().getId());
if(product.getAmount()>=op.getAmount()){
return true;
}
return false;
}
private Address findAddressById(String id){
List<Address> address = addressService.getAddress("from Address a where a.id=?", new Object[]{Integer.parseInt(id)});
if(null!=address&&address.size()>0){
return address.get(0);
}
return null;
}
/**
* 去到申请退货的页面
* */
@RequestMapping(value="/member/toApplyReturn.do")
public ModelAndView applyReturnIni(HttpServletRequest request,HttpServletResponse response){
String orderId = request.getParameter("orderId");
if(!isNumber(orderId)) return null;
String pageNum = request.getParameter("pageNum");
String pageSize = request.getParameter("pageSize");
PageArgument argment = new PageArgument();
if(!isNumber(pageNum)){
argment.setCurPage(1);
}else{
argment.setCurPage(Integer.parseInt(pageNum.trim()));
}
if(!isNumber(pageSize)){
argment.setPageSize(10);
}else{
argment.setPageSize(Integer.parseInt(pageSize.trim()));
}
PageList pageList = orderProductDao.findByPage4Report(Long.parseLong(orderId.trim()), argment);
List<Orders> list = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.parseLong(orderId.trim())});
if(list!=null&&list.size()>0){
request.setAttribute("order", list.get(0));
}else{
return null;
}
request.setAttribute("pageList", pageList);
request.setAttribute("url", MemberURLConst.URL_ORDER_APPLY_RETURN);
return new ModelAndView(MemberURLConst.URL_BASE);
}
/**
* 去到申请退货理由的页面
* */
@RequestMapping(value="/member/toReturnReasonIni.do")
public ModelAndView toReturnReasonIni(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------------toReturnReasonIni----------------------------");
String orderId = request.getParameter("orderId");
if(!isNumber(orderId)) return null;
String[] returnProductIds = request.getParameterValues("returnProductId");
List<OrderProduct> returnOps = new ArrayList<OrderProduct>();
if(null!=returnProductIds){
for(int i=0;i<returnProductIds.length;i++){
OrderProduct op = orderProductDao.findOrderProductById(Integer.parseInt(returnProductIds[i].trim()));
if(null!= op)returnOps.add(op);
}
}
request.setAttribute("orderId", orderId);
request.setAttribute("returnOrderProduct", returnOps);
System.out.println("************************"+returnProductIds.length);
request.setAttribute("url", MemberURLConst.URL_ORDER_RETURN_REASON);
return new ModelAndView(MemberURLConst.URL_BASE);
}
/**
* 确认收货
* */
@RequestMapping(value="/member/confirmOrder.do")
public ModelAndView confirmOrder(HttpServletRequest request,HttpServletResponse response){
System.out.println("--------------------------toReturnReasonIni----------------------------");
String orderId = request.getParameter("orderId");
if(!isNumber(orderId)) return null;
List<Orders> orderList = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.parseLong(orderId.trim())});
if(null!=orderList&&orderList.size()>0){
Orders order = orderList.get(0);
order.setConfirmtime(new Date());
order.setStatus(Orders.STATUS_CONFIRM);
orderService.updateOrder(order);
}
request.setAttribute("url", MemberURLConst.URL_ORDER_QUERY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
/**
* 提交退货申请
* */
@RequestMapping(value="/member/applyReturn.do")
public ModelAndView applyReturn(HttpServletRequest req,HttpServletResponse response){
System.out.println("--------------------------applyReturn----------------------------");
DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest)req;
String[] ids = request.getParameterValues("returnOrderProductId");
ProductImage pi1 = null;
ProductImage pi2 = null;
ProductImage pi3 = null;
if(ids!=null&&ids.length>0){
try{
String orderId = request.getParameter("orderId");
ReturnRequest rr = new ReturnRequest();
String reason = request.getParameter("reason");
String descripion = request.getParameter("descripion");
rr.setReason(reason);
pi1 = fileUpload(request,"proof1");
if(null!=pi1)rr.setProof1(pi1);
pi2 = fileUpload(request,"proof2");
if(null!=pi1)rr.setProof2(pi2);
pi3 = fileUpload(request,"proof3");
if(null!=pi1)rr.setProof3(pi3);
rr.setDescripion(descripion);
List<Orders> orderList = orderService.queryOrders("from Orders o where o.id=?", new Object[]{Long.parseLong(orderId.trim())});
Orders o = orderList.get(0);
rr.setRelatedorderid(o.getId());
Orders order= new Orders();
order.setAddresscity(o.getAddresscity());
order.setAddressname(o.getAddressname());
order.setAddressprovince(o.getAddressprovince());
order.setAddressregion(o.getAddressregion());
order.setAddresstel(o.getAddresstel());
order.setAddresszipcode(o.getAddresszipcode());
order.setAdrreessname(o.getAddressname());
order.setReturnrequest(rr);
rr.setOrders(order);
order.setFare(o.getFare());
order.setFareway(o.getFareway());
User user = new User();
user.setId(RunTimeUser.getRunTimeUser(request).getId());
order.setUser(user);
order.setTime(new Date());
double returnScore = 0;
for(int i=0;i<ids.length;i++){
OrderProduct op = orderProductDao.findOrderProductById(Integer.parseInt(ids[i].trim()));
op.setIsapplyreturn(OrderProduct.APPLY_RETURN_YES);
OrderProduct newObj = new OrderProduct();
BeanUtils.copyProperties(op, newObj);
newObj.setId(0);
newObj.setProduct(productDao.getProductById(op.getProduct().getId()));
newObj.setOrders(order);
returnScore +=newObj.getAmount()*newObj.getPrice();
order.addOrderProduct(newObj);
orderProductDao.update(op);
}
order.setStatus(Orders.STATUS_APPLY_RETURN);
o.setStatus(Orders.STATUS_CONFIRM);
order.setScore(returnScore);
orderService.createOrders(order);
orderService.updateOrder(o);
}catch(Exception e){
e.printStackTrace();
deleteFile(pi1);
deleteFile(pi2);
deleteFile(pi3);
}
}
request.setAttribute("url", MemberURLConst.URL_ORDER_QUERY);
return new ModelAndView(MemberURLConst.URL_BASE);
}
private void deleteFile(ProductImage pi){
if(null!=pi){
File file = new File(pi.getSourceURL());
if(null!=file&&file.exists())file.delete();
}
}
private ProductImage fileUpload(MultipartHttpServletRequest multipartRequest,String key){
Map<String,MultipartFile> maps = multipartRequest.getFileMap();
MultipartFile file = maps.get(key);
try {
if(null==file)return null;
String name = file.getOriginalFilename();
if(null==name||"".equals(name.trim()))return null;
String[] names = name.split("\\"+System.getProperty("file.separator"));
name = names[names.length-1];
names = name.split("\\.");
name = names[names.length-2];
ProductImage productImage = new ProductImage();
productImage.setDate(new Date());
productImage.setDescription(name);
name = productImage.getDate().getTime()+"";
productImage.setName(name);
String uploadPath = ImageUtils.getUploadPath();
String sourcePath = uploadPath + System.getProperty("file.separator") + name+".jpg";
file.transferTo(new File(sourcePath));
String[] path = sourcePath.split("\\"+System.getProperty("file.separator"));
sourcePath = path[path.length-3]+"/"+ path[path.length-2]+"/"+ path[path.length-1];
productImage.setSourceURL(sourcePath);
return productImage;
//ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//IGatewayService gatewayService = (IGatewayService) ac.getBean("gatewayService");
//gatewayService.createProductImage(productImage);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/* private void copyOrderProduct(OrderProduct source,OrderProduct target){
target.setAmount(source.getAmount());
target.setAreacategoryname(areacategoryname);
target.setBrand(brand);
target.setCategoryname(categoryname);
target.setClothessize(clothessize);
target.setColor(color);
target.setDescription(description);
target.setImage(image);
target.setIsapplyreturn(isapplyreturn);
target.setName(name);
target.setPrice(price);
target.setShoesize(shoesize);
target.setUrl(url);
}*/
}