package com.gic.haoban.manage.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.gic.haoban.manage.web.vo.EnterpriseConfigVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.dict.api.dto.DictDTO;
import com.gic.dict.api.service.ManagerDictService;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.AccountService;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.app.customer.dto.ChildDTO;
import com.gic.haoban.app.customer.dto.CustomerDTO;
import com.gic.haoban.app.customer.dto.FilterListDTO;
import com.gic.haoban.app.customer.dto.MemberInfoListParamsDTO;
import com.gic.haoban.app.customer.dto.StaffOpenRelatedDTO;
import com.gic.haoban.app.customer.service.api.service.CustomerApiService;
import com.gic.haoban.app.customer.service.api.service.StaffMemberRelationApiService;
import com.gic.haoban.common.anno.HttpLimit;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.ClerkMainStoreRelatedDTO;
import com.gic.haoban.manage.api.dto.EnterpriseDetailDTO;
import com.gic.haoban.manage.api.dto.ExternalClerkRelatedDTO;
import com.gic.haoban.manage.api.dto.ExternalMemberLogDTO;
import com.gic.haoban.manage.api.dto.ExternalUserDTO;
import com.gic.haoban.manage.api.dto.MemberStoreDTO;
import com.gic.haoban.manage.api.dto.MemberUnionidRelatedDTO;
import com.gic.haoban.manage.api.dto.MiniprogramSettingDTO;
import com.gic.haoban.manage.api.dto.SecretSettingDTO;
import com.gic.haoban.manage.api.dto.StaffClerkInfoDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.StaffPrivacyUseLogDTO;
import com.gic.haoban.manage.api.dto.UserLoginLogDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseRelationDetailDTO;
import com.gic.haoban.manage.api.dto.YwWxEnterpriseDTO;
import com.gic.haoban.manage.api.enums.SecretTypeEnum;
import com.gic.haoban.manage.api.service.ClerkMainStoreRelatedApiService;
import com.gic.haoban.manage.api.service.ExternalClerkRelatedApiService;
import com.gic.haoban.manage.api.service.MemberUnionidRelatedApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.qo.GetUserByMemberCodeQo;
import com.gic.haoban.manage.web.qo.MemberLoginQo;
import com.gic.haoban.manage.web.qo.StaffLoginQO;
import com.gic.haoban.manage.web.utils.IPAddressUtil;
import com.gic.haoban.manage.web.vo.AppStaffVo;
import com.gic.haoban.manage.web.vo.MemberSendMessageVo;
import com.gic.haoban.manage.web.vo.StoreMemberVO;
import com.gic.haoban.manage.web.vo.WellDoneLoginInfoVO;
import com.gic.member.api.service.MemberOpenCardBusinessService;
import com.gic.membersource.api.dto.output.BusinessRefInfoDTO;
import com.gic.membersource.api.service.MemberOutsideApiService;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.dto.qywx.UserDTO;
import com.gic.wechat.api.service.qywx.QywxCorpApiService;
import com.gic.wechat.api.service.qywx.QywxUserApiService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;

/**
 * 企微配置
 */
@RestController
public class WxEnterpriseInfoController extends WebBaseController {

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

    @Autowired
    private QywxCorpApiService qywxCorpApiService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private com.gic.enterprise.api.service.StoreService storeService;
    @Autowired
    private MemberUnionidRelatedApiService memberUnionidRelatedApiService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private ManagerDictService managerDictService;
    @Autowired
    private StaffMemberRelationApiService staffMemberRelationApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private ExternalClerkRelatedApiService externalClerkRelatedApiService;
    @Autowired
    private MemberOpenCardBusinessService memberOpenCardBusinessService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private Config config;
    @Autowired
    private ClerkMainStoreRelatedApiService clerkMainStoreRelatedApiService;
    @Autowired
    private CustomerApiService customerApiService;
    @Autowired
    private AccountService accountService ;
    @Autowired
    MemberOutsideApiService memberOutsideApiService;


