package com.huiju.estateagents.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.center.taUser.entity.TaUser;
import com.huiju.estateagents.center.taUser.service.ITaUserService;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.JWTUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.excel.*;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.mapper.TaPersonBuildingMapper;
import com.huiju.estateagents.mapper.TaRecommendCustomerMapper;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.ITaRecommendCustomerService;
import com.huiju.estateagents.service.TaChannelPersonService;
import com.huiju.estateagents.service.TaChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import com.huiju.estateagents.base.BaseController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 推荐客户表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@RestController
@RequestMapping("/api")
@Api(value = "项目类型", tags = "项目类型")
public class TaRecommendCustomerController extends BaseController {

    @Autowired
    ITaRecommendCustomerService taRecommendCustomerService;

    @Autowired
    ITaPersonService taPersonService;

    @Resource
    private ApplicationContext applicationContext;

    @Autowired
    private TaChannelService taChannelService;

    @Autowired
    private TaChannelPersonService taChannelPersonService;

    @Autowired
    private TaRecommendCustomerMapper taRecommendCustomerMapper;

    @Autowired
    private TaPersonBuildingMapper taPersonBuildingMapper;

    @Autowired
    private ITaPersonService iTaPersonService;

    @Autowired
    private ITaUserService iTaUserService;


    /**
     * 我的客户列表
     * @param pageNumber
     * @param pageSize
     * @param keywords
     * @param request
     * @return
     */
    @GetMapping("/wx/customer/list")
    @ApiOperation(value = "查询我的客户列表", notes = "查询我的客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNumber", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "keywords", paramType = "query",value = "搜索关键字，目前仅支持姓名")
    })
    public ResponseBean getMyCustList(@RequestParam int pageNumber, @RequestParam int pageSize, String keywords, HttpServletRequest request) {
        if (pageNumber < 0 || pageSize < 0) {
            return ResponseBean.error("分页参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        String openid = getOpenId(request);
        return taRecommendCustomerService.getMyCustList(openid, keywords, pageNumber, pageSize);
    }

    /**
     * 我的客户列表
     * @param pageNumber
     * @param pageSize
     * @param keywords
     * @param request
     * @return
     */
    @GetMapping("/admin/customer/list/{userId}")
    @ApiOperation(value = "查询我的客户列表", notes = "查询我的客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNumber", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "keywords", paramType = "query",value = "搜索关键字，目前仅支持姓名")
    })
    public ResponseBean getAdminMyCustList(@RequestParam int pageNumber,
                                           @RequestParam int pageSize,
                                           @RequestParam(required = false) String keywords,
                                           @PathVariable("userId") Integer userId,
                                           HttpServletRequest request) {
        if (pageNumber < 0 || pageSize < 0) {
            return ResponseBean.error("分页参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        TaUser user = iTaUserService.getById(userId);
        if (null == user) {
            return ResponseBean.error("员工不存在！", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        QueryWrapper<TaPerson> personQueryWrapper = new QueryWrapper<>();
        personQueryWrapper.eq("user_id", userId);
        TaPerson person = iTaPersonService.getOne(personQueryWrapper);
        if (null == person) {
            return ResponseBean.error("未绑定小程序！", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        return taRecommendCustomerService.getAdminMyCustList(person.getMiniOpenid(), keywords, pageNumber, pageSize);
    }

    /**
     * 客户详情
     * @param id
     * @return
     */
    @GetMapping("/wx/customer/{id}")
    @ApiOperation(value = "查询客户详情", notes = "查询客户详情")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", paramType = "path",value = "搜索关键字，目前仅支持姓名")
    })
    public ResponseBean getCustDetail(@PathVariable String id) {
        if (null == id || "".equals(id.trim())) {
            return ResponseBean.error("请求地址错误", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        return taRecommendCustomerService.getCustDetail(id);
    }

    /**
     * 客户编辑
     * @param paramStr
     * @return
     */
    @PostMapping("/wx/customer/edit")
    @ApiOperation(value = "客户编辑", notes = "客户编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", paramType = "path",value = "搜索关键字，目前仅支持姓名")
    })
    public ResponseBean updateCust(@RequestBody String paramStr) {
        return taRecommendCustomerService.updateCustByJSON(paramStr);
    }

    /**
     * 推荐客户
     * @param paramStr
     * @param request
     * @return
     */
    @PostMapping("/wx/customer/new")
    public ResponseBean recommendCust(@RequestBody String paramStr, HttpServletRequest request) {
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        return taRecommendCustomerService.recommendCust(paramStr, openid,orgId);
    }

    /**
     * 报备客户
     * @param paramStr
     * @param request
     * @return
     */
    @PostMapping("/wx/customer/report")
    public ResponseBean reportCust(@RequestBody String paramStr, HttpServletRequest request) {
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);
        return taRecommendCustomerService.reportCust(paramStr, openid,orgId);
    }

    @PostMapping("/wx/customer/recommend")
    public ResponseBean getUnSignedCustomerList ( @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                                  @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                  @RequestParam(value ="buildingId") String buildingId,
                                                  HttpServletRequest request){
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try{
            return ResponseBean.success(taRecommendCustomerService.getUnSignedCustomerList(pageNumber,pageSize,buildingId,person.getPersonId()));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/wx/customer/myReport")
    public ResponseBean getCustomerIReport (HttpServletRequest request,
                                         @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try{
            IPage<TaRecommendCustomer>pg = new Page<>(pageNumber,pageSize);
            QueryWrapper<TaRecommendCustomer>queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("realty_consultant",person.getPersonId());
            queryWrapper.eq("report_recommend_status",CommConstant.REPORTED);
            queryWrapper.eq("status",CommConstant.CUSTOMER_REPORT);
            queryWrapper.orderByDesc("create_date");
            IPage<TaRecommendCustomer>result = taRecommendCustomerService.page(pg,queryWrapper);
            return ResponseBean.success(result);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/wx/customer/myCustomer")
    public ResponseBean getMyCustomer (     @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                            @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                            HttpServletRequest request){
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);

        try{
            IPage<TaRecommendCustomer>pg = new Page<>(pageNumber,pageSize);
            QueryWrapper<TaRecommendCustomer>queryWrapper = new QueryWrapper<>();

            // 2020-4-1 yansen realty_consultant 可能是 person_id, 可能是 user_id
//            queryWrapper.eq("realty_consultant",person.getPersonId());
            queryWrapper.eq("org_id", person.getOrgId());   // 主要是为了走索引
            queryWrapper.nested(query -> query.eq("realty_consultant",person.getPersonId()).or().eq("realty_consultant", person.getUserId()));
           // queryWrapper.eq("report_recommend_status",CommConstant.REPORTED);
            queryWrapper.gt("status",CommConstant.STATUS_UNACCALIMED);
            queryWrapper.orderByDesc("create_date");
            IPage<TaRecommendCustomer>result = taRecommendCustomerService.page(pg,queryWrapper);
            return ResponseBean.success(result);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    @GetMapping("/wx/customer/myInviteAgent")
    public ResponseBean getMyInviteAgent (@RequestParam(value ="personId") String personId,
                                       @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                       @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        try{
            IPage<TaRecommendCustomer>pg = new Page<>(pageNumber,pageSize);
            QueryWrapper<TaRecommendCustomer>queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("realty_consultant",personId);
            queryWrapper.eq("report_recommend_status",CommConstant.REPORTED);
            queryWrapper.orderByDesc("create_date");
            IPage<TaRecommendCustomer>result = taRecommendCustomerService.page(pg,queryWrapper);
            return ResponseBean.success(result);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    // 客户列表 公客/私客
    @GetMapping("/admin/customer/recommend")
    public ResponseBean getCustomerList (HttpServletRequest request,
                                         @RequestParam(value ="name",required = false) String name,
                                         @RequestParam(value ="tel",required = false) String tel,
                                         @RequestParam(value ="buildingId",required = false) String buildingId,
                                         @RequestParam(value ="consultName",required = false) String consultName,
                                         @RequestParam(value ="consultTel",required = false) String consultTel,
                                         @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestParam(value ="entryType",required = false) String entryType,
                                         @RequestParam(value ="verifyStatus",required = false) String verifyStatus,
                                         @RequestParam(value = "sex",required = false)Integer sex,
                                         @RequestParam(value = "customerType") String customerType,// public 公  private 私
                                         @RequestParam(value = "status",required = false) Integer status,
                                         @RequestParam(value = "sceneType",required = false) String sceneType,
                                         @RequestParam(value = "startCreateDate",required = false) String startCreateDate,
                                         @RequestParam(value = "endCreateDate",required = false) String endCreateDate){
        try{

            // TODO 目前如果是公客，就取当前操作人员的 buildingId
//            if ("public".equals(customerType)) {
//                Map<String,Object> map = JWTUtils.getUserIdAndOrgId(request);
//                String userId = (String) map.get("userId");
//                QueryWrapper<TaPersonBuilding> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("user_id", userId);
//                queryWrapper.orderByDesc("create_date");
//                queryWrapper.last("limit 1");
//                TaPersonBuilding personBuilding = taPersonBuildingMapper.selectOne(queryWrapper);
//                buildingId = personBuilding.getBuildingId();
//            }
            return ResponseBean.success(taRecommendCustomerService.getCustomerList(status,pageNumber,pageSize,buildingId,name,tel,consultName,consultTel,entryType,verifyStatus,sex, customerType, getOrgId(request),getTaPersonBuildingListByUserId(request),sceneType, startCreateDate, endCreateDate));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    //推荐客户列表
    @GetMapping("/admin/customer/recommend/recommender")
    public ResponseBean getRecCustomerList (HttpServletRequest request,
                                         @RequestParam(value ="name",required = false) String name,
                                         @RequestParam(value ="tel",required = false) String tel,
                                         @RequestParam(value ="buildingId",required = false) String buildingId,
                                         @RequestParam(value ="consultName",required = false) String consultName,
                                         @RequestParam(value ="consultTel",required = false) String consultTel,
                                         @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestParam(value ="entryType",required = false) String entryType,
                                         @RequestParam(value ="verifyStatus",required = false) String verifyStatus,
                                         @RequestParam(value = "sex",required = false)Integer sex){
        try{
            return ResponseBean.success(taRecommendCustomerService.getRecCustomerList(pageNumber,pageSize,buildingId,name,tel,consultName,consultTel,entryType,verifyStatus,sex, getOrgId(request),getTaPersonBuildingListByUserId(request)));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    //报备客户列表
    @GetMapping("/admin/customer/recommend/report")
    public ResponseBean getRepCustomerList (@RequestParam(value ="name",required = false) String name,
                                         @RequestParam(value ="tel",required = false) String tel,
                                         @RequestParam(value ="buildingId",required = false) String buildingId,
                                         @RequestParam(value ="consultName",required = false) String consultName,
                                         @RequestParam(value ="consultTel",required = false) String consultTel,
                                         @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestParam(value ="entryType",required = false) String entryType,
                                         @RequestParam(value ="verifyStatus",required = false) String verifyStatus,
                                         @RequestParam(value = "sex",required = false)Integer sex, HttpServletRequest request){
        Integer orgid = getOrgId(request);
        try{
            return ResponseBean.success(taRecommendCustomerService.getRepCustomerList(pageNumber,pageSize,buildingId,name,tel,consultName,consultTel,entryType,verifyStatus,sex, orgid,getTaPersonBuildingListByUserId(request)));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }


    /**
     * 经纪人列表
     * @param name
     * @param tel
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping("/admin/customer/agents")
    public ResponseBean getIndependentAgents (HttpServletRequest request,
                                              @RequestParam(value ="name",required = false) String name,
                                            @RequestParam(value ="tel",required = false) String tel,
                                            @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                            @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        try{
            return ResponseBean.success(taRecommendCustomerService.getIndependentAgents(pageNumber,pageSize,name,tel, getOrgId(request)));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 分配置业顾问
     */
    @RequestMapping(value="/admin/customer/consultant/assist/{personId}",method= RequestMethod.POST)
    public ResponseBean assistConsultant (@RequestBody TaUser taUser, @PathVariable String personId, HttpServletRequest request){
        try{
            Integer orgId = getOrgId(request);
            taRecommendCustomerService.consultantAssist(taUser, personId, orgId);
            return ResponseBean.success("");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 批量分配置业顾问
     */
    @RequestMapping(value="/admin/customer/consultant/batchAssist",method= RequestMethod.POST)
    public ResponseBean batchAssistConsultant (@RequestBody TaUser taUser, HttpServletRequest request){
        if (CollectionUtils.isEmpty(taUser.getPersonIds())){
            return ResponseBean.error("请至少选择一条数据", ResponseBean.ERROR_UNAVAILABLE);
        }
        try{
            Integer orgId = getOrgId(request);
            taRecommendCustomerService.batchConsultantAssist(taUser, orgId);
            return ResponseBean.success("");
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/admin/customer/recommend/{customerId}")
    public ResponseBean getCustomersIRecommended (@RequestParam int pageNumber, @RequestParam int pageSize, @PathVariable String customerId,HttpServletRequest request){
        Integer orgId = getOrgId(request);
        try{
            return ResponseBean.success(taRecommendCustomerService.getCustomersIRecommended(pageNumber,pageSize,customerId,orgId,getTaPersonBuildingListByUserId(request)));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    @GetMapping("/wx/customer/recommend/mine")
    public ResponseBean getWxCustomersIRecommended (@RequestParam int pageNumber, @RequestParam int pageSize,HttpServletRequest request){
        Integer orgId =getOrgId(request);
        String openid = getOpenId(request);
        List<TaPerson> taPersons = taPersonService.getPersonsByOpenId(openid);
        if (null == taPersons || taPersons.size() != 1) {
            return ResponseBean.error("验证人员信息失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        TaPerson person = taPersons.get(0);
        try{
            return ResponseBean.success(taRecommendCustomerService.getCustomersIRecommended(pageNumber,pageSize,person.getPersonId(),orgId,null));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }



        /**
     * 修改对象
     * @param taRecommendCustomer 实体对象
     * @return
     */
    @RequestMapping(value="/wx/customer/recommend/edit/{customerId}",method= RequestMethod.PUT)
    public ResponseBean taRecommendCustomerUpdateWx(@PathVariable String customerId,
                                        @RequestBody TaRecommendCustomer taRecommendCustomer){
        ResponseBean responseBean = new ResponseBean();
        taRecommendCustomer.setCustomerId(customerId);
        try {
            if (taRecommendCustomerService.updateById(taRecommendCustomer)){
                responseBean.addSuccess(taRecommendCustomer);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
    /**
     * 修改对象
     * @param taRecommendCustomer 实体对象
     * @return
     */
    @RequestMapping(value="/admin/customer/recommend/edit/{id}",method= RequestMethod.PUT)
    public ResponseBean taRecommendCustomerUpdate(@PathVariable String id,
                                                  @RequestBody TaRecommendCustomer taRecommendCustomer){
        ResponseBean responseBean = new ResponseBean();
        taRecommendCustomer.setCustomerId(id);
        try {
            if (taRecommendCustomerService.updateById(taRecommendCustomer)){
                responseBean.addSuccess(taRecommendCustomer);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

//    /**
//     * 修改对象
//     * @param taRecommendCustomer 实体对象
//     * @return
//     */
//    @RequestMapping(value="/wx/customer/recommend/edit/{id}",method= RequestMethod.PUT)
//    public ResponseBean taWxRecommendCustomerUpdate(@PathVariable String id,
//                                                  @RequestBody TaRecommendCustomer taRecommendCustomer){
//        ResponseBean responseBean = new ResponseBean();
//        taRecommendCustomer.setCustomerId(id);
//        try {
//            if (taRecommendCustomerService.updateById(taRecommendCustomer)){
//                responseBean.addSuccess(taRecommendCustomer);
//            }else {
//                responseBean.addError("fail");
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            responseBean.addError(e.getMessage());
//        }
//        return responseBean;
//    }

    @RequestMapping(value = "/wx/customer/recommend/get/{customerId}", method = RequestMethod.GET)
    public ResponseBean getSingleCustomer(@PathVariable(value = "customerId") String customerId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taRecommendCustomerService.getById(customerId));
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    @RequestMapping(value = "/admin/customer/recommend/getById/{id}", method = RequestMethod.GET)
    public ResponseBean getRecommendCustomerById(@PathVariable(value = "id") String customerId) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taRecommendCustomerService.getCustomerById(customerId));
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    @GetMapping(value = "/admin/customer/recommend/get/{id}")
    public ResponseBean getCustomerDetail(@PathVariable String id,
                                          @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                          @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                          @RequestParam(value ="buildingId",required = false) String buildingId,
                                          HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taRecommendCustomerService.getCustomerDetail(id,pageNumber,pageSize,getTaPersonBuildingListByUserId(request),buildingId));
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @GetMapping(value = "/admin/customer/recommend/public/get/{id}")
    public ResponseBean getPublicCustomerDetail(@PathVariable String id,
                                                @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                                @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                                @RequestParam(value ="buildingId",required = false) String buildingId,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taRecommendCustomerService.getPublicCustomerDetail(id,pageNumber,pageSize,getTaPersonBuildingListByUserId(request),buildingId));
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    @GetMapping("/admin/customer/recommend/drift")
    public ResponseBean getDriftCustomerList (HttpServletRequest request,
                                              @RequestParam(value ="buildingId",defaultValue = "") String buildingId,
                                              @RequestParam(value ="sceneType",defaultValue = "") String sceneType,
                                         @RequestParam(value ="pageNumber",defaultValue = "1") Integer pageNumber,
                                         @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize){
        try{
            return ResponseBean.success(taPersonService.getDriftCustomerList(pageNumber,pageSize,buildingId, getOrgId(request),sceneType));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBean.error(e.getMessage(),ResponseBean.ERROR_UNAVAILABLE);
        }
    }

    /**
     * 修改对象
     * @return
     */
    @RequestMapping(value="/admin/customer/recommend/verify/{id}",method= RequestMethod.PUT)
    public ResponseBean taRecommendCustomerVerify(@PathVariable String id,@RequestParam Integer verifyStatus, @RequestParam(required = false) String verifyRemark, HttpServletRequest request){
        if (null == verifyStatus) {
            return ResponseBean.error("审核结果非法", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        Integer orgId = getOrgId(request);
        ResponseBean responseBean = new ResponseBean();
        try {
            TaRecommendCustomer taRecommendCustomer = taRecommendCustomerService.getById(id);
            if(null == taRecommendCustomer.getVerifyStatus() || 0 == taRecommendCustomer.getVerifyStatus().intValue()){ // taRecommendCustomer.getVerifyStatus().equals(CommConstant.VERIFY_READY)
                taRecommendCustomer.setVerifyStatus(verifyStatus);
                if(!StringUtils.isEmpty(verifyRemark)){
                    taRecommendCustomer.setVerifyRemark(verifyRemark);
                    if(CommConstant.CUSTOMER_REPORT.equals(taRecommendCustomer.getReportRecommendStatus())){
                        taRecommendCustomer.setRealtyConsultant(taRecommendCustomer.getRecommendPerson());
                    }
                }

                // 审核不通过的时候，移除置业顾问选择
                if (CommConstant.VERIFY_DISAGREE == verifyStatus) {
                    taRecommendCustomer.setRealtyConsultant(null);
                }

                if (taRecommendCustomerService.updateById(taRecommendCustomer)){

                    // 审核通过增加积分
                    if (CommConstant.VERIFY_AGREE == verifyStatus) {
                        applicationContext.publishEvent(new EventBus(taRecommendCustomer, EventBus.EventType.RecommendCustomer, orgId));
                    }

                    responseBean.addSuccess(taRecommendCustomer);
                }else {
                    responseBean.addError("fail");
                }
            } else {
                responseBean.addSuccess("客户已审核");
            }

        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 导出数据(推荐客户列表)
     */
    @GetMapping("/admin/customer/recommend/recommender/export")
    public void export(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=推荐客户.xlsx");

        Integer count = taRecommendCustomerService.getRecCustomerExportCount(getOrgId(request),getTaPersonBuildingListByUserId(request));

        Integer pageCode = 0;
        Integer pageSize = 100;
        // 总页数
        Integer pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
        // 设置读取的class
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ExcelRecommendCustomer.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("推荐客户").build();
        do {
            List<ExcelRecommendCustomer> recCustomerExport = taRecommendCustomerService.getRecCustomerExport(getOrgId(request), pageCode * pageSize, pageSize,getTaPersonBuildingListByUserId(request));
            excelWriter.write(recCustomerExport, writeSheet);

            pageCode ++;
        } while (pageCode <= pageCount);

        /// finish 会帮忙关闭流
        excelWriter.finish();

    }


    /**
     * 导出数据(报备客户)
     */
    @GetMapping("/admin/customer/recommend/report/export")
    public void reportExport(HttpServletRequest request,
                             HttpServletResponse response,
                             @RequestParam(value ="name",required = false) String name,
                             @RequestParam(value ="tel",required = false) String tel,
                             @RequestParam(value ="buildingId",required = false) String buildingId,
                             @RequestParam(value ="consultName",required = false) String consultName,
                             @RequestParam(value ="consultTel",required = false) String consultTel,
                             @RequestParam(value ="entryType",required = false) String entryType,
                             @RequestParam(value ="verifyStatus",required = false) String verifyStatus,
                             @RequestParam(value = "sex",required = false)Integer sex) throws IOException {
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=报备客户.xlsx");

        Integer count = taRecommendCustomerService.getRepCustomerReportCount(buildingId,name,tel,consultName,consultTel,entryType,verifyStatus,sex,getOrgId(request),getTaPersonBuildingListByUserId(request));

        Integer pageCode = 0;
        Integer pageSize = 100;
        // 总页数
        Integer pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
        // 设置读取的class
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ReporRecommendCustomer.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("报备客户").build();
        List<ReporRecommendCustomer> recCustomerExport = null;
        do {
            recCustomerExport = taRecommendCustomerService.getRepCustomerReportExport(buildingId, name, tel, consultName, consultTel, entryType, verifyStatus, sex, getOrgId(request), pageCode * pageSize, pageSize,getTaPersonBuildingListByUserId(request));
            excelWriter.write(recCustomerExport, writeSheet);

            pageCode ++;
        } while (pageCode <= pageCount);

        /// finish 会帮忙关闭流
        excelWriter.finish();

    }

    /**
     * 导出数据(经纪人)
     */
    @GetMapping("/admin/customer/recommend/agents/export")
    public void agentsExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=经纪人.xlsx");

        Integer count = taRecommendCustomerService.getIndependentAgentsCount(getOrgId(request));

        Integer pageCode = 0;
        Integer pageSize = 100;
        // 总页数
        Integer pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
        // 设置读取的class
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), AgentsRecommendCustomer.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("经纪人").build();
        List<AgentsRecommendCustomer> recCustomerExport = null;
        do {
            recCustomerExport = taRecommendCustomerService.getIndependentAgentsExport(getOrgId(request), pageCode * pageSize, pageSize);
            excelWriter.write(recCustomerExport, writeSheet);

            pageCode ++;
        } while (pageCode <= pageCount);

        /// finish 会帮忙关闭流
        excelWriter.finish();

    }



    // 客户列表 公客/私客

    /**
     * 导出数据 客户列表 公客/私客
     * @param request
     * @param response
     * @param name
     * @param tel
     * @param buildingId
     * @param consultName
     * @param consultTel
     * @param entryType
     * @param verifyStatus
     * @param sex
     * @param customerType
     * @param status
     * @throws IOException
     */
    @GetMapping("/admin/customer/recommend/export")
    public void getCustomerExportList (HttpServletRequest request,
                                         HttpServletResponse response,
                                         @RequestParam(value ="name",required = false) String name,
                                         @RequestParam(value ="tel",required = false) String tel,
                                         @RequestParam(value ="buildingId",required = false) String buildingId,
                                         @RequestParam(value ="consultName",required = false) String consultName,
                                         @RequestParam(value ="consultTel",required = false) String consultTel,
                                         @RequestParam(value ="entryType",required = false) String entryType,
                                         @RequestParam(value ="verifyStatus",required = false) String verifyStatus,
                                         @RequestParam(value = "sex",required = false)Integer sex,
                                         @RequestParam(value = "customerType") String customerType,
                                         @RequestParam(value = "status",required = false) Integer status,
                                       @RequestParam(value = "sceneType",required = false) String sceneType) throws IOException { // public 公  private 私

        //        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=经纪人.xlsx");

        Integer orgId = getOrgId(request);

        Integer pageCode = 0;
        Integer pageSize = 100;
        // 总页数
        Integer pageCount = 0;

        if (CommConstant.CUTOMER_TYPE_PUBLIC.equals(customerType)) {
            /**
             * 公客
             */

            // 设置读取的class
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), PublicCustomerExport.class).registerWriteHandler(new CustomCellWriteHandler()).build();
            // 设置 sheet, 同一个sheet只需要设置一次
            WriteSheet writeSheet = EasyExcel.writerSheet("客户列表-公客").build();

//            Integer count = taRecommendCustomerMapper.getPublicCustomerExportListCount(name, tel,  entryType, verifyStatus, sex, orgId,consultTel);
//            pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
//            List<PublicCustomerExport> publicList = null;
//            do {
                List<PublicCustomerExport> publicList = taRecommendCustomerMapper.getPublicCustomerExportList(pageCode * pageSize, pageSize, buildingId, name, tel,  entryType, verifyStatus, sex, orgId,consultTel,sceneType,getTaPersonBuildingListByUserId(request));
                excelWriter.write(publicList, writeSheet);

//                pageCode ++;
//            } while (pageCode <= pageCount);

            // finish 会帮忙关闭流
            excelWriter.finish();
        } else {
            /**
             * 私客
             */

            // 设置读取的class
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), PrivateCustomerExport.class).registerWriteHandler(new CustomCellWriteHandler()).build();
            // 设置 sheet, 同一个sheet只需要设置一次
            WriteSheet writeSheet = EasyExcel.writerSheet("客户列表-私客").build();

//            Integer count = taRecommendCustomerMapper.getCustomerExportListCount(buildingId, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId,status,getTaPersonBuildingListByUserId(request));
//            pageCount = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
//            List<PrivateCustomerExport> privateList = null;
//            do {
                List<PrivateCustomerExport> privateList = taRecommendCustomerMapper.getCustomerExportList(pageCode *  pageSize, pageSize, buildingId, name, tel, consultName, consultTel, entryType, verifyStatus, sex, orgId,status,sceneType,getTaPersonBuildingListByUserId(request));
                excelWriter.write(privateList, writeSheet);

//                pageCode ++;
//            } while (pageCode <= pageCount);
            // finish 会帮忙关闭流
            excelWriter.finish();

        }


    }
    
    /**
     * 查询判客工具下的我的客户人数集合
     * @param request
     * @return
     */
    @GetMapping("/wx/inventory/customer/statistics")
    @ApiOperation(value = "查询我的客户人数统计", notes = "查询我的客户人数统计")
    public ResponseBean getMyCustStatistics(HttpServletRequest request) {
        String openid = getOpenId(request);
        return taRecommendCustomerService.getMyCustStatistics(openid);
    }
    
    /**
     * 分页查询判客工具下的我的客户跟进人集合
     *  根据type区分  follow 跟进  clinch 成交
     * @param request
     * @return
     */
    @GetMapping("/wx/inventory/customer/statistics/{type}")
    @ApiOperation(value = "查询我的客户人数统计", notes = "查询我的客户人数统计")
    public ResponseBean getMyCustFollows(@PathVariable(value = "type") String type,
                                         @RequestParam(value = "pageNumber",defaultValue = "0") Integer pageNumber,
                                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                         @RequestParam(value = "name",required = false) String name,
                                         @RequestParam(value = "phone",required = false) String phone,
                                         @RequestParam(value = "status",required = false) Integer status,
                                         @RequestParam(value = "startReportDate",required = false) String startReportDate,
                                         @RequestParam(value = "endReportDate",required = false) String endReportDate,
                                         @RequestParam(value = "startArrivalDate",required = false) String startArrivalDate,
                                         @RequestParam(value = "endArrivalDate",required = false) String endArrivalDate,
                                         HttpServletRequest request) {
        String openid = getOpenId(request);
        return taRecommendCustomerService.getMyCustFollowOrClinch(pageNumber,pageSize,openid,type,name,phone,status,startReportDate,endReportDate,startArrivalDate,endArrivalDate);
    }
    
    /**
     * 查询盘客工具下我的客户详情
     * @param request
     * @return
     */
    @GetMapping("/wx/inventory/customer/{customerId}")
    @ApiOperation(value = "查询客户详情", notes = "查询客户详情")
    public ResponseBean getMyCustDetail(@PathVariable(value = "customerId") String customerId,HttpServletRequest request) {
        String openid = getOpenId(request);
        return taRecommendCustomerService.getMyCustDetail(customerId,openid);
    }
    
    /**
     * 查询盘客工具下编辑基本信息
     * @param request
     * @return
     */
    @PutMapping("/wx/inventory/customer/{customerId}")
    @ApiOperation(value = "编辑客户信息", notes = "编辑客户信息")
    public ResponseBean updateMyCustDetail(@PathVariable(value = "customerId") String customerId,
                                           @RequestBody TaRecommendCustomer taRecommendCustomer, HttpServletRequest request) {
        String openid = getOpenId(request);
        taRecommendCustomer.setCustomerId(customerId);
        return taRecommendCustomerService.updateMyCust(taRecommendCustomer,openid);
    }
}
