//package com.gree.mall.manager.logic.admin.ew;
//
//import org.apache.commons.lang3.StringUtils;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.gree.mall.manager.bean.ExcelData;
//import com.gree.mall.manager.bean.admin.AdminUserCom;
//import com.gree.mall.manager.bean.admin.EnterpriseWechatWorkerImportList;
//import com.gree.mall.manager.commonmapper.EnterpriseWechatWorkerLogicMapper;
//import com.gree.mall.manager.constant.Constant;
//import com.gree.mall.manager.exception.RemoteServiceException;
//import com.gree.mall.manager.logic.admin.AdminWebsitLogic;
//import com.gree.mall.manager.logic.common.CommonLogic;
//import com.gree.mall.manager.logic.common.WorkWechatLogic;
//import com.gree.mall.manager.logic.user.UserLogic;
//import com.gree.mall.manager.plus.entity.AdminCompanyWechat;
//import com.gree.mall.manager.plus.entity.AdminWebsit;
//import com.gree.mall.manager.plus.entity.EnterpriseWechatWorker;
//import com.gree.mall.manager.plus.service.AdminWebsitService;
//import com.gree.mall.manager.plus.service.EnterpriseWechatWorkerService;
//import com.gree.mall.manager.utils.CommonUtils;
//import com.gree.mall.manager.utils.DateUtils;
//import com.gree.mall.manager.utils.excel.ExcelUtils;
//import me.chanjar.weixin.common.error.WxErrorException;
//import me.chanjar.weixin.cp.api.WxCpService;
//import me.chanjar.weixin.cp.api.WxCpUserService;
//import me.chanjar.weixin.cp.bean.WxCpUser;
//import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
//import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
//import org.apache.commons.collections4.CollectionUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.IOException;
//import java.util.*;
//import java.util.stream.Collectors;
//
//@Service
//public class EnterpriseWechatWorkerLogic {
//
//    @Autowired
//    EnterpriseWechatWorkerService enterpriseWechatWorkerService;
//    @Autowired
//    AdminWebsitLogic adminWebsitLogic;
//    @Autowired
//    WorkWechatLogic workWechatLogic;
//    @Autowired
//    UserLogic userLogic;
//    @Autowired
//    CommonLogic commonLogic;
//    @Autowired
//    EnterpriseWechatWorkerLogicMapper enterpriseWechatWorkerLogicMapper;
//    @Autowired
//    AdminWebsitService adminWebsitService;
//
//    /**
//     * 企业成员列表
//     */
//    public IPage<EnterpriseWechatWorker> list(String keyword, String adminWebsitId, Long websitId, Integer pageNo, Integer pageSize, HttpServletRequest request) {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        List<Long> ids = new ArrayList<>();
//        List<AdminWebsit> list = new ArrayList<>();
//
//        String corpId = null;
//        if (StringUtils.isNotBlank(adminWebsitId) && websitId != null) {
//            list.addAll(adminWebsitLogic.queryAllChild(list, websitId));
//            ids.add(websitId);
//
//            corpId = adminWebsitLogic.detail(adminWebsitId).getCorpId();
//        }
//        ids.addAll(list.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList()));
//
//        IPage<EnterpriseWechatWorker> page = enterpriseWechatWorkerService.lambdaQuery()
//                .in(ids.size() > 0, EnterpriseWechatWorker::getMainDepartment, ids)
//                .and(StringUtils.isNotBlank(keyword), v -> v.like(EnterpriseWechatWorker::getName, keyword)
//                        .or().like(EnterpriseWechatWorker::getWechatUserId, keyword)
//                        .or().like(EnterpriseWechatWorker::getMobile, keyword))
//                .in(CollectionUtils.isNotEmpty(adminUser.getCorpIds()), EnterpriseWechatWorker::getCorpId, adminUser.getCorpIds())
//                .eq(corpId != null, EnterpriseWechatWorker::getCorpId, corpId)
//                .orderByDesc(EnterpriseWechatWorker::getCreateTime, EnterpriseWechatWorker::getId)
//                .page(new Page<>(pageNo, pageSize));
//        return page;
//    }
//
//    /**
//     * 获取成员列表
//     */
//    public List<EnterpriseWechatWorker> list(String corpId) {
//        List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(StringUtils.isNotBlank(corpId), EnterpriseWechatWorker::getCorpId, corpId).list();
//        return list;
//    }
//
//    /**
//     * 根据手机号获取成员
//     */
//    public EnterpriseWechatWorker getByMobile(String mobile, String corpId) throws WxErrorException {
//        EnterpriseWechatWorker one = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(EnterpriseWechatWorker::getMobile, mobile)
//                .eq(EnterpriseWechatWorker::getCorpId, corpId)
//                .one();
//        if(one != null) {
//            AdminCompanyWechat adminCompanyWechat = commonLogic.getAdminCompanyWechat(Constant.GD_COMPANY_WECHAT_ID);
//            WxCpUserService userService = workWechatLogic.miniApp(adminCompanyWechat).getUserService();
//
//            WxCpUser wxCpUser = userService.getById(one.getWechatUserId());
//            one.setQrCode(wxCpUser.getQrCode());
//
//            WxCpContactWayResult customerQrCode = this.getCustomerQrCode(one.getWechatUserId(), one.getConfigId(), adminCompanyWechat);
//            one.setQrCode2(customerQrCode.getQrCode());
//            one.setConfigId(customerQrCode.getConfigId());
//            one.updateById();
//        }
//        return one;
//    }
//
//
//    /**
//     * 添加成员
//     *
//     * @param name
//     * @param wechatUserId
//     * @param position
//     * @param mobile
//     * @param gender
//     * @param mainDepartmentId adminWebsit的id
//     * @param email
//     * @throws RemoteServiceException
//     */
//    @Transactional
//    public void add(String name, String wechatUserId, String position, String mobile, Integer gender, Long mainDepartmentId, String email, AdminCompanyWechat adminCompanyWechat) throws RemoteServiceException, WxErrorException {
//        Integer count = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(EnterpriseWechatWorker::getCorpId, adminCompanyWechat.getCorpId())
//                .eq(EnterpriseWechatWorker::getWechatUserId, wechatUserId)
//                .count();
//        if (count > 0) {
//            throw new RemoteServiceException("操作失败,帐号已存在");
//        }
//        Integer count2 = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(EnterpriseWechatWorker::getCorpId, adminCompanyWechat.getCorpId())
//                .eq(EnterpriseWechatWorker::getMobile, mobile).count();
//        if (count2 > 0) {
//            throw new RemoteServiceException("操作失败,手机号已存在");
//        }
//        //同步到企业微信
//        workWechatLogic.addWorkUser(wechatUserId, name, mobile, gender, email, mainDepartmentId, position, adminCompanyWechat);
//        WxCpUser wxCpUser = workWechatLogic.getUser(wechatUserId, adminCompanyWechat);
//        AdminWebsit adminWebsit = adminWebsitLogic.detail(mainDepartmentId, adminCompanyWechat.getCorpId());
//
//        EnterpriseWechatWorker enterpriseWechatWorker = new EnterpriseWechatWorker();
//        enterpriseWechatWorker.setName(name);
//        enterpriseWechatWorker.setWechatUserId(wechatUserId);
//        enterpriseWechatWorker.setPosition(position);
//        enterpriseWechatWorker.setMobile(mobile);
//        enterpriseWechatWorker.setGender(gender);
//        enterpriseWechatWorker.setMainDepartment(mainDepartmentId.toString());
//        enterpriseWechatWorker.setDepartmentName(adminWebsit.getName());
//        if (StringUtils.isNotBlank(email)) {
//            enterpriseWechatWorker.setEmail(email);
//        }
//        if(wxCpUser != null){
//            enterpriseWechatWorker.setQrCode(wxCpUser.getQrCode());
//        }
//        enterpriseWechatWorker.setCorpId(adminWebsit.getCorpId());
//        enterpriseWechatWorker.setCreateTime(new Date());
//        enterpriseWechatWorker.insert();
//
//        //用户升级
//        userLogic.userLevelUp(Arrays.asList(wechatUserId));
//    }
//
//    /**
//     * 修改成员
//     *
//     * @param name
//     * @param wechatUserId
//     * @param position
//     * @param mobile
//     * @param gender
//     * @param mainDepartmentId adminWebsit的id
//     * @param email
//     * @throws RemoteServiceException
//     */
//    @Transactional
//    public void update(Integer id, String name, String wechatUserId,
//                       String position, String mobile, Integer gender, Long mainDepartmentId,
//                       String email, HttpServletRequest request) throws RemoteServiceException, WxErrorException {
//
//        EnterpriseWechatWorker enterpriseWechatWorker = enterpriseWechatWorkerService.getById(id);
//
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        Integer count = enterpriseWechatWorkerService.lambdaQuery()
//                .ne(EnterpriseWechatWorker::getId, id)
//                .eq(EnterpriseWechatWorker::getWechatUserId, wechatUserId)
//                .eq(EnterpriseWechatWorker::getCorpId, enterpriseWechatWorker.getCorpId())
//                .count();
//        if (count > 0) {
//            throw new RemoteServiceException("操作失败,帐号已存在");
//        }
//        Integer count2 = enterpriseWechatWorkerService.lambdaQuery()
//                .ne(EnterpriseWechatWorker::getId, id)
//                .eq(EnterpriseWechatWorker::getMobile, mobile)
//                .eq(EnterpriseWechatWorker::getCorpId, enterpriseWechatWorker.getCorpId())
//                .count();
//        if (count2 > 0) {
//            throw new RemoteServiceException("操作失败,手机号已存在");
//        }
//        AdminWebsit adminWebsit = adminWebsitLogic.detail(mainDepartmentId, adminUser.getAdminCompanyWechat().getCorpId());
//
//        //同步到企业微信
//        workWechatLogic.updateWorkUser(wechatUserId, name, mobile, gender, email, adminWebsit.getWebsitId(), position, adminUser.getAdminCompanyWechat());
//
//
//        enterpriseWechatWorker.setId(id);
//        enterpriseWechatWorker.setName(name);
//        enterpriseWechatWorker.setWechatUserId(wechatUserId);
//        enterpriseWechatWorker.setPosition(position);
//        enterpriseWechatWorker.setMobile(mobile);
//        enterpriseWechatWorker.setGender(gender);
//        enterpriseWechatWorker.setMainDepartment(mainDepartmentId.toString());
//        enterpriseWechatWorker.setDepartmentName(adminWebsit.getName());
//        if (StringUtils.isNotBlank(email)) {
//            enterpriseWechatWorker.setEmail(email);
//        }
//        enterpriseWechatWorker.setCreateTime(new Date());
//        enterpriseWechatWorker.updateById();
//
//    }
//
//
//    /**
//     * 成员详情
//     */
//    public EnterpriseWechatWorker detail(Integer id) {
//        return enterpriseWechatWorkerService.getById(id);
//    }
//
//    /**
//     * 删除成员
//     */
//    @Transactional
//    public void delete(List<Integer> ids, HttpServletRequest request) throws WxErrorException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//
//        List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery().in(EnterpriseWechatWorker::getId, ids).list();
//        for (EnterpriseWechatWorker bean : list) {
//            //同步到企业微信
//            workWechatLogic.deleteWorkUser(bean.getWechatUserId(), adminUser.getAdminCompanyWechat());
//        }
//        enterpriseWechatWorkerService.lambdaUpdate().in(EnterpriseWechatWorker::getId, ids).remove();
//
//        //将这些成员对应的业务员用户设为普通用户
//        List<String> workUserIds = list.stream().map(EnterpriseWechatWorker::getWechatUserId).collect(Collectors.toList());
//        if (workUserIds.size() > 0) {
//            //用户降级
//            userLogic.demotion(workUserIds);
//        }
//    }
//
//    @Transactional
//    public void loadDelete(MultipartFile multipartFile, HttpServletRequest request) throws WxErrorException, IOException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//
//        List<Object> objects = ExcelUtils.importExcel(multipartFile);
//        List<String> phoneList = new ArrayList<>();
//        for (int i = 0; i < objects.size(); i++) {
//            phoneList.add(((List<String>) objects.get(i)).get(0));
//        }
//        //----------
//        List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery()
//                .in(EnterpriseWechatWorker::getMobile, phoneList)
//                .eq(EnterpriseWechatWorker::getCorpId, adminUser.getCorpIds().get(0))
//                .list();
//        if (list.size() == 0) {
//            throw new RemoteServiceException("无符合删除条件的数据");
//        }
//        List<Integer> ids = list.stream().map(EnterpriseWechatWorker::getId).collect(Collectors.toList());
//        for (EnterpriseWechatWorker bean : list) {
//            //同步到企业微信
//            workWechatLogic.deleteWorkUser(bean.getWechatUserId(), adminUser.getAdminCompanyWechat());
//        }
//        enterpriseWechatWorkerService.removeByIds(ids);
//
//        //将这些成员对应的业务员用户设为普通用户
//        List<String> workUserIds = list.stream().map(EnterpriseWechatWorker::getWechatUserId).collect(Collectors.toList());
//        if (workUserIds.size() > 0) {
//            //用户降级
//            userLogic.demotion(workUserIds);
//        }
//    }
//
//
//    /**
//     * 刷新成员部门名称
//     */
//    public void reloadEnterpriseWechatName(AdminWebsit adminWebsit,HttpServletRequest request){
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//
//        enterpriseWechatWorkerService.lambdaUpdate()
//                .set(EnterpriseWechatWorker::getDepartmentName,adminWebsit.getName())
//                .eq(EnterpriseWechatWorker::getCorpId,adminUser.getCorpId())
//                .eq(EnterpriseWechatWorker::getMainDepartment,adminWebsit.getWebsitId())
//                .update();
//    }
//
//
//    /**
//     * 导入成员
//     */
//    @Transactional
//    public String importData(List<Object> datas, Long mainDepartmentId, HttpServletRequest request) throws WxErrorException {
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        List<EnterpriseWechatWorker> enterpriseWechatWorkers = new ArrayList<>();
//
//        List<EnterpriseWechatWorker> syncWechat = new ArrayList<>();
//
//        //所有成员
//        List<EnterpriseWechatWorker> enterpriseWechatWorkerList = enterpriseWechatWorkerService.lambdaQuery()
//                .eq(EnterpriseWechatWorker::getCorpId, adminUser.getCorpId()).list();
//        Map<String,EnterpriseWechatWorker> workers = enterpriseWechatWorkerList.stream().collect(Collectors.toMap(EnterpriseWechatWorker::getMobile, v -> v));
//        //所有部门
////        List<AdminWebsit> adminWebsits = adminWebsitService.lambdaQuery().eq(AdminWebsit::getCorpId, adminUser.getCorpId()).list();
////        Map<String, AdminWebsit> adminWebsitMap = adminWebsits.stream().collect(Collectors.toMap(AdminWebsit::getName, v -> v));
//
//        AdminWebsit detail = adminWebsitLogic.detail(mainDepartmentId, adminUser.getCorpId());
//        for (Object o : datas) {
//            List<String> row = (List<String>) o;
//            CommonUtils.initList(row, 10);
//            String name = row.get(0);
//            String gender = row.get(1);
//            String wechatUserId = row.get(2);
//            String postion = row.get(3);
//            String mobile = row.get(4);
//            String email = row.get(5);
//            String sync = row.get(6);
//            String websitName = row.get(7);
//
//            if (StringUtils.isBlank(name) || StringUtils.isBlank(gender) || StringUtils.isBlank(wechatUserId) || StringUtils.isBlank(mobile)) {
//                throw new RemoteServiceException("名称/性别/帐号/手机号都为必填项");
//            }
////            if(StringUtils.isBlank(websitName)){
////                throw new RemoteServiceException("部门名称必填");
////            }
////            AdminWebsit adminWebsit = adminWebsitMap.get(websitName);
////            if(adminWebsit == null){
////                throw new RemoteServiceException("部门名称【"+websitName+"】不存在");
////            }
//
//            //手机号存在则更新该信息
//            EnterpriseWechatWorker worker = workers.get(mobile);
//            if (worker != null) {
//                worker.setName(name);
//                worker.setPosition(postion);
//                worker.setEmail(email);
//                worker.setMainDepartment(mainDepartmentId.toString());
//                worker.setDepartmentName(detail.getName());
//                worker.updateById();
//                continue;
//            }
//
//            Integer count = enterpriseWechatWorkerService.lambdaQuery()
//                    .eq(EnterpriseWechatWorker::getWechatUserId, wechatUserId)
//                    .eq(EnterpriseWechatWorker::getCorpId,adminUser.getCorpId())
//                    .count();
//            if (count > 0) {
//                throw new RemoteServiceException("导入失败,帐号:" + wechatUserId + "已存在,无法导入");
//                //sb.append("帐号:"+wechatUserId+"已存在;");
//            }
//            WxCpUser wxCpUser = workWechatLogic.getUser(wechatUserId, adminUser.getAdminCompanyWechat());
//
//            EnterpriseWechatWorker enterpriseWechatWorker = new EnterpriseWechatWorker();
//            enterpriseWechatWorker.setName(name);
//            enterpriseWechatWorker.setGender(Integer.parseInt(gender));
//            enterpriseWechatWorker.setWechatUserId(wechatUserId);
//            enterpriseWechatWorker.setPosition(postion);
//            enterpriseWechatWorker.setMobile(mobile);
//            enterpriseWechatWorker.setEmail(email);
//            if (detail != null) {
//                enterpriseWechatWorker.setMainDepartment(mainDepartmentId.toString());
//                enterpriseWechatWorker.setDepartmentName(detail.getName());
//                enterpriseWechatWorker.setCorpId(detail.getCorpId());
//            }
//            if(wxCpUser != null){
//                enterpriseWechatWorker.setQrCode(wxCpUser.getQrCode());
//            }
//            enterpriseWechatWorker.setCreateTime(new Date());
//            enterpriseWechatWorkers.add(enterpriseWechatWorker);
//
//            if(StringUtils.isNotBlank(sync) && sync.equals("是")){
//                syncWechat.add(enterpriseWechatWorker);
//            }
//        }
//        enterpriseWechatWorkerService.saveBatch(enterpriseWechatWorkers);
////        for (EnterpriseWechatWorker enterpriseWechatWorker : syncWechat) {
////            workWechatLogic.addWorkUser(enterpriseWechatWorker.getWechatUserId(), enterpriseWechatWorker.getName(), enterpriseWechatWorker.getMobile(),
////                    enterpriseWechatWorker.getGender(), enterpriseWechatWorker.getEmail(), Long.parseLong(enterpriseWechatWorker.getMainDepartment()),
////                    enterpriseWechatWorker.getPosition(), adminUser.getAdminCompanyWechat());
////        }
//        return "导入成功" + enterpriseWechatWorkers.size() + "条。";
//    }
//
//    /**
//     * 导出成员
//     */
//    public ExcelData exportData(HttpServletRequest request, String keyword, String adminWebsitId, Long websitId) {
//        String[] titles = new String[]{"姓名", "性别", "帐号", "部门编号", "部门", "职务", "手机号码", "邮箱", "创建时间"};
//
//
//        List<String> corpIds = commonLogic.getAdminUser(request).getCorpIds();
//        List<Stroig> ids = new ArrayList<>();
//        List<AdminWebsit> list = new ArrayList<>();
//
//        String corpId = null;
//        if (StringUtils.isNotBlank(adminWebsitId) && websitId != null) {
//            list.addAll(adminWebsitLogic.queryAllChild(list, websitId));
//            ids.add(websitId);
//
//            corpId = adminWebsitLogic.detail(adminWebsitId).getCorpId();
//        }
//        ids.addAll(list.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList()));
//
//        List<EnterpriseWechatWorkerImportList> importList = enterpriseWechatWorkerLogicMapper.list(ids, keyword, corpIds, corpId);
//
//        List<List<Object>> rows = new ArrayList<>();
//        for (EnterpriseWechatWorkerImportList worker : importList) {
//            List<Object> row = new ArrayList<>();
//            String genderName = "未知";
//            if (worker.getGender() == 1) {
//                genderName = "男";
//            } else if (worker.getGender() == 2) {
//                genderName = "女";
//            }
//            row.add(worker.getName());
//            row.add(genderName);
//            row.add(worker.getWechatUserId());
//            row.add(worker.getWebsitNum());
//            row.add(worker.getDepartmentName());
//            row.add(worker.getPosition());
//            row.add(worker.getMobile());
//            row.add(worker.getEmail());
//            row.add(DateUtils.formatDate(worker.getCreateTime()));
//            rows.add(row);
//        }
//        ExcelData excelData = new ExcelData();
//        excelData.setTitles(Arrays.asList(titles));
//        excelData.setRows(rows);
//        return excelData;
//    }
//
//
//
//    public WxCpContactWayResult getCustomerQrCode(String userId,String configId,AdminCompanyWechat adminCompanyWechat) throws WxErrorException {
//        try {
//            WxCpService wxCpService = workWechatLogic.tongxunluApp(adminCompanyWechat);
//            //先删，后获取
//            try{
//                wxCpService.getExternalContactService().deleteContactWay(configId);
//            }catch(Exception e){
//
//            }
//
//            WxCpContactWayInfo wxCpContactWayInfo = new WxCpContactWayInfo();
//            WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
//            contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
//            contactWay.setType(WxCpContactWayInfo.TYPE.SINGLE);
//            contactWay.setUsers(Arrays.asList(userId));
//            wxCpContactWayInfo.setContactWay(contactWay);
//
//            WxCpContactWayResult wxCpContactWayResult = wxCpService.getExternalContactService().addContactWay(wxCpContactWayInfo);
//            return wxCpContactWayResult;
//        }catch(Exception e){
//            WxCpContactWayResult wxCpContactWayResult = new WxCpContactWayResult();
//            wxCpContactWayResult.setQrCode("");
//            wxCpContactWayResult.setConfigId("");
//            return wxCpContactWayResult;
//        }
//    }
//
//
//}