    /**
     * code授权
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "get-info-by-code", method = {RequestMethod.GET, RequestMethod.POST})
    @IgnoreLogin
    public HaobanResponse getInfoByCode(String code , String appid) {
        logger.info("code:{}", code);
        String userDTOJson = null ;
        String wxEnterpriseId = null ;
        if(StringUtils.isNotEmpty(appid)) {
            WxEnterpriseDTO wxEnterprise =  this.wxEnterpriseApiService.selectByWxaAppid(appid) ;
            if(null != wxEnterprise) {
                wxEnterpriseId = wxEnterprise.getWxEnterpriseId() ;
            }
        }
        if(null != wxEnterpriseId) {
            WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId) ;
            userDTOJson = qywxUserApiService.getUserByCode(qwDTO.getDkCorpid(), qwDTO.getSelfSecret(), code , qwDTO.getUrlHost());
        }else {
            userDTOJson = qywxCorpApiService.getCodeSession(config.getWxSuiteid(), code);
        }
        // {"errcode":0,"corpid":"wweac4ef962720aa12","session_key":"oNKOu4tDcnTWdj4wOg75YQ==","errmsg":"ok",
        //     "open_userid":"wo59NLDQAAxeJ-Nr7_vwkZVc7QOG73PQ","userid":"xugaohua","deviceid":"0BB1D1FA-C5A2-4BDD-80A2-33B6BB230F8A"}
        logger.info("好办登录={}", userDTOJson);
        UserDTO user = JSON.parseObject(userDTOJson, UserDTO.class);
        if (user == null) {
            return resultResponse(HaoBanErrCode.ERR_6);
        }
        String userId = user.getUserid();
        String corpId = user.getCorpid();
        WxEnterpriseDTO wxEnterprise = wxEnterpriseApiService.getEnterpriseBycorpId(corpId);
        boolean testFlag = false ;
        if(null == wxEnterprise) {
            logger.info("通过corpid查不到企业corpid={}",corpId);
            testFlag = true ;
        }
        if(!testFlag) {
            List<EnterpriseDetailDTO> relationList = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterprise.getWxEnterpriseId());
            if(CollectionUtils.isEmpty(relationList)) {
                logger.info("企业未关联gic商户,corpid={}",corpId);
                testFlag = true ;
            }
        }
        if(testFlag) {
            Object testAccount = RedisUtil.getCache("haoban-test-account") ;
            logger.info("testAccount={}",testAccount);
            if(null != testAccount) {
                return resultResponse(HaoBanErrCode.ERR_1, JSON.parseObject((String) testAccount));
            }
        }
        // 判断好办是否到期
        ServiceResponse<Boolean> resp = this.wxEnterpriseApiService.isStopHaoban(corpId);
        if (!resp.isSuccess()) {
            HaobanResponse response = new HaobanResponse();
            response.setErrorCode(-888);
            response.setMessage(resp.getMessage());
            return response;
        }

        // 特殊处理
        Object shachi = RedisUtil.getCache("haoban-test-account-shachi") ;
        if(null != shachi && shachi.toString().contains(corpId)) {
            HaobanResponse response = new HaobanResponse();
            response.setErrorCode(-888);
            response.setMessage("已无可用许可，联系商务购买后可继续使用");
            return response;
        }
        
        StaffDTO loginStaff = null;
        if (wxEnterprise != null) {
            loginStaff = staffApiService.getByUserIdAndReflushWhenNoPhone(userId, wxEnterprise.getWxEnterpriseId());
            if (loginStaff == null) {
                staffApiService.wxGetAdd(userId, wxEnterprise.getWxEnterpriseId());
                loginStaff = staffApiService.selectByUserIdAndEnterpriseId(userId, wxEnterprise.getWxEnterpriseId());
            }
        }
        
        
        
        if (loginStaff == null) {
            logger.info("游客用户");
            WellDoneLoginInfoVO wellDoneLoginInfoVo = new WellDoneLoginInfoVO();
            wellDoneLoginInfoVo.setWxOpenUseId(userId);
            StaffPrivacyUseLogDTO staffPrivacyUseLogDTO = staffApiService.getStaffPrivacyByUserId(userId);
            wellDoneLoginInfoVo.setPrivacyUseFlag(staffPrivacyUseLogDTO == null ? 0 : 1);
            wellDoneLoginInfoVo.setStaffId("-1");
            return resultResponse(HaoBanErrCode.ERR_1, wellDoneLoginInfoVo);
        }

        if (StringUtils.isNotBlank(loginStaff.getPhoneNumber()) || StringUtils.isNotBlank(loginStaff.getWxOpenUseId())) {
            DictDTO loginUserDict = managerDictService.getSMSDict("app_login_phone_num", loginStaff.getPhoneNumber());
            if (null == loginUserDict) {
                loginUserDict = managerDictService.getSMSDict("app_login_phone_num", loginStaff.getWxOpenUseId());
            }
            if(null == loginUserDict) {
                loginUserDict = managerDictService.getSMSDict("app_login_phone_num", loginStaff.getWxUserId());
            }
            logger.info("伪登录：{}userId:{},loginUser={}", loginStaff.getPhoneNumber(), loginStaff.getWxOpenUseId(), JSONObject.toJSONString(loginUserDict));
            if (null != loginUserDict && StringUtils.isNotEmpty(loginUserDict.getDictName()) && loginUserDict.getDictName().split(":").length == 2) {
                String dictValue = loginUserDict.getDictValue();
                List<StaffDTO> staffDTOS = new ArrayList<>();
                StaffDTO dto = staffApiService.selectByUserIdAndEnterpriseId(dictValue, loginUserDict.getDictName().split(":")[1]);
                List<StaffDTO> phoneDtos = staffApiService.listByPhoneNumber(dictValue);
                if (CollectionUtils.isNotEmpty(phoneDtos)) {
                    staffDTOS.addAll(phoneDtos);
                }
                if (null != dto) {
                    staffDTOS.add(dto);
                }
                if (CollectionUtils.isNotEmpty(staffDTOS)) {
                    if (staffDTOS.size() > 1) {
                        String dictName = loginUserDict.getDictName();
                        loginStaff = staffDTOS.stream().filter(staffDTO -> dictName.indexOf(staffDTO.getWxEnterpriseId()) > 0).findFirst().orElse(loginStaff);
                    } else {
                        loginStaff = staffDTOS.get(0);
                    }
                } else {
                    logger.info("伪登录关联用户查不到,user={}", dictValue);
                }
            }
        }
        String staffId = loginStaff.getStaffId();
        //激活状态
        if (loginStaff.getActiveFlag() == 0) {
            staffApiService.activeStaff(staffId);
        }

        wxEnterpriseId = loginStaff.getWxEnterpriseId();
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId);
        String accesstoken = null ;
        if(qwDTO.isSelf()) {
            accesstoken = qywxCorpApiService.getCorpAccessToken(qwDTO.getThirdCorpid(), config.getWxSuiteid());
        }else {
            accesstoken = qywxCorpApiService.getToken(qwDTO.getThirdCorpid(), qwDTO.getSelfSecret()) ;
        }
        WellDoneLoginInfoVO wellDoneLoginInfoVo = new WellDoneLoginInfoVO();
        wellDoneLoginInfoVo.setAccessToken(accesstoken);
        wellDoneLoginInfoVo.setStaffId(staffId);
        wellDoneLoginInfoVo.setWxEnterpriseId(wxEnterpriseId);
        wellDoneLoginInfoVo.setStaffName(loginStaff.getStaffName());
        wellDoneLoginInfoVo.setPhoneNumber(loginStaff.getPhoneNumber());
        wellDoneLoginInfoVo.setNationcode(loginStaff.getNationCode());
        wellDoneLoginInfoVo.setWxUserId(loginStaff.getWxUserId());
        StaffPrivacyUseLogDTO staffPrivacyUseLogDTO = staffApiService.getStaffPrivacyByStaffId(staffId);
        wellDoneLoginInfoVo.setPrivacyUseFlag(staffPrivacyUseLogDTO == null ? 0 : 1);
        List<StaffClerkRelationDTO> staffClerkRelationDTOS = staffClerkRelationApiService.listManageBindByStaffId(staffId);
        wellDoneLoginInfoVo.setManageFlag(CollectionUtils.isEmpty(staffClerkRelationDTOS) ? 0 : 1);
        return resultResponse(HaoBanErrCode.ERR_1, wellDoneLoginInfoVo);
    }


    /**
     * 好办小程序-登陆
     *
     * @param staffLoginQO 员工登录:
     * @return {@link HaobanResponse }
     * @author mozhu
     * @date 2021-12-14 20:18:12
     */
    @RequestMapping(value = "welldone-login", method = RequestMethod.POST)
    @IgnoreLogin
    public RestResponse<String> welldoneLogin(@RequestBody @Valid StaffLoginQO staffLoginQO, HttpServletRequest request) {
        String staffId = staffLoginQO.getStaffId();
        String wxOpenUseId = staffLoginQO.getWxOpenUseId();
        //-1 代表游客登录
        if (StringUtils.isBlank(staffId) || "-1".equals(staffId)) {
            return wellDoneTouristsLogin(staffLoginQO, request, staffId, wxOpenUseId);
        }
        //用户登录
        return wellDoneLogin(staffLoginQO, request, staffId);
    }

