/**
 * Description: 抢客规则控制器
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-11-28 下午 13:41:47
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-11-28   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.beust.jcommander.internal.Lists;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.RushCustomerRuleVo;
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.DepartmentListRequest;
import com.house365.ws.beans.request.ProjectListRequest;
import com.house365.ws.beans.request.RushCustomerRuleListRequest;
import com.house365.ws.beans.request.RushCustomerRuleRequest;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.*;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 抢客规则控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-11-28
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/rushcustomerrule")
public class RushCustomerRuleController extends BaseController {

    /**
     * 自动注入抢客规则WS实现
     */
    @Autowired
    private IRushCustomerRule rushCustomerRule;
    @Autowired
    private IProject project;
    @Autowired
    private IDepartment department;
    @Autowired
    private ICrmSource crmSource;
    @Autowired
    private IDictionary dictionary;

    /**
     * 去新增抢客规则
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model, HttpServletRequest request) {

        List<ProjectEntity> projects = project.getProjectList(new ProjectListRequest()).getObjectList();
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentResponse departmentResponse = department.getDepartmentById(userEntity.getDeptId());
        map.put("REGEXP_urlPath", "^" + departmentResponse.getEntity().getUrlPath() + "$|^" + departmentResponse.getEntity().getUrlPath() + "/");
        map.put("EQ_rushRule", 1);
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> departments = resp.getObjectList();

        CrmSourceListResponse sourcesResp = crmSource.getRushCrmSourceList(departmentResponse.getEntity().getDescripition());

        List<DictionaryEntity> dictionaries = dictionary.getListByKey("customer.active.time");

        model.addAttribute("dictionaries", dictionaries);
        model.addAttribute("sources", sourcesResp.getObjectList());
        model.addAttribute("departments", departments);

        model.addAttribute("action", "create");
        model.addAttribute("projects", projects);
        return getAutoUrl("form");
    }

    /**
     * 新增抢客规则
     *
     * @param vo     抢客规则页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createRushCustomerRule(@Valid RushCustomerRuleVo vo, BindingResult result,
                                         RedirectAttributes redirectAttributes, Model model, HttpServletRequest httpRequest) {
        RushCustomerRuleEntity 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) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                DepartmentEntity departmentEntity = (DepartmentEntity) httpRequest.getSession().getAttribute(
                        SessionConstants.SESSION_CURRNET_DEPT_KEY);

                RushCustomerRuleRequest request = new RushCustomerRuleRequest();
                entity.setStatus(0);
                entity.setCreateTime(new Date());
                entity.setCreateUserName(userEntity.getRealName());
                entity.setCreateUserId(userEntity.getId());
                entity.setCityCode(departmentEntity.getDescripition());
                request.setEntity(entity);
                RushCustomerRuleResponse response = rushCustomerRule
                        .addRushCustomerRule(request);
                Integer id = response.getEntity().getId();
                return "redirect:/rushcustomerrule/" + 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++) {
                    rushCustomerRule.deleteRushCustomerRuleById(Integer.valueOf(ids[i]));
                }
            } else {
                rushCustomerRule.deleteRushCustomerRuleById(Integer.valueOf(id));
            }
        }
    }

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

    /**
     * 去修改抢客规则
     *
     * @param id      抢客规则页面表单对象唯一标识
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model, HttpServletRequest request) {
        RushCustomerRuleResponse response = rushCustomerRule
                .getRushCustomerRuleById(id);

        List<ProjectEntity> projects = project.getProjectList(new ProjectListRequest()).getObjectList();
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentResponse departmentResponse = department.getDepartmentById(userEntity.getDeptId());
        map.put("REGEXP_urlPath", "^" + departmentResponse.getEntity().getUrlPath() + "$|^" + departmentResponse.getEntity().getUrlPath() + "/");
        map.put("EQ_rushRuleId", id);
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> departments = resp.getObjectList();

        RushCustomerRuleEntity rushCustomerRule = response.getEntity();

        CrmSourceListResponse sourcesResp = crmSource.getRushCrmSourceList(departmentResponse.getEntity().getDescripition());

        List<DictionaryEntity> dictionaries = dictionary.getListByKey("customer.active.time");

        if (StringUtils.isNotBlank(rushCustomerRule.getDepartment())) {
            for (DepartmentEntity dept : departments) {
                dept.setType("0");
                for (String deptm : Lists.newArrayList(rushCustomerRule.getDepartment().split(","))) {
                    if (deptm.equals(dept.getId().toString())) {
                        dept.setType("1");
                        break;
                    } else {
                        dept.setType("0");
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(rushCustomerRule.getSource())) {
            for (CrmSourceEntity crmSource : sourcesResp.getObjectList()) {
                crmSource.setFlag(false);
                for (String sourceStr : Lists.newArrayList(rushCustomerRule.getSource().split(","))) {
                    if (sourceStr.equals(String.valueOf(crmSource.getSourceId()))) {
                        crmSource.setFlag(true);
                        break;
                    } else {
                        crmSource.setFlag(false);
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(rushCustomerRule.getActiveTime())) {
            for (DictionaryEntity dictionary : dictionaries) {
                dictionary.setCity("0");
                for (String activeStr : Lists.newArrayList(rushCustomerRule.getActiveTime().split(","))) {
                    if (activeStr.equals(String.valueOf(dictionary.getDicValue()))) {
                        dictionary.setCity("1");
                        break;
                    } else {
                        dictionary.setCity("0");
                    }
                }
            }
        }

        model.addAttribute("entity", rushCustomerRule);

        model.addAttribute("dictionaries", dictionaries);
        model.addAttribute("sources", sourcesResp.getObjectList());
        model.addAttribute("departments", departments);
        model.addAttribute("projects", projects);
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改抢客规则
     *
     * @param vo     抢客规则页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateRushCustomerRule(@Valid RushCustomerRuleVo vo, BindingResult result, HttpServletRequest httpRequest,
                                         @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model) {
        RushCustomerRuleEntity 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) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

                RushCustomerRuleRequest request = new RushCustomerRuleRequest();
                entity.setUpdateTime(new Date());
                entity.setUpdateUserName(userEntity.getRealName());
                entity.setUpdateUserId(userEntity.getId());
                request.setEntity(entity);
                @SuppressWarnings("unused")
                RushCustomerRuleResponse rersponse = rushCustomerRule
                        .updateRushCustomerRule(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/rushcustomerrule/" + 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) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        DepartmentResponse departmentResponse = department.getDepartmentById(userEntity.getDeptId());

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(
                request, "search_");
        //展示该部门及子部门的抢客规则
        searchParams.put("EQ_departments", departmentResponse.getEntity().getId());
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        RushCustomerRuleListRequest listRequest = new RushCustomerRuleListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        RushCustomerRuleListResponse response = rushCustomerRule.getRushCustomerRuleList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("rushCustomerRules", response.getObjectList());
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 查询抢客规则
     *
     * @param httpRequest 抢客规则页面表单对象
     * @return 结果视图
     */
    @RequestMapping(value = "changeStatus/{id}/{status}", method = RequestMethod.POST)
    @ResponseBody
    public Object changeStatus(HttpServletRequest httpRequest, @PathVariable Integer id, @PathVariable int status) {
        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        rushCustomerRule.changeRuleStatus(id, status, userEntity.getId(), userEntity.getRealName());
        return "10000";
    }
}
