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

import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmUserVo;
import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.CityUtil;
import com.house365.web.util.Constant;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmUserListRequest;
import com.house365.ws.beans.request.CmUserRequest;
import com.house365.ws.beans.response.CmUserListResponse;
import com.house365.ws.beans.response.CmUserResponse;
import com.house365.ws.interfaces.server.ICmUser;
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.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

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

    /**
     * 自动注入CmUserWS实现
     */
    @Autowired
    private ICmUser cmUser;

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

    /**
     * 新增CmUser
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmUser(
            @Valid CmUserVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmUserEntity 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 {
                CmUserRequest request = new CmUserRequest();
                request.setEntity(entity);
                CmUserResponse response = cmUser.addCmUser(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmuser/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除CmUser
     *
     * @param id CmUser页面表单对象唯一标识
     * @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++) {
                    cmUser.deleteCmUserById(Integer.valueOf(ids[i]));
                }
            } else {
                cmUser.deleteCmUserById(Integer.valueOf(id));
            }
        }
    }

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

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

    /**
     * 修改CmUser
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmUser(
            @Valid CmUserVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model
    ) {
        CmUserEntity 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 {
                CmUserRequest request = new CmUserRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") CmUserResponse rersponse = cmUser.updateCmUser(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmuser/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询CmUser
     *
     * @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);
        }
        CmUserListRequest listRequest = new CmUserListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CmUserListResponse response = cmUser.getCmUserList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmUsers", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 查询CmUser
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "remainingCreditsList", method = RequestMethod.GET)
    public String remainingCreditsList(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        if (searchParams.get("EQ_cityId") == null || org.apache.commons.lang3.StringUtils.isBlank(searchParams.get("EQ_cityId").toString())) {
            String cityKey = (String) request.getSession().getAttribute(CmConstant.CITY_KEY);
            searchParams.put("EQ_cityId", cityKey);
        }
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
//        List<KlfCityEntity> cityList = CityUtil.getCityList();
        //调用新接口，查询用户城市信息
        String userName =  String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
        List<KlfCityEntity> cityList = CityUtil.getCityListNew(userName);
        model.addAttribute("cityList", cityList);
        CmUserListRequest listRequest = new CmUserListRequest();
        listRequest.setPaging(page);
        //设定排序
        Object ocObj = request.getParameter("orderColumn");
        if (ocObj != null && !"".equals(ocObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
        } else {
            listRequest.setOrderColumn("credits");
        }
        Object omObj = request.getParameter("orderMode");
        if (omObj != null && !"".equals(omObj.toString().trim())) {
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderMode(Constant.DESC);
        }
        searchParams.put("EQ_creditsNotNull", "notnull");
        listRequest.setSearchParams(searchParams);

        Integer userCount = cmUser.countAllCreditsNotNull();
        Integer remainingCredits = cmUser.countAllRemainingCredits();

        CmUserListResponse response = cmUser.getCmUserList(listRequest);
        for (CmUserEntity userEntity : response.getObjectList()) {
            for (KlfCityEntity city : cityList) {
                if (userEntity.getCityId() != null && city.getCode() != null && city.getCode().equals(userEntity.getCityId())) {
                    userEntity.setCityId(city.getName());
                }
            }
        }

        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmUsers", response.getObjectList());
        model.addAttribute("userCount", userCount);
        model.addAttribute("remainingCredits", remainingCredits);

        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }
}