    /**
     * 游客登录
     *
     * @param staffLoginQO
     * @param request
     * @param staffId
     * @param wxOpenUseId
     * @return
     */
    private RestResponse<String> wellDoneTouristsLogin(StaffLoginQO staffLoginQO, HttpServletRequest request, String staffId, String wxOpenUseId) {
        logger.info("游客登录,wxOpenUseId:{}", wxOpenUseId);
        StaffPrivacyUseLogDTO privacyUseLogDTO = new StaffPrivacyUseLogDTO();
        BeanUtils.copyProperties(staffLoginQO, privacyUseLogDTO);
        privacyUseLogDTO.setStaffIp(IPAddressUtil.getIpAddress(request));
        wxEnterpriseApiService.wellDoneLoginAddPrivacy(privacyUseLogDTO);
        return RestResponse.successResult("token");
    }

    /**
     * 用户登录
     *
     * @param staffLoginQO
     * @param request
     * @param staffId
     * @return
     */
    private RestResponse<String> wellDoneLogin(StaffLoginQO staffLoginQO, HttpServletRequest request, String staffId) {
        // 正常登录
        String loginPhoneNumber = staffLoginQO.getPhoneNumber();
        logger.info("好办登录，staffId：{},loginPhoneNumber:{}", staffId, loginPhoneNumber);
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        if (staffDTO == null) {
            return RestResponse.failure(String.valueOf(HaoBanErrCode.ERR_6.getCode()), HaoBanErrCode.ERR_6.getMsg());
        }

        String phoneNumber = staffDTO.getPhoneNumber();

        StaffPrivacyUseLogDTO privacyUseLogDTO = new StaffPrivacyUseLogDTO();
        BeanUtils.copyProperties(staffLoginQO, privacyUseLogDTO);
        privacyUseLogDTO.setStaffIp(IPAddressUtil.getIpAddress(request));
        privacyUseLogDTO.setWxEnterpriseId(staffDTO.getWxEnterpriseId());
        privacyUseLogDTO.setPhoneNumber(phoneNumber);
        privacyUseLogDTO.setWxUserId(staffDTO.getWxUserId());
        privacyUseLogDTO.setWxOpenUseId(staffDTO.getWxOpenUseId());
        wxEnterpriseApiService.wellDoneLoginAddPrivacy(privacyUseLogDTO);
        return RestResponse.successResult("token");
    }

