package com.house365.web.controller;

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.MobileUtil;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.ICloudActivityInterface;
import com.house365.ws.interfaces.server.ICloudCustomerInterface;
import com.house365.ws.interfaces.server.ICustomer;
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.PathVariable;
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.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 云迹客户controller
 *
 * @author Created by Administrator on 2020/3/26.
 */
@Controller
@RequestMapping("/cloudcustomer")
public class CloudCustomerController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CloudCustomerController.class);

    @Autowired
    private ICloudCustomerInterface cloudCustomerInterface;
    @Autowired
    private ICloudActivityInterface activityInterface;
    @Autowired
    private ICustomer customer;

    /**
     * 云迹客户信息列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list/{activeId}")
    public String list(Integer number, Model model, HttpServletRequest request, @PathVariable int activeId) {
        try {
            DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String type = request.getParameter("type") == null ? "" : request.getParameter("type");
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("type", type);
            searchParams.put("userId", userEntity.getId());
            Page page = new Page(50);
            if (null != number) {
                page.setCurrentPage(number);
            }
            Map<String, Object> map = new HashMap<>(5);
            map.put("id", activeId);
            List<CloudActivityEntity> list = activityInterface.queryByConditions(map);
            model.addAttribute("activity", list.get(0));
            model.addAttribute("type", type);
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = cloudCustomerInterface.list(listRequest, activeId);

            List<Map<String, Object>> objectList = response.getObjectList();
            if(userEntity.getShowMobile() != 1) {
                for (Map<String, Object> i : objectList) {
                    if(i != null && i.containsKey("phone")) {
                       i.replace("phone",MobileUtil.hidePhone(String.valueOf(i.get("phone"))));
                    }
                }
            }

            model.addAttribute("waitCount", response.getWaitCount());
            model.addAttribute("sentCount", response.getSentCount());
            model.addAttribute("customerCount", response.getCustomerCount());
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", objectList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询云迹客户信息列表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 获取云迹客户crmurl
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCloudCrmUrl", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse getCloudCrmUrl(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                CloudCustomerEntity entity = cloudCustomerInterface.getById(Integer.valueOf(customerId));
                House365RestObject<String> hro = new House365RestObject<>();
                String url = customer.getCRMViewURL(entity.getCityCode(), entity.getPhone());
                hro.setEntity(url);
                restResponse.setData(hro);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }
        return restResponse;
    }

    /**
     * 查看营销活动客户是否是私客
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/judgeCustomer/{id}")
    @ResponseBody
    public HResult judgeCustomer(@PathVariable int id) {
        HResult result = new HResult();
        try {
            result = cloudCustomerInterface.judgeCustomer(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("查看云迹活动客户是否是私客失败");
            logger.error("查看云迹活动客户是否是私客失败", e);
        }
        return result;
    }

}
