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

import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.RushCustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.RushCustomerVo;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SessionConstants;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.RushCustomerListRequest;
import com.house365.ws.beans.request.RushCustomerRequest;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.RushCustomerListResponse;
import com.house365.ws.beans.response.RushCustomerResponse;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IRushCustomer;
import com.house365.ws.interfaces.server.IUser;
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.*;

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

    /**
     * 自动注入抢客WS实现
     */
    @Autowired
    private IRushCustomer rushCustomer;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser user;

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

    /**
     * 新增抢客
     *
     * @param vo     抢客页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createRushCustomer(@Valid RushCustomerVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
        RushCustomerEntity 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 {
                RushCustomerRequest request = new RushCustomerRequest();
                request.setEntity(entity);
                RushCustomerResponse response = rushCustomer
                        .addRushCustomer(request);
                Integer id = response.getEntity().getId();
                return "redirect:/rushcustomer/" + 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++) {
                    rushCustomer.deleteRushCustomerById(Integer.valueOf(ids[i]));
                }
            } else {
                rushCustomer.deleteRushCustomerById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看抢客
     *
     * @param id 抢客页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        RushCustomerResponse response = rushCustomer
                .getRushCustomerById(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) {
        RushCustomerResponse response = rushCustomer
                .getRushCustomerById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改抢客
     *
     * @param vo     抢客页面表单对象
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateRushCustomer(@Valid RushCustomerVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes, Model model) {
        RushCustomerEntity 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 {
                RushCustomerRequest request = new RushCustomerRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused")
                RushCustomerResponse rersponse = rushCustomer
                        .updateRushCustomer(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/rushcustomer/" + 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,
                       String timeType, String createTimeStart, String createTimeEnd, String type, String phone) {
        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));
        String cityCode = departmentResponse.getEntity().getDescripition();
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(
                request, "search_");

        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }
        page.setPageSize(50);
        RushCustomerListRequest listRequest = new RushCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        type = StringUtils.isBlank(type) ? "0" : type;
        RushCustomerListResponse response = rushCustomer.getRushCustomerList(timeType, createTimeStart, createTimeEnd, type, phone, userEntity.getId(), cityCode, number);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("rushCustomers", response.getObjectList());
        model.addAttribute("type", type);
        model.addAttribute("searchParams", Servlets
                .encodeParameterStringWithPrefix(searchParams, "search_"));

        Map<String, Object> rushCustomerCounts = rushCustomer.getRushCustomerCounts(timeType, createTimeStart, createTimeEnd, userEntity.getId(), cityCode, phone);
        model.addAttribute("rushCustomerCounts", rushCustomerCounts);

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        calendar.setTime(new Date());
        // 时间过滤 半小时推送一次
        int minute = Integer.valueOf(DateTimeUtils.parseDate(calendar.getTime(), "mm"));
        if (minute >= 30) {
            createTimeEnd = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00");
        } else {
            createTimeEnd = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        }
        createTimeStart = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd 00:00:00");
        Map<String, Object> todayRushCustomerCounts = rushCustomer.getRushCustomerCounts("0", createTimeStart, createTimeEnd, userEntity.getId(), cityCode, null);
        //共多少条数据，今日新增多少条
        Map<String, Object> seaSummary = new HashMap<>();
        int totalCount = Integer.valueOf(rushCustomerCounts.get("type0").toString())
                + Integer.valueOf(rushCustomerCounts.get("type1").toString())
                + Integer.valueOf(rushCustomerCounts.get("type2").toString());
        seaSummary.put("totalCount", totalCount);
        int todayCount = Integer.valueOf(todayRushCustomerCounts.get("type0").toString())
                + Integer.valueOf(todayRushCustomerCounts.get("type1").toString())
                + Integer.valueOf(todayRushCustomerCounts.get("type2").toString());
        seaSummary.put("todayCount", todayCount);
        model.addAttribute("summary", seaSummary);
        return getAutoUrl();
    }

    /**
     * 派工
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assignManager", method = RequestMethod.GET)
    public String assignManager(Model model, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerCount = request.getParameter("customerCount") == null ? "0" : request.getParameter(
                "customerCount");

        //当前城市下所有员工
        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 = new HashMap<>();

        String urlPath = "";
        //是总部员工，选择当前城市和下属所有部门员工 ， 非管理员，选登录用户下属所有部门员工
        if (userEntity.getDeptId() == 1) {
            urlPath = city.getUrlPath();
        } else {
            urlPath = userEntity.getDeptUrlPath() + "/";
        }

        searchParams.put("LIKE_deptUrlPath", urlPath);

        Page page = new Page(Integer.MAX_VALUE);
        UserListRequest listRequest = new UserListRequest();
        listRequest.setPaging(page);
        listRequest.setOrderColumn("name");
        listRequest.setOrderMode("asc");
        listRequest.setSearchParams(searchParams);
        UserListResponse response = user.getUserList(listRequest);
        List<UserEntity> userList = response.getObjectList();
        userList.add(0, userEntity);
        model.addAttribute("users", userList);
        model.addAttribute("customerCount", customerCount);
        return getAutoUrl("assignManager");
    }

    /**
     * 派工
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "assign", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse assign(Model model, HttpServletRequest request) {

        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        String userIds = request.getParameter("userIds");
        String customerIds = request.getParameter("customerIds");
        String[] customerIdArray = customerIds.split(",");
        String[] userIdArray = userIds.split(",");

        try {
            rushCustomer.bindUser(customerIdArray, Integer.valueOf(userIdArray[0]), userEntity.getId(), userEntity.getRealName());
        } catch (Exception e) {
            restResponse.setResult("0");
            restResponse.setMsg(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return restResponse;
    }
}