    /**
     * 令牌token刷新
     *
     * @return {@link HaobanResponse }
     * @author mozhu
     * @date 2021-12-10 18:34:12
     */
    @RequestMapping(value = "welldone-token-refresh", method = RequestMethod.GET)
    public HaobanResponse welldoneTokenRefresh() {
        return resultResponse(HaoBanErrCode.ERR_1, null);
    }

    /**
     * 会员小程序-获取登录用户信息
     *
     * @param qo
     * @return
     */
    @IgnoreLogin
    @RequestMapping("get-user-by-member-code")
    public HaobanResponse getInfoByMemberCode(GetUserByMemberCodeQo qo) {
        logger.info("会员小程序={}", JSON.toJSONString(qo));
        String gicEnterpriseId = qo.getGicEnterpriseId();
        if (StringUtils.isNotEmpty(gicEnterpriseId)) {
            if (this.wxEnterpriseApiService.haobanIsStop(gicEnterpriseId)) {
                HaobanResponse response = new HaobanResponse();
                response.setErrorCode(-888);
                String msg = this.wxEnterpriseApiService.getEndDate(gicEnterpriseId);
                response.setMessage(msg);
                response.setDetailError(msg);
                return response;
            }
        }
        WxEnterpriseDTO enterpriseDTO = null;
        if (StringUtils.isNotBlank(qo.getCorpId())) {
            enterpriseDTO = wxEnterpriseApiService.getEnterpriseBycorpId(qo.getCorpId());

        } else {
            List<WxEnterpriseDTO> wxEnterpriseDTOS = wxEnterpriseRelatedApiService.listWxEnterpriseByEid(gicEnterpriseId);
            if (CollectionUtils.isNotEmpty(wxEnterpriseDTOS)) {
                enterpriseDTO = wxEnterpriseDTOS.get(0);
            }
        }
        if (null == enterpriseDTO) {
            logger.info("企微查不到");
            return resultResponse(HaoBanErrCode.ERR_500001);
        }
        String wxEnterpriseId = enterpriseDTO.getWxEnterpriseId();
        logger.info("查询到的企微ID={}-{}", wxEnterpriseId, enterpriseDTO.getCorpName());
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId);
        MemberLoginQo user = new MemberLoginQo();
        if (StringUtils.isBlank(qo.getUserId())) {
            user = getUserByCode(wxEnterpriseId, qwDTO.getMemberCorpid(), qo.getCode(), qo.getGicEnterpriseId(),qwDTO);
            if (user == null) {
                logger.info("登录失败,从微信获取用户信息失败");
                return resultResponse(HaoBanErrCode.ERR_6);
            }
            if (null == qo.getCorpId() && !user.getCorpId().equals(enterpriseDTO.getWxCorpid()) && !user.getCorpId().equals(enterpriseDTO.getOpenCorpid())) {
                logger.info("corpid不一致,{},{},{}", user.getCorpId(), enterpriseDTO.getWxCorpid(), enterpriseDTO.getOpenCorpid());
                return resultResponse(HaoBanErrCode.ERR_500003, user.getCorpId());
            }
            enterpriseDTO = wxEnterpriseApiService.getEnterpriseBycorpId(user.getCorpId());
            if (enterpriseDTO == null) {
                logger.info("该企业不存在corpid={}", user.getCorpId());
                return resultResponse(HaoBanErrCode.ERR_400002);
            }
        } else {
            user.setUserId(qo.getUserId());
        }

