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.AttachmentListResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.*;
import org.apache.commons.collections.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.*;
import org.springside.modules.web.Servlets;

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

/**
 * 外部客户实体类
 *
 * @author Created by Administrator on 2020/6/30.
 */
@Controller
@RequestMapping("/externalCustomer")
public class ExternalCustomerController extends BaseController {

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

    @Autowired
    private IDepartment department;
    @Autowired
    private ICustomerSource customerSource;
    @Autowired
    private IExternalCustomerInterface customerInterface;
    @Autowired
    private IExternalCusCallLogInterface callLogInterface;
    @Autowired
    private ICityCallInterface callInterface;
    @Autowired
    private IExternalCusLogInterface cusLogInterface;
    @Autowired
    private IAttachmentInterface attachmentInterface;
    @Autowired
    private IUser user;

    /**
     * 跳转新增客户信息
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/toAdd")
    public String createForm(Model model, HttpServletRequest request) {
        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();
        String cityCode = city.getDescripition();
        Map<String, Object> map = new HashMap<>(10);
        map.put("city", cityCode);
        map.put("status", 1);
        map.put("type", 2);
        List<CustomerSourceEntity> list = customerSource.queryByConditions(map);
        model.addAttribute("sources", list);
        return getAutoUrl("add");
    }

    /**
     * 外部客户新增
     *
     * @param request
     * @param entity
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public HResult save(HttpServletRequest request, @RequestBody ExternalCustomerEntity entity) {
        HResult result = new HResult();
        try {
            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));
            DepartmentEntity city = departmentResponse.getEntity();
            Date newDate = new Date();
            entity.setCreateTime(newDate);
            if (StringUtils.isNotBlank(entity.getRemark())) {
                entity.setLastCallTime(newDate);
            }
            entity.setUpdateTime(newDate);
            entity.setCreater(userEntity.getId());
            entity.setManagerId(userEntity.getId());
            entity.setManagerName(userEntity.getRealName());
            entity.setCityName(city.getName());
            entity.setCityCode(city.getDescripition());
            entity.setIsDelete(0);
            entity.setCreateSource("外部客户");
            entity.setStatus(1);
            entity.setBindTime(newDate);
            entity.setLastManager("");
            CustomerSourceEntity cse = customerSource.getCustomerSourceById(entity.getActSourceId()).getEntity();
            entity.setActSource(cse == null ? "" : cse.getSourceName());
            result = checkPhone(entity.getPhone());
            if (result.getStatus() == 0) {
                int id = customerInterface.save(entity);
                if (!Strings.isNullOrEmpty(entity.getRemark())) {
                    addCallBack(userEntity, id, entity.getBuyIntention(), entity.getRemark(), newDate);
                }
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("新增外部客户失败", e);
            result.setStatus(500);
            result.setErrorMessage("新增外部客户失败");
        }
        return result;
    }

    /**
     * 跳转修改客户信息
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/toEdit/{id}")
    public String toEdit(@PathVariable int id, Model model) {
        ExternalCustomerEntity entity = customerInterface.queryById(id);
        //判断是否有城市外呼配置
        if (StringUtils.isNotBlank(entity.getCityCode())) {
            List<CityCallConfig> list = callInterface.queryByCity(entity.getCityCode());
            if (CollectionUtils.isNotEmpty(list)) {
                model.addAttribute("hasPhone", 1);
            }
        }
        Map<String, Object> searchMap = new HashMap<>(5);
        searchMap.put("customerId", id);
        List<ExternalCustomerCallbackLogEntity> callLogList = callLogInterface.queryByConditions(searchMap);
        AttachmentListResponse response = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id), "customer_cer_img");
        if (null != response && CollectionUtils.isNotEmpty(response.getObjectList())) {
            model.addAttribute("attachList", response.getObjectList());
        } else {
            model.addAttribute("attachList", Collections.emptyList());
        }
        UserEntity userEntity = user.getById(entity.getCreater());
        if (null != userEntity) {
            entity.setCreateName(userEntity.getRealName());
        }
        //查询客户日志
        Map<String, Object> map = new HashMap<>(10);
        map.put("relateId", entity.getId());
        List<ExternalCustomerLogEntity> list = cusLogInterface.queryByConditions(map);
        List<String> logShowList = new ArrayList<>(15);
        if (CollectionUtils.isNotEmpty(list)) {
            for (ExternalCustomerLogEntity p : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //获取String类型的时间
                String showTime = sdf.format(p.getCreateTime());
                if (p.getType() == 1) {
                    String showWord = showTime + "  " + p.getCreateUserName() + " [新增客户]";
                    logShowList.add(showWord);
                } else if (p.getType() == 2) {
                    StringBuilder builder = new StringBuilder();
                    builder.append(showTime).append("   ").append(p.getCreateUserName()).append("  [编辑客户]  ");
                    builder.append("将  '").append(p.getModifyName()).append("'  由  '").append(p.getOldValue())
                            .append("'  修改为  '").append(p.getNewValue()).append("' , ");
                    logShowList.add(builder.toString().substring(0, builder.toString().lastIndexOf(",")));
                } else if (p.getType() == 4) {
                    //无变动
                    String showWord = showTime + "  " + p.getCreateUserName() + " [无变动]";
                    logShowList.add(showWord);
                }

            }
        }

        if(userEntity.getShowMobile() == null || userEntity.getShowMobile() != 1) {
            entity.setPhone(MobileUtil.hidePhone(entity.getPhone()));
        }

        model.addAttribute("callLogs", callLogList);
        model.addAttribute("entity", entity);
        List<ExternalCustomerEntity> oldList = new ArrayList<>();
        oldList.add(entity);
        model.addAttribute("oldList", oldList);
        //客户日志列表
        model.addAttribute("logList", logShowList);
        return getAutoUrl("edit");
    }

    /**
     * 修改客户信息
     *
     * @return 结果视图
     */
    @RequestMapping(value = "edit/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public HResult edit(@RequestBody ExternalCustomerEntity entity, @PathVariable Integer id, HttpServletRequest request) {
        HResult result = new HResult();
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        try {
            ExternalCustomerEntity oldEntity = customerInterface.queryById(id);
            oldEntity.setName(entity.getName());
            if (StringUtils.isNotBlank(entity.getBakPhone())) {
                oldEntity.setBakPhone(entity.getBakPhone());
            }
            oldEntity.setTraceStatus(entity.getTraceStatus());
            if (StringUtils.isNotBlank(entity.getBuyIntention())) {
                oldEntity.setBuyIntention(entity.getBuyIntention());
            }
            oldEntity.setSex(entity.getSex());
            oldEntity.setBuyIntention(entity.getBuyIntention());
            oldEntity.setUpdater(userEntity.getId());
            oldEntity.setUpdateTime(new Date());
            customerInterface.update(oldEntity, userEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改外部客户信息失败", e);
            result.setStatus(500);
            result.setErrorMessage("修改外部客户信息失败");
        }
        return result;
    }

    /**
     * 外部客户列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Integer number, Model model, HttpServletRequest request) {
        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 timePeriod = request.getParameter("timePeriod") == null ? "0" : request.getParameter("timePeriod");
            model.addAttribute("timePeriod", timePeriod);
            String city = dept.getDescripition();
            searchParams.put("city", city);
            searchParams.put("userId", userEntity.getId());
            Page page = new Page(100);
            if (null != number) {
                page.setCurrentPage(number);
            }
            //判断是否有城市外呼配置
            if (StringUtils.isNotBlank(city)) {
                List<CityCallConfig> list = callInterface.queryByCity(city);
                if (CollectionUtils.isNotEmpty(list)) {
                    model.addAttribute("hasPhone", 1);
                }
            }
            MapListRequest listRequest = new MapListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            MapListResponse response = customerInterface.list(listRequest);

            List<Map<String, Object>> objectList = response.getObjectList();
            if(userEntity.getShowMobile() == null || 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("page", response.getPaging());
            model.addAttribute("dataList", objectList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询外部客户列表失败", e);
        }
        return getAutoUrl();
    }

    private void addCallBack(UserEntity userEntity, int customerId, String buyIntention, String content, Date newDate) {
        ExternalCustomerCallbackLogEntity logEntity = new ExternalCustomerCallbackLogEntity();
        logEntity.setCustomerId(customerId);
        logEntity.setContent(content);
        logEntity.setCreater(userEntity.getName());
        logEntity.setCreateTime(newDate);
        logEntity.setManagerId(userEntity.getId());
        logEntity.setManagerName(userEntity.getRealName());
        logEntity.setResult(buyIntention);
        callLogInterface.saveCallBackLog(logEntity);
    }

    @RequestMapping(value = "/checkPhone")
    @ResponseBody
    public HResult checkPhone(String customerPhone) {
        HResult result = new HResult();
        if (StringUtils.isNotBlank(customerPhone)) {
            Map<String, Object> map = new HashMap<>(10);
            map.put("phone", customerPhone);
            List<ExternalCustomerEntity> list = customerInterface.queryByConditions(map);
            if (CollectionUtils.isNotEmpty(list)) {
                result.setStatus(101);
                result.setErrorMessage("该号码已被跟进，请勿重复添加");
            }
        }
        return result;
    }

    /**
     * 拨打电话
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/callCustomer", method = RequestMethod.GET)
    public String callCustomer(Model model, String memPhone, int customerId, int buyIntention, String abandon) {
        model.addAttribute("memPhone", memPhone);
        model.addAttribute("customerId", customerId);
        model.addAttribute("buyIntention", buyIntention);
        model.addAttribute("abandon", abandon);
        return getAutoUrl("callCustomer");
    }

    /**
     * 拨打电话
     *
     * @return
     */
    @RequestMapping(value = "/calling", method = RequestMethod.GET)
    @ResponseBody
    public Object calling(HttpServletRequest request, String memPhone, Integer customerId) {
        Integer userId = (Integer) request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY);
        return customerInterface.calling(memPhone, customerId, userId);
    }

