package com.huiju.estateagents.controller;


import com.alibaba.fastjson.JSONObject;
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.huiju.estateagents.base.BaseController;
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.SMSUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaChannel;
import com.huiju.estateagents.entity.TaChannelPerson;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaPersonBuilding;
import com.huiju.estateagents.service.ITaPersonBuildingService;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.TaChannelPersonService;
import com.huiju.estateagents.service.TaChannelService;
import com.huiju.estateagents.third.entity.TaThirdPartyMiniappConfig;
import com.huiju.estateagents.third.service.ITaThirdPartyMiniappConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 人员表 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@RestController
@RequestMapping("/api")
public class TaPersonController extends BaseController {
    @Autowired
    ITaPersonService taPersonService;
    @Autowired
    TaChannelService taChannelService;
    @Autowired
    TaChannelPersonService taChannelPersonService;
    @Autowired
    ITaUserService taUserService;
    @Autowired
    SMSUtils smsUtils;
    @Autowired
    ITaPersonBuildingService taPersonBuildingService;

    @Autowired
    public ITaThirdPartyMiniappConfigService iTaThirdPartyMiniappConfigService;

    /**
     *
     *  因为人员表是集合系统的所有种类的用户，包含了各种角色。因此各种角色的操作都在本 controller 中完成
     *  以下是置业顾问卡片内容
     *
     */