        StaffDTO staffDTO = staffApiService.selectByUserIdAndEnterpriseId(user.getUserId(), enterpriseDTO.getWxEnterpriseId());
        if (staffDTO == null) {
            logger.info("成员不存在,userId={}", user.getUserId());
            return resultResponse(HaoBanErrCode.ERR_6);
        }
        //保存关联关系
        StaffOpenRelatedDTO relatedDTO = new StaffOpenRelatedDTO();
        relatedDTO.setMemberId(qo.getMemberId());
        relatedDTO.setOpenId(qo.getOpenid());
        relatedDTO.setStaffId(staffDTO.getStaffId());
        relatedDTO.setWxEnterpriseId(enterpriseDTO.getWxEnterpriseId());
        relatedDTO.setGicEnterpriseId(qo.getGicEnterpriseId());
        staffMemberRelationApiService.bindMemberAndStaff(relatedDTO);

        //补充字段赋值
        user.setStaffId(staffDTO.getStaffId());
        user.setWxEnterpriseId(staffDTO.getWxEnterpriseId());
        user.setStaffName(staffDTO.getStaffName());
        user.setPhoneNumber(staffDTO.getPhoneNumber());
        user.setNationCode(staffDTO.getNationCode());
        user.setWxUserId(staffDTO.getWxUserId());

        List<StaffClerkInfoDTO> result = staffClerkRelationApiService.listBindDetailByStaffId(staffDTO.getStaffId());

