/**
 * Description: 客户活动来源控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-18 上午 08:58:25
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-18   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.CustomerSourceEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CustomerSourceVo;
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.CustomerSourceListRequest;
import com.house365.ws.beans.request.CustomerSourceRequest;
import com.house365.ws.beans.response.CustomerSourceListResponse;
import com.house365.ws.beans.response.CustomerSourceResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.ICustomerSource;
import com.house365.ws.interfaces.server.IDepartment;
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.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户活动来源控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-18
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/customersource")
public class CustomerSourceController extends BaseController {

    /**
     * 自动注入客户活动来源WS实现
     */
    @Autowired
    private ICustomerSource customerSource;

    @Autowired
    private IDepartment department;

    @Autowired
    private ICustomer customer;

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

    /**
     * 新增客户活动来源
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCustomerSource(
            @Valid CustomerSourceVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model,
            HttpServletRequest request
    ) {
        CustomerSourceEntity 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 {
                UserEntity userEntity = (UserEntity) request.getSession().getAttribute(
                        SessionConstants.THREAD_USER_KEY);
                DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                        SessionConstants.SESSION_CURRNET_DEPT_KEY);
                String cityId = departmentEntity.getCityID();
                DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
                DepartmentEntity city = departmentResponse.getEntity();

                Map<String, Object> sm = new HashMap<>(10);
                sm.put("EQ_sourceName", entity.getSourceName());
                sm.put("EQ_city", city.getDescripition());
                sm.put("EQ_status", "1");
                CustomerSourceListRequest csl = new CustomerSourceListRequest();
                csl.setSearchParams(sm);
                CustomerSourceListResponse lr = customerSource.getCustomerSourceList(csl);
                if (lr.getObjectList() != null && !lr.getObjectList().isEmpty()) {
                    model.addAttribute("action", "create");
                    addErrorMessage(model, "名称已存在！");
                    return getAutoUrl("form");
                }

                entity.setSourceName(StringUtils.StringFilter(entity.getSourceName()));
                entity.setStatus(1);
                entity.setCreateTime(new Date());
                entity.setCreater(userEntity.getRealName());
                entity.setCity(city.getDescripition());
                entity.setSource("SYSTEM");
                CustomerSourceRequest csr = new CustomerSourceRequest();
                csr.setEntity(entity);
                CustomerSourceResponse response = customerSource.addCustomerSource(csr);
                Integer id = response.getEntity().getId();
                return "redirect:/customersource/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除客户活动来源
     *
     * @param id 客户活动来源页面表单对象唯一标识
     * @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++) {
                    customerSource.deleteCustomerSourceById(Integer.valueOf(ids[i]));
                }
            } else {
                customerSource.deleteCustomerSourceById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看客户活动来源
     *
     * @param id 客户活动来源页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CustomerSourceResponse response = customerSource.getCustomerSourceById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

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

    /**
     * 修改客户活动来源
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCustomerSource(
            @Valid CustomerSourceVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CustomerSourceEntity 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 {
                CustomerSourceResponse csr = customerSource.getCustomerSourceById(entity.getId());

                Map<String, Object> sm = new HashMap<>(10);
                sm.put("EQ_sourceName", entity.getSourceName());
                sm.put("EQ_city", entity.getCity());
                sm.put("NOTEQ_id", entity.getId());
                sm.put("EQ_status", "1");
                CustomerSourceListRequest csl = new CustomerSourceListRequest();
                csl.setSearchParams(sm);

                CustomerSourceListResponse lr = customerSource.getCustomerSourceList(csl);
                if (lr.getObjectList() != null && !lr.getObjectList().isEmpty()) {
                    model.addAttribute("action", "create");
                    redirectAttributes.addAttribute("message", "名称已存在");
                    return "redirect:/customersource/" + entity.getId() + "?action=edit";
                }
                entity.setCreateTime(csr.getEntity().getCreateTime());
                CustomerSourceRequest request = new CustomerSourceRequest();
                request.setEntity(entity);
                customerSource.updateCustomerSource(request);

                customer.updateSourceName(String.valueOf(entity.getId()), entity.getSourceName());

                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/customersource/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询客户活动来源
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);
        String cityId = departmentEntity.getCityID();
        DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
        DepartmentEntity city = departmentResponse.getEntity();

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        searchParams.put("EQ_status", "1");
        searchParams.put("EQ_city", city.getDescripition());
        CustomerSourceListRequest listRequest = new CustomerSourceListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("sort");
        listRequest.setOrderMode("desc");
        CustomerSourceListResponse response = customerSource.getCustomerSourceList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("customerSources", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }
}
