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

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.DictionaryEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.DictionaryVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.DictionaryListRequest;
import com.house365.ws.beans.request.DictionaryRequest;
import com.house365.ws.beans.response.DictionaryListResponse;
import com.house365.ws.beans.response.DictionaryResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.IDictionary;
import org.apache.commons.collections4.CollectionUtils;
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.*;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    /**
     * 自动注入DictionaryWS实现
     */
    @Autowired
    private IDictionary dictionary;

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

    /**
     * 新增Dictionary
     *
     * @param vo      Dictionary页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createDictionary(@Valid DictionaryVo vo, BindingResult result, HttpServletRequest request, Model model) {
        DictionaryEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        entity.setCity(departmentEntity.getDescripition());
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                DictionaryRequest dictionaryRequest = new DictionaryRequest();
                dictionaryRequest.setEntity(entity);
                DictionaryResponse response = dictionary.addDictionary(dictionaryRequest);
                Integer id = response.getEntity().getId();
                return "redirect:/dictionary/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }


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

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

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

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

    /**
     * 查询Dictionary
     *
     * @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();
        if (null != number) {
            page.setCurrentPage(number);
        }
        DictionaryListRequest listRequest = new DictionaryListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        DictionaryListResponse response = dictionary.getDictionaryList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("dictionarys", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 查询Dictionary
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/removeTime/removeTimeList", method = RequestMethod.GET)
    public String removeTimeList(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = new HashMap<>();
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        searchParams.put("EQ_city", departmentEntity.getDescripition());
        searchParams.put("LIKE_dicKey", "customer.remove.days");
        DictionaryListRequest listRequest = new DictionaryListRequest();
        listRequest.setOrderMode("asc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        DictionaryListResponse response = dictionary.getDictionaryList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("dictionarys", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl("removeTimeList");
    }

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

    /**
     * 新增Dictionary
     *
     * @param vo      Dictionary页面表单对象
     * @param result  表单验证数据
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/removeTime", method = {RequestMethod.POST})
    public String removeTimeSetting(@Valid DictionaryVo vo, BindingResult result, HttpServletRequest request,
                                    RedirectAttributes redirectAttributes, Model model) {
        DictionaryEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        entity.setCity(departmentEntity.getDescripition());
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return "redirect:/dictionary/removeTime/removeTimeList";
        } else {
            try {
                Map<String, Object> searchParams = new HashMap<>();
                searchParams.put("EQ_dicKey", entity.getDicKey());
                searchParams.put("EQ_city", entity.getCity());
                DictionaryListRequest listRequest = new DictionaryListRequest();
                listRequest.setSearchParams(searchParams);
                DictionaryListResponse listResponse = dictionary.getDictionaryList(listRequest);
                if (listResponse.getObjectList() != null && listResponse.getObjectList().size() != 0) {
                    model.addAttribute("action", "create");
                    addErrorMessage(model, "该设置已存在");
                    return getAutoUrl("removeTimeSetting");
                }

                DictionaryRequest dictionaryRequest = new DictionaryRequest();
                dictionaryRequest.setEntity(entity);
                DictionaryResponse response = dictionary.addDictionary(dictionaryRequest);
                Integer id = response.getEntity().getId();
                return "redirect:/dictionary/removeTime/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("removeTimeSetting");
            }
        }
    }

    /**
     * 去查看Dictionary
     *
     * @param id Dictionary页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/removeTime/{id}", method = {RequestMethod.GET})
    public String showRemoveTimeForm(@PathVariable(value = "id") Integer id, Model model) {
        DictionaryResponse response = dictionary
                .getDictionaryById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("removeTimeSetting");
    }

    /**
     * 去修改Dictionary
     *
     * @param id Dictionary页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/removeTime/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateRemoveTimeForm(@PathVariable(value = "id") Integer id, Model model) {
        DictionaryResponse response = dictionary
                .getDictionaryById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("removeTimeSetting");
    }

    /**
     * 修改Dictionary
     *
     * @param vo     Dictionary页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/removeTime/{id}", method = {RequestMethod.POST})
    public String updateRemoveTimeDictionary(@Valid DictionaryVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model) {
        DictionaryEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("removeTimeSetting");
        } else {
            try {
                DictionaryRequest request = new DictionaryRequest();
                request.setEntity(entity);

                @SuppressWarnings("unused")
                DictionaryResponse rersponse = dictionary.updateDictionary(request);
                addSuccessMessage(model, "更新成功");
                return getAutoUrl("removeTimeSetting");
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    @RequestMapping(value = "/getDictList")
    @ResponseBody
    public HResult getDictList() {
        HResult result = new HResult();
        try {
            String key = "crm_visit_result";
            List<DictionaryEntity> list = dictionary.getListByKey(key);
            List<DictionaryEntity> newList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                for (DictionaryEntity entity : list) {
                    String dicValue = entity.getDicValue();
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(dicValue)) {
                        int value = Integer.parseInt(dicValue);
                        if (value < 5) {
                            newList.add(entity);
                        }
                    }
                }
            }
            result.setData(newList);
        } catch (Exception e) {
            result.setStatus(101);
            result.setErrorMessage("获取配置list失败");
            e.printStackTrace();
            logger.error("获取配置list失败", e);
        }
        return result;
    }

}
