/**
 * Description: CmOrder控制器
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-10 下午 17:06:17
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-10   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.house365.beans.entity.CmProductStatEntity;
import com.house365.web.util.ExcelUtil;
import com.house365.ws.beans.request.CmProductStatListRequest;
import com.house365.ws.beans.response.CmProductStatListResponse;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.house365.beans.entity.CmOrderEntity;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmOrderVo;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.CityUtil;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmOrderListRequest;
import com.house365.ws.beans.request.CmOrderRequest;
import com.house365.ws.beans.response.CmOrderListResponse;
import com.house365.ws.beans.response.CmOrderResponse;
import com.house365.ws.interfaces.server.ICmOrder;
import com.house365.ws.system.ReturnAppResult;

/**
 * CmOrder控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/cmorder")
public class CmOrderController extends BaseController {

    /**
     * 自动注入CmOrderWS实现
     */
    @Autowired
    private ICmOrder cmOrder;

    /**
     * 去新增CmOrder
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增CmOrder
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmOrder(
        @Valid CmOrderVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmOrderEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmOrderRequest request = new CmOrderRequest();
                request.setEntity(entity);
                CmOrderResponse response = cmOrder.addCmOrder(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmorder/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    CmOrderResponse response = cmOrder.deleteCmOrderById(Integer.valueOf(ids[i]));
                }
            } else {
                CmOrderResponse response = cmOrder.deleteCmOrderById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CmOrderResponse response = cmOrder.getCmOrderById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        CmOrderResponse response = cmOrder.getCmOrderById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 去修改CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/deliverUpdate", method = {RequestMethod.POST})
    @ResponseBody
    public String deliverUpdate(
        Integer id, String orderNumber, String selectReceiveType, String expressCompany, Model model
    ) {
        if ("1".equals(selectReceiveType)) {
            selectReceiveType = "快递";
        } else if ("0".equals(selectReceiveType)) {
            selectReceiveType = "自提";
        }
        House365RestResponse<CmOrderVo> orderResponse = new House365RestResponse<CmOrderVo>();
        CmOrderResponse response = cmOrder.getCmOrderById(id);
        CmOrderEntity entity = response.getEntity();
        entity.setDeliverType(selectReceiveType);
        entity.setExpressCompany(expressCompany);
        entity.setOerderNumber(orderNumber);
        entity.setOrderStatus(1);
        try {
            CmOrderRequest request = new CmOrderRequest();
            request.setEntity(entity);
            @SuppressWarnings("unused") CmOrderResponse rersponse = cmOrder.updateCmOrder(request);
            orderResponse.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            orderResponse.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
            return JSONObject.fromObject(orderResponse).toString();
        } catch (Exception ex) {
            orderResponse.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            orderResponse.setMsg(ex.getMessage());
            return JSONObject.fromObject(orderResponse).toString();
        }
    }


    /**
     * 去查看实体奖品CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/order/{id}", method = {RequestMethod.GET})
    public String updateOrderForm(@PathVariable(value = "id") Integer id, Model model) {
        CmOrderResponse response = cmOrder.getCmOrderById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "editorder");
        return getAutoUrl("orderForm");
    }

    /**
     * 去查看虚拟奖品CmOrder
     *
     * @param id CmOrder页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/virtualorder/{id}", method = {RequestMethod.GET})
    public String updateVirtualOrderForm(@PathVariable(value = "id") Integer id, Model model) {
        CmOrderResponse response = cmOrder.getCmOrderById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "editorder");
        return getAutoUrl("virtualOrderForm");
    }


    /**
     * 修改CmOrder
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmOrder(
        @Valid CmOrderVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
        Model model
    ) {
        CmOrderEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmOrderRequest request = new CmOrderRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") CmOrderResponse rersponse = cmOrder.updateCmOrder(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmorder/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询CmOrder
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        CmOrderListRequest listRequest = new CmOrderListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("create_time ");
        //获取城市列表
        List<KlfCityEntity> cityList = CityUtil.getCityList();
        model.addAttribute("cityList", cityList);
        //listRequest.setOrderMode("desc");
        CmOrderListResponse response = cmOrder.getCmOrderList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmOrders", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }


    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(Model model, HttpServletRequest request, HttpServletResponse response) {
        final String[] excelTitles = {"订单编号", "商品名称", "商品类型", "会员ID", "登录名", "会员手机", "状态", "组织", "下单时间"};
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(10000);
        page.setCurrentPage(1);
        CmOrderListRequest listRequest = new CmOrderListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("create_time ");
        //获取城市列表
        List<KlfCityEntity> cityList = CityUtil.getCityList();
        model.addAttribute("cityList", cityList);
        //listRequest.setOrderMode("desc");
        CmOrderListResponse listResponse = cmOrder.getCmOrderList(listRequest);
        List<List<Object>> recordList = new ArrayList<>();
        for (CmOrderEntity entity : listResponse.getObjectList()) {
            List<Object> record = new ArrayList<>();
            record.add(entity.getId());
            record.add(entity.getGoodsName());
            record.add(entity.getGoodsType() == 1 ? "虚拟" : "实物");
            record.add(entity.getUserId());
            record.add(entity.getUserName());
            record.add(entity.getUserPhone());
            record.add(entity.getOrderStatus() == 1 ? "已完成" : "未配送");
            record.add(entity.getCityName());
            record.add(entity.getCreateTime());
            recordList.add(record);
        }
        ExcelUtil.exportExcel("订单导出.xlsx", "订单导出", excelTitles, recordList, response);
    }


    /**
     * 查询CmOrder
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "totalQueryList", method = RequestMethod.GET)
    public String statisticsQuery(Integer number, Model model, HttpServletRequest request) {
        /*// 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(
                request, "search_");
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        String userRole = String.valueOf(request.getSession().getAttribute(CmConstant.USER_ROLE));
        if(!userRole.equals(CmConstant.ROLE_ADMIN)){
            searchParams.put("EQ_cityKey", request.getSession().getAttribute(CmConstant.CITY_KEY).toString());
        }
        CmOrderListRequest listRequest = new CmOrderListRequest();
        listRequest.setPaging(page);
        searchParams.put("EQ_groupByGoodsId", "goods_id");
        listRequest.setSearchParams(searchParams);
        CmOrderListResponse response = cmOrder.getCmOrderStatisticsList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmOrders", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));*/
        return "redirect:/cmcreditgoods/listCreditsOfAll";//getAutoUrl("totalQueryList");
    }
}
