package com.house365.web.controller;

import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.LabelEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.LabelVo;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.PathUtil;
import com.house365.web.util.SessionConstants;
import com.house365.ws.beans.request.DepartmentListRequest;
import com.house365.ws.beans.request.LabelRequest;
import com.house365.ws.beans.response.CustomerResponse;
import com.house365.ws.beans.response.DepartmentListResponse;
import com.house365.ws.beans.response.DepartmentResponse;
import com.house365.ws.beans.response.LabelResponse;
import com.house365.ws.beans.util.HResult;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.IDepartment;
import com.house365.ws.interfaces.server.IUser;
import org.apache.commons.collections.CollectionUtils;
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.util.*;

/**
 * @author 标签管理和客户标签管理管理类
 */
@Controller
@RequestMapping("/labelmanager")
public class LabelManagerController extends BaseController {

    @Autowired
    private IUser user;

    @Autowired
    private ICustomer customer;

    @Autowired
    private IDepartment department;

    @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);

        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_");
        String likeLabelName = String.valueOf(searchParams.get("LIKE_labelName"));
        searchParams.put("EQ_createId", userEntity.getId());
        searchParams.put("EQ_cityCode", cityCode);
        Page page = new Page(pageSize == null ? 20 : pageSize);
        if (null != number) {
            page.setCurrentPage(number);
        }
        LabelRequest listRequest = new LabelRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn("loginTime");
        listRequest.setOrderMode("desc");
        LabelResponse response = user.getLabelList(listRequest);
        model.addAttribute("page", response.getPaging());
        if (response.getObjectList() != null && response.getObjectList().size() > 0) {
            model.addAttribute("showcontent", "1");
        } else {
            model.addAttribute("showcontent", "0");
        }
        if (likeLabelName == null || "".equals(likeLabelName) || "null".equals(likeLabelName)) {
            model.addAttribute("labelName", "");
        } else {
            model.addAttribute("labelName", likeLabelName);
        }

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

    /**
     * 添加客户标签
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "addCustomerLabel", method = {RequestMethod.GET})
    public String addCustomerLabel(Model model, HttpServletRequest request) {
        String customerIds = request.getParameter("customerIds");
        model.addAttribute("customerIds", customerIds);
        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();
        //加载客户标签
        LabelRequest labelrequest = new LabelRequest();
        Map<String, Object> searchMap = new HashMap<>(10);
        searchMap.put("EQ_createId", userEntity.getId());
        searchMap.put("EQ_cityCode", cityCode);
        Page page = new Page(20);
        labelrequest.setPaging(page);
        labelrequest.setSearchParams(searchMap);
        labelrequest.setOrderColumn("loginTime");
        labelrequest.setOrderMode("desc");
        LabelResponse labelresponse = user.getLabelList(labelrequest);
        if (labelresponse.getObjectList() != null && labelresponse.getObjectList().size() > 0) {
            List<LabelEntity> label = labelresponse.getObjectList();
            model.addAttribute("labellist", label);
            model.addAttribute("haslabel", "1");
        }
        return getAutoUrl();
    }

    /**
     * 新增标签页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model, HttpServletRequest request) {
        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>();
        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("LIKE_urlPath", deptEntity.getEntity().getUrlPath());
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();

        DepartmentResponse currentDept = department.getDepartmentById(departmentEntity.getId());
        model.addAttribute("departList", models);
        if (currentDept.getEntity() != null) {
            model.addAttribute("currentDept", currentDept.getEntity());
        }

        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 管理添加标签-新增标签页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "addLabel", method = {RequestMethod.GET})
    @ResponseBody
    public String addLabel(HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(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();

        String labelName = request.getParameter("labelName");
        String colorId = request.getParameter("colorId");
        Date date = new Date();
        Integer createId = userEntity.getId();
        String createName = userEntity.getRealName();
        LabelEntity labelentity = new LabelEntity();
        labelentity.setColorId(colorId);
        labelentity.setCreateId(createId);
        labelentity.setCreateName(createName);
        labelentity.setUpdateTime(date);
        labelentity.setLabelName(labelName);
        labelentity.setCityCode(cityCode);
        user.addLabel(labelentity);
        return "success";
    }

    /**
     * 管理修改标签-修改标签页
     *
     * @param id
     * @param colorId
     * @param labelName
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/{id}/{colorId}/{labelName}", params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, @PathVariable(value = "colorId") Integer colorId,
                             @PathVariable(value = "labelName") String labelName, Model model, HttpServletRequest request) {

        DepartmentListRequest listReq = new DepartmentListRequest();
        Map<String, Object> map = new HashMap<>(5);

        DepartmentEntity departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                SessionConstants.SESSION_REAL_DEPT_KEY);
        if (PathUtil.isAdminDept(departmentEntity)) {
            departmentEntity = (DepartmentEntity) request.getSession().getAttribute(
                    SessionConstants.SESSION_CURRNET_DEPT_KEY);
        }
        DepartmentResponse deptEntity = department.getDepartmentById(departmentEntity.getId());
        map.put("LIKE_urlPath", deptEntity.getEntity().getUrlPath());
        Page page = new Page(1, Integer.MAX_VALUE);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("orderNum");
        listReq.setOrderMode("asc");
        DepartmentListResponse resp = department.getDepartmentList(listReq);
        List<DepartmentEntity> models = resp.getObjectList();

        DepartmentResponse currentDept = department.getDepartmentById(departmentEntity.getId());
        model.addAttribute("departList", models);
        if (currentDept.getEntity() != null) {
            model.addAttribute("currentDept", currentDept.getEntity());
        }
        model.addAttribute("action", "edit");
        model.addAttribute("id", id);
        model.addAttribute("colorId", colorId);
        model.addAttribute("labelName", labelName);
        return getAutoUrl("edit");
    }

    /**
     * 更新标签
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "updateLabel", method = {RequestMethod.GET})
    @ResponseBody
    public String updateLabel(HttpServletRequest request) {
        String labelName = request.getParameter("labelName");
        String colorId = request.getParameter("colorId");
        Integer id = Integer.valueOf(request.getParameter("id"));
        Date date = new Date();
        LabelEntity labelentity = new LabelEntity();
        labelentity.setId(id);
        labelentity.setLabelName(labelName);
        labelentity.setColorId(colorId);
        labelentity.setUpdateTime(date);
        user.updateLabel(labelentity);
        return "success";
    }

    /**
     * 标签管理删除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delLabel", method = {RequestMethod.DELETE})
    @ResponseBody
    public String delLabel(HttpServletRequest request) {
        Integer id = (Integer.valueOf(request.getParameter("id")));
        Date date = new Date();
        LabelEntity labelentity = new LabelEntity();
        labelentity.setId(id);
        labelentity.setUpdateTime(date);
        user.delLabel(labelentity);
        return "success";
    }

    /**
     * 保存客户添加标签
     *
     * @param entity
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveCustomersLabels", method = {RequestMethod.POST})
    @ResponseBody
    public String saveCustomersLabels(LabelEntity entity, HttpServletRequest request) {
        UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        String customerIds = request.getParameter("customerIds");
        String labelIds = entity.getLabelId();
        List<String> ids = new ArrayList<>();
        List<String> labIds = new ArrayList<>();
        String[] cids;
        if (customerIds.contains(",")) {
            customerIds = customerIds.substring(0, customerIds.length() - 1);
            cids = customerIds.split(",");
        } else {
            cids = new String[1];
            cids[0] = customerIds;
        }
        //客户ids
        for (String id : cids) {
            ids.add(id);
        }
        String[] lids;
        if (labelIds.contains(",")) {
            lids = labelIds.split(",");
        } else {
            lids = new String[1];
            lids[0] = labelIds;
        }
        List<LabelEntity> paramList = new ArrayList<>();
        LabelEntity labelentity = new LabelEntity();
        //每个客户分次循环插入多个标签
        for (String id : ids) {
            //标签ids
            for (String lid : lids) {
                labIds.add(lid);
            }
            labelentity.setManagerId(userEntity.getId());
            labelentity.setCustomerId(Integer.valueOf(id));
            List<LabelEntity> oldLabList = user.getCustomerLabelById(labelentity);
            if (oldLabList != null && oldLabList.size() > 0) {
                for (LabelEntity oldEntity : oldLabList) {
                    String oldId = oldEntity.getLabelId();
                    Iterator<String> iterator = labIds.iterator();
                    while (iterator.hasNext()) {
                        String newId = iterator.next();
                        if (oldId.equals(newId)) {
                            iterator.remove();
                        }
                    }
                }
                if (labIds.size() == 0) {
                    continue;
                }
                for (String lid : labIds) {
                    LabelEntity le = new LabelEntity();
                    le.setManagerId(userEntity.getId());
                    le.setCustomerId(Integer.valueOf(id));
                    le.setLabelId(lid);
                    paramList.add(le);
                }
            } else {//无标签
                for (String lid : labIds) {
                    LabelEntity le = new LabelEntity();
                    le.setManagerId(userEntity.getId());
                    le.setCustomerId(Integer.valueOf(id));
                    le.setLabelId(lid);
                    paramList.add(le);
                }
            }
            user.saveCustomersLabels(paramList);
            paramList.clear();
            labIds.clear();
        }
        return "success";
    }

    /**
     * 保存客户添加标签新
     *
     * @param labelVo
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveCustomersLabel", method = {RequestMethod.POST})
    @ResponseBody
    public HResult saveCustomersLabel(@RequestBody LabelVo labelVo, HttpServletRequest request) {
        HResult result = new HResult();
        try {
            UserEntity userEntity = (UserEntity) request.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
            List<Integer> customerIds = labelVo.getCustomerIdList();
            List<Integer> labIdList = labelVo.getLabelIdList();
            String detailType = labelVo.getDetailType();
            Integer managerId = labelVo.getManagerId();
            String phone = labelVo.getPhone();
            String mycustomerSource = labelVo.getMycustomerSource();
            //待回访详情
            if ("1".equals(detailType)) {
                CustomerEntity mergeEntity = customer.getCustomerMerge(phone, managerId);
                customerIds.remove(0);
                customerIds.add(mergeEntity.getId());
            }
            if (CollectionUtils.isNotEmpty(labIdList)) {

                //每个客户分次循环插入多个标签
                for (Integer id : customerIds) {
                    if (!"1".equals(detailType)) {
                        //客户id做一个处理
                        id = dealCustomerId(id);
                    }
                    List<LabelEntity> paramList = new ArrayList<>();
                    List<Integer> labIds = new ArrayList<>();
                    CollectionUtils.addAll(labIds, new Object[labIdList.size()]);
                    Collections.copy(labIds, labIdList);
                    //删除原有的旧的标签:客户列表追加不删除
                    if (!"1".equals(mycustomerSource)) {
                        LabelEntity labelentity = new LabelEntity();
                        labelentity.setManagerId(userEntity.getId());
                        labelentity.setCustomerId(id);
                        user.delCustomerLabel(labelentity);
                    }
                    for (Integer lid : labIds) {
                        LabelEntity le = new LabelEntity();
                        le.setManagerId(userEntity.getId());
                        le.setCustomerId(id);
                        le.setLabelId(lid.toString());
                        List<LabelEntity> labelIds = user.getCustomerLabelIds(le);
                        boolean exists = false;
                        for (LabelEntity tem : labelIds) {
                            if (tem.getLabelId().equals(String.valueOf(lid))) {
                                exists = true;
                            }
                        }
                        if (!exists) {
                            paramList.add(le);
                        }
                    }
                    if (paramList.size() > 0) {
                        user.saveCustomersLabels(paramList);
                    }
                }
            } else {
                result.setStatus(400);
                result.setErrorMessage("请选择标签");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus(500);
            result.setErrorMessage("新增客户标签失败");
            logger.error("新增客户标签失败", e);
        }
        return result;
    }

    /**
     * 客户列表删除标签
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delCustomerLabel", method = {RequestMethod.DELETE})
    @ResponseBody
    public String delCustomerLabel(HttpServletRequest request) {
        Integer customerId = (Integer.valueOf(request.getParameter("customerId")));
        //客户id做一个处理
        customerId = dealCustomerId(customerId);
        String labelId = request.getParameter("labelId");
        String waitFlag = request.getParameter("waitFlag");
        LabelEntity labelentity = new LabelEntity();
        if ("1".equals(waitFlag)) {
            CustomerResponse resp = customer.getCustomerById(customerId);
            CustomerEntity ce = resp.getEntity();
            if (ce.getPhone() != null && ce.getManagerId() != null) {
                CustomerEntity mergeEntity = customer.getCustomerMerge(ce.getPhone(), ce.getManagerId());
                if (mergeEntity != null) {
                    labelentity.setCustomerId(mergeEntity.getId());
                } else {
                    labelentity.setCustomerId(customerId);
                }
            }
        } else {
            labelentity.setCustomerId(customerId);
        }
        labelentity.setLabelId(labelId);
        user.delCustomerLabel(labelentity);
        return "success";
    }

    private int dealCustomerId(int customerId) {
        CustomerResponse customerResponse = customer.getCustomerById(customerId);
        if (customerResponse != null && customerResponse.getEntity() != null) {
            CustomerEntity customerEntity = customerResponse.getEntity();
            Map<String, Object> idMap = new HashMap<>(10);
            idMap.put("phone", customerEntity.getPhone());
            idMap.put("managerId", customerEntity.getManagerId());
            List<CustomerEntity> mergeList = customer.queryMergeByConditions(idMap);
            if (CollectionUtils.isNotEmpty(mergeList)) {
                customerId = mergeList.get(0).getId();
            }
        }
        return customerId;
    }

}
