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

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserStarEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.ManagerVO;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.UserStarListRequest;
import com.house365.ws.beans.request.UserStarRequest;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.beans.response.UserStarListResponse;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.interfaces.server.IUserStar;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户信息控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-19
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/manager")
public class ManagerController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入客户信息WS实现
     */
    @Autowired
    private ICustomer customer;
    @Autowired
    private IDepartment department;
    @Autowired
    private IUser user;
    @Autowired
    private IUserStar userStar;

    /**
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Integer pageSize, Model model, HttpServletRequest request) {

        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        boolean isDirector = user.isDirector(userEntity.getId());
        List<DepartmentEntity> departmentEntities = user.getChildDepartList(userEntity.getDeptId());

        if (departmentEntities != null && departmentEntities.isEmpty()) {
            model.addAttribute("departments", departmentEntities);
            return getAutoUrl();
        }
        //get user list
        Page page = new Page(pageSize == null ? 20 : pageSize);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (CollectionUtils.isNotEmpty(departmentEntities)) {
            DepartmentEntity dep = departmentEntities.get(0);

            String deptId = request.getParameter("deptId") == null ? "" : request.getParameter("deptId");
            if (!Strings.isNullOrEmpty(deptId)) {
                dep = department.getDepartmentById(Integer.valueOf(deptId)).getEntity();
            }

            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            UserListResponse ulr = user.getUserListByDept(dep, searchParams, page);
            List<UserEntity> userEntities = ulr.getObjectList();
            if (searchParams.containsKey("LIKE_realName") && StringUtils.isNotBlank(String.valueOf(searchParams.get("LIKE_realName")))) {
                if(userEntity.getRealName().contains(searchParams.get("LIKE_realName").toString())){
                    userEntities.add(userEntity);
                }
            }else {
                userEntities.add(userEntity);
            }
            page = ulr.getPaging();
            List<ManagerVO> managerVOS = new ArrayList<>();
            for (UserEntity ue : userEntities) {
                ManagerVO vo = new ManagerVO();
                vo.setManagerId(ue.getId());
                vo.setManagerName(ue.getRealName());
                Map<String, Object> map = user.getSummary(ue.getId().toString());
                vo.setTotal(String.valueOf(map.get("allCount")));
                vo.setWaitCount(String.valueOf(map.get("waitCount")));
                vo.setCallToday(String.valueOf(map.get("callToday")));
                vo.setCallYesterday(String.valueOf(map.get("callYesterday")));
                vo.setAllCallToday(String.valueOf(map.get("allCallToday")));
                vo.setAllCallYesterday(String.valueOf(map.get("allCallYesterday")));

                Map<String, Object> search = new HashMap<>(10);
                search.put("EQ_starUserId", ue.getId());
                search.put("EQ_userId", userEntity.getId());
                UserStarListRequest cul = new UserStarListRequest();
                cul.setPaging(new Page(1));
                cul.setSearchParams(search);
                UserStarListResponse res = userStar.getUserStarList(cul);
                if (res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                    UserStarEntity entity = res.getObjectList().get(0);
                    vo.setStar(entity.getStar() == 1 ? "on" : "off");
                } else {
                    vo.setStar("off");
                }
                Map<String, Object> managerIdMap = new HashMap<>(10);
                managerIdMap.put("managerId", ue.getId());
                Integer customers = customer.getCustomersById(managerIdMap);
                if (customers > 0) {
                    vo.setIsClear("1");//0:无客户,1:有客户
                } else {
                    vo.setIsClear("0");//0:无客户,1:有客户
                }
                managerVOS.add(vo);
            }
            if (isDirector) {
                model.addAttribute("isDirector", "1");//1：是主管
            } else {
                model.addAttribute("isDirector", "0");//0:普通顾问
            }
            model.addAttribute("deptId", dep.getId());
            model.addAttribute("list", managerVOS);
            model.addAttribute("page", page);
            model.addAttribute("departments", departmentEntities);
            model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
            return getAutoUrl();
        }
        return getAutoUrl();
    }

    @RequestMapping(value = "clearCustomerByManagerId", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject clearCustomerByManagerId(HttpServletRequest request, String managerId, String managerName) throws ServiceRunException {
        JSONObject resultJo = new JSONObject();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String updateId = String.valueOf(userEntity.getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String time = sdf.format(date);
        Map<String, Object> map = new HashMap<>(10);
        map.put("managerId", managerId);
        map.put("date", time);
        map.put("updaterId", updateId);
        map.put("lastManager", managerName);
        customer.clearCustomerByManagerId(map, userEntity.getId(), userEntity.getRealName());
        resultJo.put("flag", "1");
        return resultJo;
    }

    /**
     * 获取我的用户列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getMyCustomers", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse getMyCustomers(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        String curId = String.valueOf(userEntity.getId());
        String curName = userEntity.getRealName();
        if (!Strings.isNullOrEmpty(customerId)) {
            try {
                House365RestObject<String> hro = new House365RestObject();
                String url = customer.getCRMCustomerURL(Integer.valueOf(customerId), curId, curName);
                hro.setEntity(url);
                restResponse.setData(hro);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    @RequestMapping(value = "starToggle", method = RequestMethod.GET)
    @ResponseBody
    public Object starToggle(HttpServletRequest request, String flag, Integer starUserId) throws ServiceRunException {
        // 取得所需参数
        House365RestResponse<CustomerEntity> response = new House365RestResponse<>();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

            Map<String, Object> search = new HashMap<>(10);
            search.put("EQ_starUserId", starUserId);
            search.put("EQ_userId", userEntity.getId());

            UserStarListRequest cul = new UserStarListRequest();
            cul.setPaging(new Page(1));
            cul.setSearchParams(search);

            //update
            UserStarListResponse res = userStar.getUserStarList(cul);
            if (res.getObjectList() != null && !res.getObjectList().isEmpty()) {
                UserStarEntity entity = res.getObjectList().get(0);
                entity.setStar("on".equalsIgnoreCase(flag) ? 1 : 0);

                UserStarRequest updateReq = new UserStarRequest();
                updateReq.setEntity(entity);
                userStar.updateUserStar(updateReq);
            } else {
                //add new
                UserStarEntity entity = new UserStarEntity();
                entity.setStarUserId(starUserId);
                entity.setUserId(userEntity.getId());
                entity.setStar("on".equalsIgnoreCase(flag) ? 1 : 0);
                entity.setCreateTime(new Date());

                UserStarRequest newReq = new UserStarRequest();
                newReq.setEntity(entity);
                userStar.addUserStar(newReq);
            }

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

}