    /**
     * 挂断电话
     *
     * @return
     */
    @RequestMapping(value = "handUp", method = RequestMethod.GET)
    @ResponseBody
    public Object handUp(HttpServletRequest request, Integer callbackLogId, String callContent, String buyIntention, String abandon) {
        Integer userId = (Integer) request.getSession().getAttribute(SessionConstants.THREAD_USERID_KEY);
        customerInterface.handUp(callbackLogId, callContent, buyIntention, userId, abandon);
        return "";
    }

    /**
     * 外部客户创建回访纪录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addCall", method = RequestMethod.GET)
    @ResponseBody
    public House365RestResponse addCall(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        House365RestResponse restResponse = new House365RestResponse();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        Date newDate = new Date();
        if (null != customerId && userEntity != null) {
            try {
                String content = request.getParameter("content");
                String buyIntention = request.getParameter("buyIntention");
                ExternalCustomerEntity customerEntity = customerInterface.queryById(Integer.valueOf(customerId));
                //添加回访
                addCallBack(userEntity, Integer.valueOf(customerId), buyIntention, content, newDate);

                //更新客户信息
                customerEntity.setLastCallTime(newDate);
                customerEntity.setUpdateTime(newDate);
                customerEntity.setUpdater(userEntity.getId());
                customerEntity.setBuyIntention("99".equalsIgnoreCase(buyIntention) ? "" : buyIntention);
                //更新回访记录的时候，同时更新会员备注
                customerEntity.setRemark(content);
                customerInterface.update(customerEntity, userEntity);
            } catch (Exception e) {
                restResponse.setResult("0");
                restResponse.setMsg(e.getMessage());
                e.printStackTrace();
                logger.error("外部客户添加回访失败", e);
            }
        }
        return restResponse;
    }

    /**
     * 查询客户回访记录
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/getCustomerCallbackLogs", method = RequestMethod.GET)
    @ResponseBody
    public List getCustomerCallbackLogs(Integer customerId) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("customerId", customerId);
        return callLogInterface.queryByConditions(map);
    }

    /**
     * 获取CRM用户视图地址
     *
     * @param request
     * @return
     */
    @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();
        UserEntity currUser = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String curId = String.valueOf(currUser.getId());
        String curName = currUser.getRealName();
        restResponse.setResult("1");
        String customerId = request.getParameter("customerId");
        if (!Strings.isNullOrEmpty(customerId) && userEntity != null) {
            try {
                House365RestObject<String> hro = new House365RestObject<>();
                String url = customerInterface.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;
    }

}
