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

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.MarketCustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.MarketCustomerVo;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.cached.RedisUtilsInterface;
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.MarketCustomerListRequest;
import com.house365.ws.beans.request.MarketCustomerRequest;
import com.house365.ws.beans.response.CustomerCallbackLogResponse;
import com.house365.ws.beans.response.MarketCustomerListResponse;
import com.house365.ws.beans.response.MarketCustomerResponse;
import com.house365.ws.beans.response.MarketingActivityResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.ICustomerCallbackLog;
import com.house365.ws.interfaces.server.IMarketCustomer;
import com.house365.ws.interfaces.server.IMarketingActivity;
import org.apache.commons.collections.CollectionUtils;
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.HashMap;
import java.util.List;
import java.util.Map;

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

    /**
     * 自动注入客户信息WS实现
     */
    @Autowired
    private IMarketCustomer marketCustomer;

    @Autowired
    private IMarketingActivity marketingActivity;

    @Autowired
    private ICustomer customer;

    @Autowired
    private ICustomerCallbackLog customerCallbackLog;

    @Autowired
    private RedisUtilsInterface redisUtils;

    /**
     * 去新增客户信息
     *
     * @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 createMarketCustomer(@Valid MarketCustomerVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
        MarketCustomerEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                MarketCustomerRequest request = new MarketCustomerRequest();
                request.setEntity(entity);
                MarketCustomerResponse response = marketCustomer.addMarketCustomer(request);
                Integer id = response.getEntity().getId();
                return "redirect:/marketcustomer/" + 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++) {
                    marketCustomer.deleteMarketCustomerById(Integer.valueOf(ids[i]));
                }
            } else {
                marketCustomer.deleteMarketCustomerById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看客户信息
     *
     * @param id 客户信息页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        MarketCustomerResponse response = marketCustomer.getMarketCustomerById(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) {
        MarketCustomerResponse response = marketCustomer.getMarketCustomerById(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 updateMarketCustomer(
            @Valid MarketCustomerVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        MarketCustomerEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                MarketCustomerRequest request = new MarketCustomerRequest();
                request.setEntity(entity);
                @SuppressWarnings("unused") MarketCustomerResponse rersponse = marketCustomer.updateMarketCustomer(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/marketcustomer/" + 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) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        String type = request.getParameter("type") == null ? "" : request.getParameter("type");
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.remove("LIKE_managerName");
        }

        MarketCustomerListResponse countResponse = getnotassignListCount(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse countNotassignandovertimeResponse = getNotassignandovertimeCount(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse countAbandonListResponse = getAbandonCount(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse countAssignResponse = getAssignedCount(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse response = getnotassignList(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse notassignandovertimeResponse = getNotassignandovertimeList(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse abandonListResponse = getAbandonList(number, Servlets.getParametersStartingWith(request, "search_"));
        MarketCustomerListResponse assignResponse = getAssignedList(number, Servlets.getParametersStartingWith(request, "search_"));

        model.addAttribute("type", type);
        model.addAttribute("assignedCount", countAssignResponse.getPaging().getRecords());
        model.addAttribute("notassignandovertimeCount", countNotassignandovertimeResponse.getPaging().getRecords());
        model.addAttribute("notassignCount", countResponse.getPaging().getRecords());
        model.addAttribute("abandonCount", countAbandonListResponse.getPaging().getRecords());

        //redis存值，方便派工所有时查询
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        Map<String, Object> searchParamNew = Servlets.getParametersStartingWith(request, "search_");
        redisUtils.deleteByKeyNew("marketCustomer_bind_phone" + userEntity.getId());
        redisUtils.deleteByKeyNew("marketCustomer_bind_signupSourceName" + userEntity.getId());
        redisUtils.deleteByKeyNew("marketCustomer_bind_actSource" + userEntity.getId());
        redisUtils.deleteByKeyNew("marketCustomer_bind_managerName" + userEntity.getId());
        if (searchParamNew.get("LIKE_phone") != null) {
            String phone = searchParamNew.get("LIKE_phone").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(phone)) {
                redisUtils.setValueNew("marketCustomer_bind_phone" + userEntity.getId(), searchParamNew.get("LIKE_phone").toString());
            } else {
                redisUtils.setValueNew("marketCustomer_bind_phone" + userEntity.getId(), "");
            }
        }
        if (searchParamNew.get("LIKE_signupSourceName") != null) {
            String signupSourceName = searchParamNew.get("LIKE_signupSourceName").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(signupSourceName)) {
                redisUtils.setValueNew("marketCustomer_bind_signupSourceName" + userEntity.getId(), signupSourceName);
            } else {
                redisUtils.setValueNew("marketCustomer_bind_signupSourceName" + userEntity.getId(), "");
            }
        }
        if (searchParamNew.get("LIKE_actSource") != null) {
            String actSource = searchParamNew.get("LIKE_actSource").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(actSource)) {
                redisUtils.setValueNew("marketCustomer_bind_actSource" + userEntity.getId(), actSource);
            } else {
                redisUtils.setValueNew("marketCustomer_bind_actSource" + userEntity.getId(), "");
            }
        }
        if (searchParamNew.get("LIKE_managerName") != null) {
            String managerName = searchParamNew.get("LIKE_managerName").toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(managerName)) {
                redisUtils.setValueNew("marketCustomer_bind_managerName" + userEntity.getId(), managerName);
            } else {
                redisUtils.setValueNew("marketCustomer_bind_managerName" + userEntity.getId(), "");
            }
        }

        if ("assigned".equalsIgnoreCase(type)) {
            model.addAttribute("page", assignResponse.getPaging());
            model.addAttribute("marketCustomers", assignResponse.getObjectList());
        } else if ("notassignandovertime".equalsIgnoreCase(type)) {
            model.addAttribute("page", notassignandovertimeResponse.getPaging());
            model.addAttribute("marketCustomers", notassignandovertimeResponse.getObjectList());
        } else if ("abandon".equalsIgnoreCase(type)) {
            model.addAttribute("page", abandonListResponse.getPaging());
            model.addAttribute("marketCustomers", abandonListResponse.getObjectList());
        } else {
            model.addAttribute("page", response.getPaging());
            model.addAttribute("marketCustomers", response.getObjectList());
        }

        String actId = String.valueOf(searchParams.get("EQ_activeId"));
        if (!Strings.isNullOrEmpty(actId)) {
            MarketingActivityResponse activity = marketingActivity.getMarketingActivityById(Integer.valueOf(actId));
            model.addAttribute("act_name", activity.getEntity().getName());
        }

        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }


    private MarketCustomerListResponse getnotassignListCount(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(1);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_notassign", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse getnotassignList(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(50);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.put("LIKE_lastManager", searchParams.get("LIKE_managerName"));
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_notassign", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setOrderColumn("a.create_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getAbandonCount(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(1);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_isabandon", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse getAbandonList(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(50);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.put("LIKE_lastManager", searchParams.get("LIKE_managerName"));
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_isabandon", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setOrderColumn("a.create_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getNotassignandovertimeCount(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(1);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_notassignandovertime", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getTotalCount(listRequest);
    }

    private MarketCustomerListResponse getNotassignandovertimeList(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(50);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.put("LIKE_lastManager", searchParams.get("LIKE_managerName"));
            searchParams.remove("LIKE_managerName");
        }
        searchParams.put("EQ_notassignandovertime", "1");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setOrderColumn("a.create_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getAssignedCount(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(1);
        if (null != number) {
            page.setCurrentPage(number);
        }
        if (searchParams.containsKey("LIKE_managerName")) {
            searchParams.remove("LIKE_managerName");
        }
        if (searchParams.containsKey("EQ_isBack")) {
            String isBack = (String) searchParams.get("EQ_isBack");
            if ("0".equals(isBack)) {
                searchParams.remove("EQ_isBack");
                searchParams.put("EQ_isNotBack", "1");
            }
        }
        searchParams.put("EQ_assigned", "1");
        searchParams.put("NOTEQ_status", "3");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    private MarketCustomerListResponse getAssignedList(Integer number, Map<String, Object> searchParams) {
        Page page = new Page(50);
        if (null != number) {
            page.setCurrentPage(number);
        }
        searchParams.put("EQ_assigned", "1");
        searchParams.put("NOTEQ_status", "3");
        MarketCustomerListRequest listRequest = new MarketCustomerListRequest();
        listRequest.setOrderColumn("a.create_time");
        listRequest.setOrderMode("desc");
        listRequest.setPaging(page);

        String isBack = String.valueOf(searchParams.get("EQ_isBack"));
        if ("1".equals(isBack)) {
            // 已回访
            searchParams.remove("EQ_isNotBack");
        } else if ("0".equals(isBack)) {
            // 未回访
            searchParams.remove("EQ_isBack");
            searchParams.put("EQ_isNotBack", "1");
        } else {
            searchParams.remove("EQ_isBack");
            searchParams.remove("EQ_isNotBack");
        }

        listRequest.setSearchParams(searchParams);
        return marketCustomer.getMarketCustomerList(listRequest);
    }

    @RequestMapping(value = "getCRMURL", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse getCRM(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 {
                MarketCustomerResponse customerResponse = marketCustomer.getMarketCustomerById(
                        Integer.valueOf(customerId));
                House365RestObject<String> hro = new House365RestObject();
                String url = customer.getCRMViewURL(customerResponse.getEntity().getCityCode(), customerResponse.getEntity().getPhone());
                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 = "abandonMsg", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse abandonMsg(Model model, HttpServletRequest request) {
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        try {
            String id = request.getParameter("customerId");
            if (!Strings.isNullOrEmpty(id)) {
                MarketCustomerResponse marketCustomerResponse = marketCustomer.getMarketCustomerById(
                        Integer.valueOf(id));
                if (marketCustomerResponse.getEntity() != null && null != marketCustomerResponse.getEntity().getIsabandon()) {
                    restResponse.setMsg("无原因");
                    if (1 == marketCustomerResponse.getEntity().getIsabandon() && null != marketCustomerResponse.getEntity().getAbandonLogID()) {
                        Integer logId = marketCustomerResponse.getEntity().getAbandonLogID();
                        CustomerCallbackLogResponse customerCallbackLogResponse = customerCallbackLog.getCustomerCallbackLogById(
                                logId);
                        if (null != customerCallbackLogResponse.getEntity()) {
                            CustomerCallbackLogEntity callback = customerCallbackLogResponse.getEntity();
                            String msg = "";

                            if (!Strings.isNullOrEmpty(callback.getContent())) {
                                msg += callback.getContent() + "<br>";
                            }
                            if (!Strings.isNullOrEmpty(callback.getCallRecordName())) {
                                msg += "<audio controls><source src=\"http://218.94.115.131:98/uncall_api/downloadFile.php?f_path=" + callback.getCallRecordName() + "\">" + "Your browser does not support this audio format." + "</audio>";
                            }
                            restResponse.setMsg(msg);
                        }
                    }
                }
            }

        } 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 = marketCustomer.judgeCustomer(id);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(-1);
            result.setErrorMessage("查看营销活动客户是否是私客失败");
            logger.error("查看营销活动客户是否是私客失败", e);
        }
        return result;
    }
}
