/**
 * Description: CrmSource控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-09 下午 16:02:32
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-09   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.CrmSourceEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CrmSourceVo;
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.CrmSourceListRequest;
import com.house365.ws.beans.request.CrmSourceRequest;
import com.house365.ws.beans.response.CrmSourceListResponse;
import com.house365.ws.beans.response.CrmSourceResponse;
import com.house365.ws.interfaces.server.ICrmSource;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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.*;

/**
 * CrmSource控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-09
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/crmsource")
public class CrmSourceController extends BaseController {

    /**
     * 自动注入CrmSourceWS实现
     */
    @Autowired
    private ICrmSource crmSource;

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

    /**
     * 新增CrmSource
     *
     * @param vo     CrmSource页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCrmSource(
            @Valid CrmSourceVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CrmSourceEntity 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 {
                CrmSourceRequest request = new CrmSourceRequest();
                request.setEntity(entity);
                CrmSourceResponse response = crmSource.addCrmSource(request);
                Integer id = response.getEntity().getId();
                return "redirect:/crmsource/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

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

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

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

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

    /**
     * 查询CrmSource
     *
     * @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);
        }
        CrmSourceListRequest listRequest = new CrmSourceListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CrmSourceListResponse response = crmSource.getCrmSourceList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("crmSources", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "treeList", method = RequestMethod.GET)
    public String treeList(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        CrmSourceListRequest listRequest = new CrmSourceListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CrmSourceListResponse response = crmSource.getCrmSourceList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("crmSources", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl("list");
    }

    @RequestMapping(value = "ajax/load", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object load(HttpServletRequest request, @RequestParam(value = "id", required = false) String categoryId, String choseIds) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String city = departmentEntity.getDescripition();

        List<CrmSourceEntity> models;
        Page page = new Page();
        page.setPageSize(Integer.MAX_VALUE);
        CrmSourceListRequest req = new CrmSourceListRequest();
        req.setPaging(page);
        Map<String, Object> parameter = new HashMap<>(10);

        parameter.put("EQ_categoryId", categoryId);

        req.setSearchParams(parameter);
        models = crmSource.getCrmSourceList(req).getObjectList();

        String[] choseIdArray = choseIds.split(",");
        Set choseIdsSet = new HashSet();
        Collections.addAll(choseIdsSet, choseIdArray);
        //南京站新需求 过滤400来电562 和房博士im咨询99  //CRM已经限制，全链条无需限制
//        if (CollectionUtils.isNotEmpty(models) && "nj".equals(city)) {
//            models.removeIf(m -> m.getSourceId() == 99 || m.getSourceId() == 562);
//        }
        JSONArray sources = new JSONArray();
        for (CrmSourceEntity model : models) {
            JSONObject source = new JSONObject();
            source.put("id", model.getSourceId());
            source.put("pId", model.getCategoryId());
            source.put("name", model.getSourceName());
            if (choseIdsSet.contains(model.getSourceId().toString())) {
                source.put("checked", "true");
            } else {
                source.put("checked", "false");
            }
            sources.add(source);
        }

        return JSONArray.fromObject(sources).toString();
    }
}