        List<StoreMemberVO> retList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(result)) {
            result.stream().filter(staffClerkInfoDTO -> staffClerkInfoDTO.getEnterpriseId().equals(qo.getGicEnterpriseId())).forEach(dto -> {
                StoreMemberVO storeMemberVO = new StoreMemberVO();
                StoreDTO store = storeService.getStore(dto.getStoreId());
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(dto.getClerkId());
                if (null != store && clerkDTO != null) {
                    storeMemberVO.setUserId(staffDTO.getWxUserId());
                    storeMemberVO.setStoreId(dto.getStoreId());//为空，则无该值
                    storeMemberVO.setStoreName(dto.getStoreName());
                    storeMemberVO.setWxEnterpriseId(dto.getWxEnterpriseId());
                    storeMemberVO.setEnterpriseId(store.getEnterpriseId());
                    storeMemberVO.setStoreImg(store.getImageUrl());//先置空
                    storeMemberVO.setBindFlag(1);
                    storeMemberVO.setClerkCode(clerkDTO.getClerkCode());
                    storeMemberVO.setClerkType(clerkDTO.getClerkType());
                    storeMemberVO.setStaffId(staffDTO.getStaffId());
                    storeMemberVO.setClerkId(clerkDTO.getClerkId());
                    storeMemberVO.setClerkName(clerkDTO.getClerkName());
                    storeMemberVO.setClerkHead(clerkDTO.getHeadImgUrl());
                    retList.add(storeMemberVO);
                }

            });
            user.setStoreList(retList);
        }
        return resultResponse(HaoBanErrCode.ERR_1, user);
    }

    private MemberLoginQo getUserByCode(String wxEnterpriseId, String corpid, String code, String enterpriseId,WxEnterpriseQwDTO qwDTO) {
        SecretSettingDTO secretSetting = wxEnterpriseApiService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.MEMBER_WAPP.getVal(), enterpriseId);
        if (null == secretSetting || StringUtils.isBlank(secretSetting.getSecretVal())) {
            logger.info("MEMBER_WAPPsecret没有配置{},{}", wxEnterpriseId, enterpriseId);
            return null;
        }
        String userDTOJson = qywxUserApiService.getUserByCode(corpid, secretSetting.getSecretVal(), code ,qwDTO.getUrlHost());
        logger.info("会员微信登录信息=============>{}", userDTOJson);
        return JSON.parseObject(userDTOJson, MemberLoginQo.class);
    }

    /**
     * 好办点击进来日志表
     *
     * @param userLoginLogDTO
     * @return
     */
    @RequestMapping("save-user-login-log")
    public HaobanResponse saveUserLoginLog(UserLoginLogDTO userLoginLogDTO) {
        staffApiService.insertUserLoginLog(userLoginLogDTO);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    @RequestMapping("get-member-store")
    public HaobanResponse getMemberStore(String externalUserid, String staffId, String storeId) {
        if (StringUtils.isAnyBlank(externalUserid, staffId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<MemberStoreDTO> result = memberUnionidRelatedApiService.listByExTernalUseridAndWxUserId(externalUserid, staffId, storeId);
        return resultResponse(HaoBanErrCode.ERR_1, result);
    }
    
    @RequestMapping("get-externaluser-memberid")
    public RestResponse<Object> getMemberDetail(String externalUserid, String staffId, String enterpriseId) {
        logger.info("获取外部联系人memberid={},{}",externalUserid,staffId);
        if (StringUtils.isAnyBlank(externalUserid, staffId,enterpriseId)) {
            return RestResponse.failure("9999",HaoBanErrCode.ERR_2.getMsg());
        }
        ServiceResponse<MemberStoreDTO> resp = memberUnionidRelatedApiService.getMemberIdForDetail(externalUserid, staffId, enterpriseId);
        if(resp.isSuccess()) {
            return RestResponse.successResult(resp.getResult());
        }
        return RestResponse.failure("9999",resp.getMessage());
    }

    /**
     * 是否能打开客户详情权限
     *
     * @param clerkId
     * @param memberId
     * @param storeId
     * @param enterpriseId
     * @return
     */
    @RequestMapping("get-member-clerk-flag")
    public RestResponse getMemberFlag(String clerkId, String memberId, String storeId, String enterpriseId) {
        if (StringUtils.isAnyBlank(clerkId, memberId, storeId)) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()), HaoBanErrCode.ERR_2.getMsg());
        }
        CustomerDTO params = new CustomerDTO();
        params.setClerkType("0");
        params.setStoreId(storeId);
        params.setClerkId(clerkId);
        params.setEnterpriseId(enterpriseId);
        params.setStoreManagerFlag(isManager(clerkId));
        MemberInfoListParamsDTO memberInfoListParamsDTO = new MemberInfoListParamsDTO();
        memberInfoListParamsDTO.setMemberId(memberId);

        FilterListDTO filterListDTO = new FilterListDTO();
        filterListDTO.setFilterType("4");
        ChildDTO childDTO = new ChildDTO();
        childDTO.setId("");
        filterListDTO.setChild(childDTO);
        List<FilterListDTO> filterList = new ArrayList<>();
        filterList.add(filterListDTO);
        memberInfoListParamsDTO.setFilterList(filterList);

        boolean flag = customerApiService.checkMemberRangeByMemberId(params, memberInfoListParamsDTO);
        if (flag) {
            return RestResponse.successResult(true);
        } else {
            return RestResponse.successResult(false);
        }

    }

    /**
     * 是否店长
     *
     * @param clerkId
     * @return
     */
    private boolean isManager(String clerkId) {
        ClerkDTO clerkDTO = clerkService.getclerkById(clerkId);
        if (clerkDTO != null) {
            Integer isManager = clerkDTO.getClerkType();
            return isManager != null && isManager == 1 && clerkDTO.getStatus() == 1;
        }
        return false;
    }

    @RequestMapping("get-staff-info")
    @IgnoreLogin
    public HaobanResponse getStaffInfo(String phoneNumber) {
        if (StringUtils.isBlank(phoneNumber)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<StaffDTO> list = staffApiService.listByPhoneNumber(phoneNumber);
        if (CollectionUtil.isNotEmpty(list)) {
            List<AppStaffVo> staffs = EntityUtil.changeEntityListByJSON(AppStaffVo.class, list);
            Set<String> wxEnterpriseIds = list.stream().map(s -> s.getWxEnterpriseId()).collect(Collectors.toSet());
            List<YwWxEnterpriseDTO> enterprises = wxEnterpriseApiService.listByIds(wxEnterpriseIds);
            Map<String, YwWxEnterpriseDTO> map = com.gic.commons.util.CollectionUtil.toMap(enterprises, "wxEnterpriseId");
            for (AppStaffVo vo : staffs) {
                String wxEnterpriseId = vo.getWxEnterpriseId();
                String corpName = map.get(wxEnterpriseId) == null ? "" : map.get(wxEnterpriseId).getCorpName();
                vo.setWxEnterpriseName(corpName);
            }
            return resultResponse(HaoBanErrCode.ERR_1, staffs);
        }
        return resultResponse(HaoBanErrCode.ERR_1, new ArrayList<>());
    }


    @RequestMapping(value = "get-staff-by-id", method = RequestMethod.GET)
    public RestResponse<AppStaffVo> getStaffInfoById(String staffId) {
        if (StringUtils.isBlank(staffId)) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()), HaoBanErrCode.ERR_2.getMsg());
        }
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        AppStaffVo appStaffVo = EntityUtil.changeEntityByOrika(AppStaffVo.class, staffDTO);
        if (staffDTO != null) {
            WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(staffDTO.getWxEnterpriseId());
            if (wxEnterpriseDTO != null) {
                appStaffVo.setWxEnterpriseName(wxEnterpriseDTO.getCorpName());
            }
        }
        return RestResponse.successResult(appStaffVo);
    }

    /**
     * 会员小程序-获取绑定信息(会员工具)
     *
     * @param externalUserid
     * @param wxEnterpriseId
     * @return
     */
    @IgnoreLogin
    @HttpLimit
    @RequestMapping("get-send-message-info")
    public HaobanResponse getMessageMember(String externalUserid, String staffId, String wxEnterpriseId, String gicEnterpriseId) {
        logger.info("会员工具传入参数：externalUserid:{},wxUserId:{},wxEnterpriseId:{},gicEnterpriseId:{}", externalUserid, staffId, wxEnterpriseId, gicEnterpriseId);
        if (StringUtils.isAnyBlank(externalUserid, staffId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WxEnterpriseRelationDetailDTO enterpriseBindInfo = wxEnterpriseRelatedApiService.getEnterpriseBindInfo(wxEnterpriseId, gicEnterpriseId);
        if (null == enterpriseBindInfo) {
            logger.info("企业不存在没有绑定,wxEnterpriseId:{}", wxEnterpriseId);
            return resultResponse(HaoBanErrCode.ERR_400002);
        }
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        if (staffDTO == null) {
            logger.info("查询到该员工,wxUserId:{}", staffId);
            return resultResponse(HaoBanErrCode.ERR_400017);
        }
        if (!staffDTO.getWxEnterpriseId().equals(wxEnterpriseId)) {
            logger.info("查询到该员工,异常");
            return resultResponse(HaoBanErrCode.ERR_400017);
        }
        ClerkMainStoreRelatedDTO clerkMainStoreRelatedDTO = clerkMainStoreRelatedApiService.getWxEnterpriseIdAndStaffId(wxEnterpriseId, staffId);
        if (clerkMainStoreRelatedDTO == null) {
            logger.info("未设置主门店,wxUserId:{}", staffId);
            return resultResponse(HaoBanErrCode.ERR_400021);
        }
        //获取自建客户详情
        WxEnterpriseQwDTO qwInfo = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId);
        String wxUserId = staffDTO.getWxUserId();
        if (qwInfo.needOpenUserIdDk()) {
            wxUserId = staffDTO.getWxOpenUseId();
        }
        ExternalUserDTO externalUserDTO = memberUnionidRelatedApiService.getCorpSelfExternalUseridInfoForMember(wxEnterpriseId, wxUserId, externalUserid, gicEnterpriseId);
        if (externalUserDTO == null) {
            logger.info("请先添加好友，企业微信未查询到该好友,externalUserid:{}", externalUserid);
            return resultResponse(HaoBanErrCode.ERR_11126);
        } 
        /*if(!qwInfo.isSelf()) {
            MemberUnionidRelatedDTO memberUnionidRelatedDTO = memberUnionidRelatedApiService.getBySelfExternalUserId(wxEnterpriseId, externalUserid);
            if (null == memberUnionidRelatedDTO) {
                logger.info("请刷新好友，wxEnterpriseId:{},传入的externalUserid：{},wxUserId:{}", wxEnterpriseId, externalUserid, wxUserId);
                return resultResponse(HaoBanErrCode.ERR_11123);
            }
            externalUserid = memberUnionidRelatedDTO.getExternalUserid() ;
            logger.info("会员数据：{}", JSON.toJSONString(memberUnionidRelatedDTO));
        }*/
        ExternalClerkRelatedDTO clerkRelatedDTO = externalClerkRelatedApiService.getExternalClerkByWxUserIdAncExternalUserId(wxEnterpriseId, staffId, gicEnterpriseId, externalUserid);
        if (clerkRelatedDTO == null) {
            logger.info("该企业没有对应需要发送好友关系的信息，wxEnterpriseId:{},externalUserid：{},wxUserId:{}", wxEnterpriseId, externalUserid, wxUserId);
            return resultResponse(HaoBanErrCode.ERR_11123);
        }
        MiniprogramSettingDTO settingDTO = wxEnterpriseApiService.getMiniprogramSettingByEid(wxEnterpriseId, gicEnterpriseId);
        if (null == settingDTO) {
            logger.info("该企业没有对应需要发送的小程序信息，wxEnterpriseId:{}", wxEnterpriseId);
            return resultResponse(HaoBanErrCode.ERR_11124);
        }
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(gicEnterpriseId);
        MemberSendMessageVo memberSendMessageVo = new MemberSendMessageVo();
        String relationKey = clerkRelatedDTO.getRelationKey();
        memberSendMessageVo.setRelationKey(StringUtils.isNotBlank(relationKey) ? relationKey : "-1");
        memberSendMessageVo.setImageUrl(settingDTO.getImageUrl());
        memberSendMessageVo.setMediaId(settingDTO.getMediaId());
        memberSendMessageVo.setSelfExteralUserId(externalUserid);
        memberSendMessageVo.setTitle(settingDTO.getTitle());
        memberSendMessageVo.setWxaHandUrl(enterpriseDTO.getMallMiniprogramLogoUrl());
        int bindFlag = 0 ;
        if(clerkRelatedDTO.getStatusFlag()==1 && StringUtils.isNotBlank(clerkRelatedDTO.getMemberId())) {
            bindFlag = 1 ;
        }
        memberSendMessageVo.setBindFlag(bindFlag);
        memberSendMessageVo.setWxaName(settingDTO.getMiniprogramName());
        return resultResponse(HaoBanErrCode.ERR_1, memberSendMessageVo);
    }

    /**
     * 会员小程序-绑定好友
     *
     * @param memberId
     * @param enterpriseId
     * @param unionid
     * @param relationKey
     * @return
     */
    @IgnoreLogin
    @RequestMapping("member-bind-friend")
    public HaobanResponse memberBindFriend(String memberId, String enterpriseId, String unionid, String relationKey) {
        if (StringUtils.isAnyBlank(enterpriseId, relationKey , unionid)) {
            logger.info("参数错误");
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        ExternalMemberLogDTO memberLog = new ExternalMemberLogDTO() ;
        memberLog.setEnterpriseId(enterpriseId);
        memberLog.setUnionid(unionid);
        memberLog.setRelationKey(relationKey);
        memberLog.setMemberId(memberId);
        if(StringUtils.isEmpty(memberId)) {
            this.memberUnionidRelatedApiService.saveExternalMemberLog(memberLog) ;
            this.save(enterpriseId, unionid, relationKey);
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        ExternalClerkRelatedDTO externalClerkRelatedDTO = externalClerkRelatedApiService.getExternalClerkByRelationKeyAndPre(relationKey);
        if (externalClerkRelatedDTO == null) {
            this.memberUnionidRelatedApiService.saveExternalMemberLog(memberLog) ;
            logger.info("好友表不存在记录,memberId:{},enterpriseId:{},unionid:{},relationKey:{}", memberId, enterpriseId, unionid, relationKey);
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        logger.info("会员绑定好友，memberId:{},enterpriseId:{},unionid:{},relationKey:{}", memberId, enterpriseId, unionid, relationKey);
        memberOpenCardBusinessService.memberClerkProcessByQywxFriend(enterpriseId, memberId, unionid, relationKey);
        return resultResponse(HaoBanErrCode.ERR_1);
    }
    
    
    private void save(String enterpriseId , String unionid , String relationKey) {
        BusinessRefInfoDTO businessRefInfoDTO=new BusinessRefInfoDTO();
        businessRefInfoDTO.setKeyType(1);
        businessRefInfoDTO.setEnterpriseId(enterpriseId);
        businessRefInfoDTO.setKey(unionid);
        businessRefInfoDTO.setType(4);
        businessRefInfoDTO.setValue(relationKey);
        memberOutsideApiService.addBusinessRefInfo(businessRefInfoDTO);
    }
    
    @RequestMapping("check-storage-fee")
    @ResponseBody
    public RestResponse<Object> checkStorageFee(String enterpriseId , String url) {
        String gicUrl = "1251519181.cos.ap-shanghai.myqcloud.com" ;
        if(StringUtils.isNotBlank(url) && !url.contains(gicUrl)) {
            return RestResponse.successResult(true) ;
        }
        boolean check = this.accountService.storageFeeCheck(enterpriseId) ;
        return RestResponse.successResult(check) ;
    }

    /**
     * 查询企业配置
     * @param enterpriseId
     * @return
     */
    @RequestMapping(path = "/enterprise/config")
    public RestResponse<EnterpriseConfigVO> queryEnterpriseConfig(String enterpriseId) {

        if (StringUtils.isBlank(enterpriseId)) {
            return RestResponse.failure("-701", "参数缺失");
        }
        EnterpriseDTO enterpriseInfo = enterpriseService.getEnterpriseById(enterpriseId);
        if (enterpriseInfo == null) {
            return RestResponse.failure("-2", "企业信息不存在");
        }

        EnterpriseConfigVO configVO = EnterpriseConfigVO
                .builder()
                .miniAppId(enterpriseInfo.getMallMiniprogramAppid())
                .mallMiniProgramLogoUrl(enterpriseInfo.getMallMiniprogramLogoUrl())
                .mallMiniProgramLogoName(enterpriseInfo.getBrandName())
                .build();
        return RestResponse.successResult(configVO);
    }
}