    /**
     * 获取卡片列表
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @GetMapping("/wx/cards")
    public ResponseBean getCardList(@RequestParam(defaultValue = "1") int pageNumber,
                                    @RequestParam(defaultValue = "10") int pageSize,
                                    @RequestParam(defaultValue = "false") boolean mine,
                                    @RequestParam(value = "buildingId", required = false)String buildingId,
                                    HttpServletRequest request) {
        if (pageNumber < 0 || pageSize < 0) {
            return ResponseBean.error("分页参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        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);

        if (mine){
            IPage<Map<String, Object>>  result = taPersonService.getSavedConsaultants(pageNumber,pageSize,person.getPersonId());
            return ResponseBean.success(result);
        }else {
            IPage<Map<String, Object>> result = taPersonService.getCardList(pageNumber, pageSize,buildingId,orgId, person);
            return ResponseBean.success(result);
        }


    }

    @PutMapping("/wx/registerConsultant")
    public ResponseBean registerConsultant(HttpServletRequest request,@RequestParam String phone,@RequestParam String code) {
        ResponseBean responseBean = new ResponseBean();
        if(!smsUtils.checkCaptcha(phone,code)){
            responseBean.addError("验证码错误。");
            return responseBean;
        }
        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);
        QueryWrapper<TaUser>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        queryWrapper.eq("org_id",orgId);
        queryWrapper.eq("is_consultant",true);
        List<TaUser> users = taUserService.list(queryWrapper);
        if(users.size()>0){
            TaUser user = users.get(0);
            person.setPersonType(CommConstant.PERSON_REALTY_CONSULTANT);
            person.setUserId(user.getUserId());
            person.setAvatarurl(user.getAvatar());
            person.setCompany(user.getOrgName());
            person.setTel(user.getPhone());
            person.setName(user.getUserName());
            person.setAddress(user.getAddress());
            person.setIdNo(user.getIdNo());
            person.setDepartment(user.getDepartment());
            person.setPost(user.getPosition());
            person.setPhoto(user.getPhoto());
            if(StringUtils.isEmpty(person.getPhone())){
                person.setPhone(user.getPhone());
            }
            taPersonService.updateById(person);
            responseBean.addSuccess(person);
        }else {
            responseBean.addError("此手机号未录入到后台系统，请联系营销云管理员。");
        }
        return responseBean;
    }

    @PutMapping("/wx/registerConsultantOneClick")
    public ResponseBean registerConsultantOneClick(HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        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);
        if (person.getPersonType().equals(CommConstant.PERSON_REALTY_CONSULTANT)){
            return ResponseBean.error("您已经成为置业顾问",ResponseBean.ERROR_UNAVAILABLE);
        }
        QueryWrapper<TaUser>queryWrapper = new QueryWrapper<>();
        queryWrapper.nested(query -> query.eq("phone", person.getTel()).or().eq("phone", person.getPhone()));
        queryWrapper.eq("org_id",orgId);
        queryWrapper.eq("status",CommConstant.STATUS_NORMAL);
        queryWrapper.eq("is_consultant",true);
        List<TaUser> users = taUserService.list(queryWrapper);

        if(users.size()>0){
            TaUser user = users.get(0);
            person.setPersonType(CommConstant.PERSON_REALTY_CONSULTANT);
            person.setUserId(user.getUserId());
            person.setAvatarurl(user.getAvatar());
            person.setCompany(user.getOrgName());
            person.setTel(user.getPhone());
            person.setName(user.getUserName());
            person.setAddress(user.getAddress());
            person.setIdNo(user.getIdNo());
            person.setDepartment(user.getDepartment());
            person.setPost(user.getPosition());
            person.setPhoto(user.getPhoto());
            taPersonService.updateById(person);
            responseBean.addSuccess(person);
        }else {
            responseBean.addError("手机号不存在,请联系管理员维护。");
            return responseBean;
        }

        TaChannelPerson taChannelPerson = new TaChannelPerson();
        taChannelPerson.setStatus(CommConstant.STATUS_DELETE);
        QueryWrapper<TaChannelPerson> taChannelPersonQueryWrapper = new QueryWrapper<>();
        taChannelPersonQueryWrapper.eq("person_id", person.getPersonId());
        taChannelPersonService.update(taChannelPerson, taChannelPersonQueryWrapper);

        return responseBean;
    }

    @PutMapping("/wx/registerAgent")
    public ResponseBean registerAgent(@RequestParam(required = false) String recommendAgentCode, @RequestParam(required = false) String channelCode,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        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);
        person.setAgentCode(taPersonService.agentCodeGenerator());
        if (!StringUtils.isEmpty(recommendAgentCode)){
            QueryWrapper<TaPerson> agentWrapper = new QueryWrapper();
            agentWrapper.eq("agent_code",recommendAgentCode);
            agentWrapper.eq("org_id",orgId);
            TaPerson agent = taPersonService.getOne(agentWrapper);
            if (null != agent){
                person.setRecommendAgent(agent.getPersonId());
            }
        }
        if(StringUtils.isEmpty(channelCode)){
            person.setPersonType(CommConstant.PERSON_ESTATE_AGENT);
        }else {
            person.setPersonType(CommConstant.PERSON_ESTATE_AGENT);
            QueryWrapper<TaChannel> queryWrapper = new QueryWrapper();
            queryWrapper.eq("channel_code",channelCode);
            queryWrapper.eq("org_id",orgId);
            TaChannel channel = taChannelService.getOne(queryWrapper);
            if (null == channel){
                return ResponseBean.error("验证码有误，请确认后重新输入",ResponseBean.ERROR_UNAVAILABLE);
            }
            QueryWrapper<TaChannelPerson>taChannelPersonQueryWrapper = new QueryWrapper<>();
            taChannelPersonQueryWrapper.eq("person_id",person.getPersonId());
            taChannelPersonQueryWrapper.eq("channel_id",channel.getChannelId());
            taChannelPersonQueryWrapper.eq("status",CommConstant.STATUS_NORMAL);
            int count = taChannelPersonService.count(taChannelPersonQueryWrapper);
            if(count>0){
                return ResponseBean.error("您已绑定过该渠道",ResponseBean.ERROR_UNAVAILABLE);
            }
            TaChannelPerson channelPerson = new TaChannelPerson();
            channelPerson.setChannelId(channel.getChannelId());
            channelPerson.setPersonId(person.getPersonId());
            channelPerson.setCreateDate(LocalDateTime.now());
            channelPerson.setStatus(CommConstant.STATUS_NORMAL);
            taChannelPersonService.save(channelPerson);
        }
        taPersonService.updateById(person);
        responseBean.addSuccess(person);

        return responseBean;
    }

    /**
     * 绑定卡片
     * @param paramStr
     * @return
     */
    @PostMapping("/wx/cards/apply")
    public ResponseBean applyCard(@RequestBody String paramStr, HttpServletRequest request) {
        JSONObject params = JSONObject.parseObject(paramStr);
        String phone = (String) params.get("phone");
        String pass = (String) params.get("pass");
        String openid = getOpenId(request);

        if (isEmpty(phone) || isEmpty(pass)) {
            return ResponseBean.error("参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        ResponseBean resp = taPersonService.checkPhoneAndPass(phone, pass);

        // 成功返回空数据
        if (resp.getCode() != ResponseBean.CODE_SUCCESS) {
            return resp;
        }

        return taPersonService.bindCard(phone, pass, openid);
    }

    /**
     * 获取名片详情
     * @param id
     * @return
     */
    @GetMapping("/wx/cards/{id}")
    public ResponseBean getCardDetail(@PathVariable String id, HttpServletRequest request) {
        if (isEmpty(id)) {
            return ResponseBean.error("参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        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);
//        QueryWrapper<TaPersonBuilding>queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id",person.getUserId());
//        TaPersonBuilding personBuilding = taPersonBuildingService.getOne(queryWrapper);

        return taPersonService.getCardDetail(openid, id,person.getPersonId());
    }

    /**
     * 获取名片详情
     * @param id
     * @return
     */
    @GetMapping("/wx/onePerson/{id}")
    public ResponseBean getPersonByPersonId(@PathVariable String id, HttpServletRequest request) {
        if (isEmpty(id)) {
            return ResponseBean.error("参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }
        TaPerson person = taPersonService.getById(id);
        return ResponseBean.success(person);
    }

    /**
     * 找回密码
     * @param plat 平台类型 wx 是微信相关, admin 是后台管理系统
     * @param paramStr
     * @return
     */
    @PostMapping("/{plat}/resetPass")
    public ResponseBean resetPassword(@PathVariable String plat, @RequestBody String paramStr) {
        JSONObject params = JSONObject.parseObject(paramStr);
        String phone = (String) params.get("phone");
        String code = (String) params.get("code");
        String pass = (String) params.get("pass");

        if (isEmpty(phone) || isEmpty(code) || isEmpty(pass)) {
            return ResponseBean.error("参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        // todo
        // 验证 验证码是否正确
        if (code != "1234") {
            return ResponseBean.error("验证码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        return taPersonService.resetPassword(phone, pass, plat);
    }


    /**
     *
     *  以下是经纪人部分
     *
     */


    /**
     * 注册经纪人
     * @param paramStr
     * @param request
     * @return
     */
    @PostMapping("/wx/register")
    public ResponseBean resgiteAgent(@RequestBody String paramStr, HttpServletRequest request) {
        JSONObject params = JSONObject.parseObject(paramStr);
        String name = (String) params.get("name");
        String phone = (String) params.get("phone");
        Integer sex = (Integer) params.get("sex");
        String explain = (String) params.get("explain");

        if (isEmpty(name) || isEmpty(phone) || isEmpty(explain)) {
            return ResponseBean.error("请检查部分参数不能为空", ResponseBean.ERROR_ILLEGAL_PARAMS);
        }

        // 当前人员
        String openid = getOpenId(request);

        return taPersonService.resgiteAgent(name, phone, sex, explain, openid);
    }

    /**
     * 生成海报
     * @param paramStr
     * @param request
     * @return
     */
    @PostMapping("/wx/poster")
    public ResponseBean genPoster(@RequestBody String paramStr, HttpServletRequest request) {
        return null;
    }


    /**
     *
     * 以下是个人中心部分
     *
     */

    /**
     * 获取个人信息
     * @param request
     * @return
     */
    @GetMapping("/wx/user/info")
    public ResponseBean getUserInfo(HttpServletRequest request) {
        String openid = getOpenId(request);

        return taPersonService.getWxUser(openid);
    }

    /**
     * 第三方获取个人信息
     * @param request
     * @return
     */
    @GetMapping("/third/user/info")
    public ResponseBean thirdGetUserInfo(@RequestParam("personId") String personId,  HttpServletRequest request) {
        //获取H5项目相关信息
        String xAppid = request.getHeader("x-appid");
        QueryWrapper<TaThirdPartyMiniappConfig> taThirdPartyMiniappConfigQueryWrapper = new QueryWrapper<>();

        taThirdPartyMiniappConfigQueryWrapper.eq("appid", xAppid);
        TaThirdPartyMiniappConfig taThirdPartyMiniappConfig = iTaThirdPartyMiniappConfigService.getOne(taThirdPartyMiniappConfigQueryWrapper);
        if (null == taThirdPartyMiniappConfig){
            return ResponseBean.error("不存在的H5活动",ResponseBean.ERROR_UNAVAILABLE);
        }
        return taPersonService.ThirdUserInfo(personId);
    }

    /**
     * 个人getPersonId(request);
     * @param request
     * @return
     */
    @PostMapping("/wx/user/signin")
    public ResponseBean userSign(HttpServletRequest request) {
        String openid = getOpenId(request);
        Integer orgId = getOrgId(request);

        return taPersonService.getWxUserSign(openid, orgId);
    }


    /**
     *
     *
     *  以下是系统用户管理
     *
     */

    /**
     * 用户手机号登录
     * @param paramStr
     * @return
     */
//    @PostMapping("/admin/signin")
//    public ResponseBean signin(@RequestBody String paramStr) {
//        JSONObject params = JSONObject.parseObject(paramStr);
//        if (params == null) {
//            return ResponseBean.error("非法参数", ResponseBean.ERROR_MISSING_PARAMS);
//        }
//
//        String userPhone = params.getString("phone");
//        String userCaptcha = params.getString("captcha");
//
//        // todo
//        if (!"1234".equals(userCaptcha)) {
//            return ResponseBean.error("验证码不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
//        }
//
//        TaPerson taPerson = taPersonService.getPersonByTel(userPhone);
//        if (taPerson == null) {
//            return ResponseBean.error("手机号不存在", ResponseBean.ERROR_ILLEGAL_PARAMS);
//        }
//
//        if (taPerson.getStatus() != CommConstant.STATUS_NORMAL) {
//            return ResponseBean.error("用户状态异常", ResponseBean.ERROR_UNAVAILABLE);
//        }
//
//        String token = JWTUtils.newToken(taPerson.getPersonId());
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("token", token);
//        result.put("person", taPerson);
//
//        return ResponseBean.success(result);
//    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    @GetMapping("/admin/user/current")
    public ResponseBean getCurrentPerson(HttpServletRequest request) {
        String personId = getPersonId(request);
        TaPerson taPerson = taPersonService.getById(personId);
        if (null == taPerson || taPerson.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("用户状态异常", ResponseBean.ERROR_AUTH_EXPIRED);
        }

        return ResponseBean.success(taPerson);
    }

    @GetMapping("/admin/consultant")
    public ResponseBean getConsultantList(
            Integer pageNumber,
            Integer pageSize,
            String name,
            String phone,
            Integer status,
            String buildingId,
            String personTags
    ) {
        if (null == pageNumber) pageNumber = 1;
        if (null == pageSize) pageSize = 10;

        IPage<TaPerson> taPersonIPage = taPersonService.getPersonList(pageNumber, pageSize, CommConstant.PERSON_REALTY_CONSULTANT, name, phone,status,buildingId,personTags);
        return ResponseBean.success(taPersonIPage);
    }

    @GetMapping("/admin/building/consultant")
    public ResponseBean getBuildingConsultantList(
            Integer pageNumber,
            Integer pageSize,
            String buildingId
    ) {
        if (null == pageNumber) pageNumber = 1;
        if (null == pageSize) pageSize = 10;

        IPage<TaUser> taPersonIPage = taPersonService.getBuildingConsultantList(pageNumber,pageSize,buildingId);
        return ResponseBean.success(taPersonIPage);
    }

    @GetMapping("/wx/building/consultant")
    public ResponseBean getWxBuildingConsultantList(
            Integer pageNumber,
            Integer pageSize,
            String buildingId
    ) {
        if (null == pageNumber) pageNumber = 1;
        if (null == pageSize) pageSize = 10;

        IPage<TaUser> taPersonIPage = taPersonService.getBuildingConsultantList(pageNumber,pageSize,buildingId);
        return ResponseBean.success(taPersonIPage);
    }

    @GetMapping("/admin/consultant/{id}")
    public ResponseBean getConsultant(@PathVariable String id) {
        TaPerson taPerson = taPersonService.getById(id);

        List<TaPersonBuilding> buildings = taPersonService.getPersonBuildings(id);
        if (null != buildings && buildings.size() > 0) {
            List<String> projects = new ArrayList<>();
            for (TaPersonBuilding b : buildings) {
                projects.add(b.getBuildingId());
            }
            taPerson.setProjects(projects);
        }

        return ResponseBean.success(taPerson);
    }

    @PostMapping("/admin/consultant")
    public ResponseBean newConsultant(@RequestBody String paramStr) {
        return taPersonService.newConsultant(paramStr);
    }

    @PutMapping("/admin/consultant/{id}")
    public ResponseBean editConsultant(@PathVariable String id, @RequestBody String paramStr) {
        return taPersonService.editConsultant(id, paramStr);
    }

    @PutMapping("/wx/editPerson")
    public ResponseBean editWxConsultant(@RequestParam(required = false)String name,@RequestParam(required = false)String avatar,@RequestParam(required = false)String phone,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        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);
        if (!StringUtils.isEmpty(name)){
            person.setName(name);
        }
        if (!StringUtils.isEmpty(avatar)){
            person.setAvatarurl(avatar);
        }
        if (!StringUtils.isEmpty(phone)){
            person.setTel(phone);
//            person.setPhone(phone);
            if(person.getPersonType().equals(CommConstant.PERSON_REALTY_CONSULTANT)){
                TaUser user = taUserService.getById(person.getUserId());
                user.setPhone(phone);
                user.setLoginName(phone);
                taUserService.updateById(user);
            }
        }
        try{
            if(taPersonService.updateById(person)){
                responseBean.addSuccess(person);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){

        }
        return responseBean;
    }

    boolean isEmpty(String str) {
        return null == str || "".equals(str.trim());
    }

    /**
//     * 获取收藏置业顾问列表
//     * @param pageNumber
//     * @param pageSize
//     * @return
//     */
//    @GetMapping("/wx/savedPerson")
//    public ResponseBean getSavedConsaultants(@RequestParam(defaultValue = "1") int pageNumber,
//                                    @RequestParam(defaultValue = "10") int 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);
//        if (pageNumber < 0 || pageSize < 0) {
//            return ResponseBean.error("分页参数不正确", ResponseBean.ERROR_ILLEGAL_PARAMS);
//        }
//        try {
//            IPage<TaPerson> result = taPersonService.getSavedConsaultants(pageNumber,pageSize,person.getPersonId());
//            return ResponseBean.success(result);
//        }catch (Exception e){
//            e.printStackTrace();
//            return ResponseBean.error("查询失败", ResponseBean.ERROR_UNAVAILABLE);
//        }
//
//    }
    /**
     * 变更经纪人类型
     * @param channelCode 渠道码
     * @return
     */
    @RequestMapping(value="/wx/customer/recommend/becomeChannel",method= RequestMethod.PUT)
    public ResponseBean taRecommendAgentBecomeChannel(@RequestParam(required = false) String channelCode,HttpServletRequest request,@RequestParam("personType")String personType){
        ResponseBean responseBean = new ResponseBean();

        if (org.apache.commons.lang3.StringUtils.isBlank(personType)) {
            responseBean.addSuccess("personType为空");
            return responseBean;
        }

        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 {
            if(CommConstant.PERSON_ESTATE_CHANNEL.equals(personType)){
                QueryWrapper<TaChannel>channelQueryWrapper = new QueryWrapper<>();
                channelQueryWrapper.eq("channel_code",channelCode);
                channelQueryWrapper.eq("org_id",getOrgId(request));
                QueryWrapper<TaChannelPerson>channelPersonQueryWrapper = new QueryWrapper<>();
                List<TaChannel> channel = taChannelService.list(channelQueryWrapper);
                if(channel.size()>0){
                    channelPersonQueryWrapper.eq("person_id",person.getPersonId());
                    channelPersonQueryWrapper.eq("channel_id",channel.get(0).getChannelId());
                    channelPersonQueryWrapper.eq("status",CommConstant.STATUS_NORMAL);
                    int count = taChannelPersonService.count(channelPersonQueryWrapper);
                    if(count >0){
                        return ResponseBean.error("您已绑定过渠道",ResponseBean.ERROR_UNAVAILABLE);
                    }
                    TaChannelPerson channelPerson = new TaChannelPerson();
                    channelPerson.setCreateDate(LocalDateTime.now());
                    channelPerson.setPersonId(person.getPersonId());
                    channelPerson.setChannelId(channel.get(0).getChannelId());
                    channelPerson.setStatus(CommConstant.STATUS_NORMAL);
                    taChannelPersonService.save(channelPerson);
                }else {
                    return ResponseBean.error("渠道码错误", ResponseBean.ERROR_UNAVAILABLE);
                }

            }
            //编辑个人信息暂时不修改经纪人类型
//            else {
//
//                QueryWrapper<TaChannelPerson>channelPersonQueryWrapper = new QueryWrapper<>();
//                channelPersonQueryWrapper.eq("person_id",person.getPersonId());
//                List<TaChannelPerson> taChannelPerson = taChannelPersonService.list(channelPersonQueryWrapper);
//                if (taChannelPerson.size()>0){
//                    for(int i=0;i<taChannelPerson.size();i++){
//                        taChannelPerson.get(i).setStatus(CommConstant.STATUS_DELETE);
//                    }
//                    taChannelPersonService.updateBatchById(taChannelPerson);
//                }
//            }
            person.setPersonType(personType);
            if (taPersonService.updateById(person)){
                responseBean.addSuccess(person);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 获取名片详情
     * @return
     */
    @GetMapping("/wx/agent/recommend/mine")
    public ResponseBean getAgentIRecommend(@RequestParam(defaultValue = "1") int pageNumber,
                                           @RequestParam(defaultValue = "10") int 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);
        QueryWrapper<TaPerson>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recommend_agent",person.getPersonId());
        queryWrapper.eq("person_type", CommConstant.PERSON_ESTATE_AGENT);
        queryWrapper.eq("status",CommConstant.STATUS_NORMAL);
        Page<TaPerson>page = new Page<>();
        page.setPages(pageNumber);
        page.setCurrent(pageNumber);
        page.setSize(pageSize);
        ResponseBean responseBean = new ResponseBean();
        IPage<TaPerson>data = taPersonService.page(page,queryWrapper);
        responseBean.addSuccess(data);

        return responseBean;
    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    @GetMapping("/wx/user/current")
    public ResponseBean getWxCurrentPerson(HttpServletRequest request) {
        String personId = getPersonId(request);
        TaPerson taPerson = taPersonService.getById(personId);
        if (null == taPerson || taPerson.getStatus() != CommConstant.STATUS_NORMAL) {
            return ResponseBean.error("用户状态异常", ResponseBean.ERROR_AUTH_EXPIRED);
        }

        return ResponseBean.success(taPerson);
    }

    
    /**
     * 微信添加人员添加城市
     * @param params
     * @param request
     * @return
     */
    @PutMapping("/wx/person/city")
    public ResponseBean updatePersonCity(@RequestBody String params, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        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);
        JSONObject jsonObject = JSONObject.parseObject(params);
        String lat = jsonObject.getString("lat");
        String lon = jsonObject.getString("lon");
        String location = lon+","+lat;
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject("https://restapi.amap.com/v3/geocode/regeo?key="+ CommConstant.GD_KEY + "&location=" +location+ "&output=json", String.class);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!resultJson.getString("status").equals(CommConstant.STATUS_NORMAL)){
            String adcode =  resultJson.getJSONObject("regeocode").getJSONObject("addressComponent").getString("adcode");
            String cityName =  resultJson.getJSONObject("regeocode").getJSONObject("addressComponent").getString("city");
            adcode = adcode.substring(0,adcode.length()-2) + "00";
            person.setCity(adcode);
            taPersonService.updateById(person);
            Map<Object,Object> data = new HashMap<>();
            data.put("cityName",cityName);
            data.put("cityCode",adcode);
            responseBean.addSuccess(data);
            return responseBean;
        }
        responseBean.addError("未找到城市");
        return responseBean;
    }

    @PutMapping("/wx/userInfo/updatePhoto")
    public ResponseBean updateUserPhoto(@RequestBody Map<String, String> photoUrl, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();

        String openId = getOpenId(request);
        String imgUrl = photoUrl.get("photoUrl");
        if (StringUtils.isEmpty(imgUrl)){
            responseBean.addError("请上传图片");
            return responseBean;
        }
        return taPersonService.updateUserPhoto(imgUrl, openId);
    }
}
