package com.gree.mall.manager.logic.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.admin.AdminWebsitNewBean;
import com.gree.mall.manager.bean.admin.AdminWebsitTree;
import com.gree.mall.manager.bean.admin.reqDto.AdminUserAddReqBean;
import com.gree.mall.manager.bean.workorder.AdminWebsitList;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.enums.material.WebsitGoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.LbsAmapLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminWebsitLogic {

    //    @Autowired
//    WorkWechatLogic workWechatLogic;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    AdminZoneService adminZoneService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    StorageService storageService;
    @Autowired
    AdminWebsitPayConfigService adminWebsitPayConfigService;

    @Autowired
    AdminDeptService adminDeptService;

    @Autowired
    AdminDeptWebsitService adminDeptWebsitService;
    @Resource
    LbsAmapLogic lbsAmapLogic;
    @Resource
    AdminCompanyWechatPayConfigService adminCompanyWechatPayConfigService;
    @Resource
    WebsitUserService websitUserService;

    @Autowired
    WebsitDispatchService websitDispatchService;
    @Resource
    AdminUserLogic adminUserLogic;
//    @Autowired
//    EnterpriseWechatWorkerLogic enterpriseWechatWorkerLogic;

    /**
     * 区域列表
     */
    public List<AdminZone> adminZoneList() {
        List<AdminZone> list = adminZoneService.list();
        return list;
    }

    /**
     * 部门树
     */
    public List<AdminWebsitTree> tree(HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
                .and(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()), v -> v.in(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatIds()))
                .list();
        List<AdminWebsitTree> trees = new ArrayList<>();
        for (AdminWebsit adminWebsit : list) {
            AdminWebsitTree adminWebsitTree = new AdminWebsitTree();
            BeanUtils.copyProperties(adminWebsit, adminWebsitTree);
            trees.add(adminWebsitTree);
        }
        AdminUserWebsitRela one = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminUserId, adminUser.getAdminUserId()).last("limit 1").one();

        List<AdminWebsitTree> parentList = trees.stream()
                .filter(x -> (CollectionUtils.isEmpty(adminUser.getAdminWebsitIds()) && x.getParentId().equals("0")) ||
                        (!CollectionUtils.isEmpty(adminUser.getAdminWebsitIds()) && adminUser.getAdminWebsitIds().contains(x.getWebsitId())))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(parentList)) {
            parentList = trees.stream().filter(x -> x.getParentId().equals("0")).collect(Collectors.toList());
        }
        for (AdminWebsitTree adminWebsit : parentList) {
            adminWebsit.setChildren(this.treeModule(trees, adminWebsit.getWebsitId()));
        }
        return parentList;
    }

    public List<AdminWebsit> list(String type, Boolean isAll, Boolean isIncre, Boolean status, String streetCode, String channelId, String categoryId,
                                  String orderSmallId, String orderSourceId, Boolean queryPartsWebsit) {
        AdminUserCom adminUser = commonLogic.getAdminUser();


        List<String> websitIds = new ArrayList<>();
        if (!StringUtil.isEmpty(streetCode)) {
            websitIds = websitDispatchService.lambdaQuery()
                    .eq(!StringUtil.isEmpty(adminUser.getCompanyWechatId()), WebsitDispatch::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(!StringUtil.isEmpty(streetCode), WebsitDispatch::getStreetCode, streetCode)
                    .eq(!StringUtil.isEmpty(channelId), WebsitDispatch::getDictCode, channelId)
                    .eq(!StringUtil.isEmpty(categoryId), WebsitDispatch::getCategoryId, categoryId)
                    .eq(!StringUtil.isEmpty(orderSmallId), WebsitDispatch::getOrderSmallId, orderSmallId)
                    .eq(!StringUtil.isEmpty(orderSourceId), WebsitDispatch::getOrderSource, orderSourceId)
                    .list().stream().map(WebsitDispatch::getWebsitId).collect(Collectors.toList());
        }


        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
                .eq(StringUtils.isNotBlank(type), AdminWebsit::getType, type)
                .in(StringUtils.isNotBlank(streetCode) && !CollectionUtils.isEmpty(websitIds), AdminWebsit::getWebsitId, websitIds)
                .eq(isIncre != null, AdminWebsit::getIsIncre, isIncre)
                .eq(status != null, AdminWebsit::getStatus, status)
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()) && (isAll == null || !isAll), AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()), AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .and(Objects.nonNull(queryPartsWebsit) && queryPartsWebsit, v -> v.isNotNull(AdminWebsit::getPartsWebsitId)
                        .or()
                        .ne(AdminWebsit::getPartsWebsitId, ""))
                .list();
        return list;
    }


    /**
     * 新增部门
     */
    @Transactional
    public void add(AdminWebsitNewBean adminWebsit, HttpServletRequest request) throws WxErrorException, RemoteServiceException {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        AdminWebsit parent = adminWebsitService.getById(adminWebsit.getParentId());
        if (Objects.isNull(parent)) {
            throw new RemoteServiceException("请选择上级");
        }
        if (parent.getType().equals(AdminWebsitTypeEnum.A.getKey()) && adminUser.getType() != 2) {
            throw new RemoteServiceException("非平台账号不能创建商户");
        }
        if (parent.getType().equals(AdminWebsitTypeEnum.B.getKey()) && adminUser.getType() == 0) {
            throw new RemoteServiceException("网点账号不能创建网点");
        }
//        if(StringUtils.isNotBlank(parent.getCompanyWechatId())) {
//            //最多3个部门
//            final int max = 3;
//            Integer count1 = adminWebsitService.lambdaQuery()
//                    .eq(AdminWebsit::getCompanyWechatId, parent.getCompanyWechatId())
//                    .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey()).count();
//            if(count1 >= max){
//                throw new RemoteServiceException("创建网点数量已达上限3，请联系相关人员");
//            }
//        }

        if (parent.getType().equals(AdminWebsitTypeEnum.A.getKey())) {
            adminWebsit.setType(AdminWebsitTypeEnum.B.getKey());
        } else if (parent.getType().equals(AdminWebsitTypeEnum.B.getKey())) {
            adminWebsit.setType(AdminWebsitTypeEnum.C.getKey());
        }

        if (adminUser.getType() == 2 && adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
            throw new RemoteServiceException("平台账号不能创建网点");
        }

        this.checkWebsitIdAndName(adminWebsit, adminUser, true);

        if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())
                && adminWebsit.getIsUseAllinpay()
                && CollectionUtil.isEmpty(adminWebsit.getPayConfigList())) {
            throw new RemoteServiceException("支付配置不能为空");
        }

        adminWebsit.setCompanyWechatId(parent.getCompanyWechatId());
        adminWebsit.setCompanyWechatName(parent.getCompanyWechatName());
        if (!adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
            adminWebsit.setWebsitId(IdWorker.getIdStr());
        }
        adminWebsit.setWebsitNumber(adminWebsit.getWebsitId());
        adminWebsit.insert();

        if (adminWebsit.getIsUseAllinpay()
                && CollectionUtil.isNotEmpty(adminWebsit.getPayConfigList())) {
            for (int i = 0; i < adminWebsit.getPayConfigList().size(); i++) {
                AdminWebsitPayConfig payConfig = adminWebsit.getPayConfigList().get(i);
                if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getName())) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 商户名称不能为空");
                }
                if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getType())) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 请选择类别");
                }
                if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getMchNo())) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 通联商户号不能为空");
                }
                if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getAppid())) {
                    throw new RemoteServiceException("第" + (i + 1) + "行, 通联商户appid不能为空");
                }
                payConfig.setCompanyWechatId(adminWebsit.getCompanyWechatId())
                        .setCompanyWechatName(adminWebsit.getCompanyWechatName())
                        .setWebsitId(adminWebsit.getWebsitId());
            }
            adminWebsitPayConfigService.saveBatch(adminWebsit.getPayConfigList());
        }

        reloadJoinCode(adminWebsit.getCompanyWechatId(), adminWebsit.getJoinCode());

        // 初始化辅材配件默认仓
        initMaterialStorage(adminUser, adminWebsit);


        AdminDept adminDept = adminDeptService.lambdaQuery().eq(AdminDept::getCompanyWechatId, adminWebsit.getCompanyWechatId())
                .eq(AdminDept::getPId, "1").last("limit 1").one();
        AdminDeptWebsit adminDeptWebsit = new AdminDeptWebsit();
        adminDeptWebsit.setAdminDeptId(adminDept.getAdminDeptId());
        adminDeptWebsit.setWebsitId(adminWebsit.getWebsitId());
        adminDeptWebsit.setWebsitName(adminWebsit.getName());
        adminDeptWebsit.setDeptName(adminDept.getDeptName());
        adminDeptWebsit.insert();

        // 网点新增账号
        if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey()))
            this.addAdminUser(adminWebsit);
    }

    private void addAdminUser(AdminWebsitNewBean adminWebsit) {
        AdminUserAddReqBean adminUser = new AdminUserAddReqBean();
        adminUser.setCompanyWechatId(adminWebsit.getCompanyWechatId())
                .setCompanyName(adminWebsit.getCompanyWechatName())
                .setUserName(adminWebsit.getWebsitId())
                .setNickName(adminWebsit.getName())
                .setRoleId("1831614042544427009")
                .setPassword(adminWebsit.getWebsitPhone())
                .setPubNotice(true)
                .setIsVender(false)
                .setLinkPhone(adminWebsit.getWebsitPhone());
        adminUser.setAdminWebsitId(Collections.singletonList(adminWebsit.getWebsitId()));
        adminUserLogic.add(adminUser, false);
    }

    private void initMaterialStorage(AdminUserCom adminUser, AdminWebsit adminWebsit) {
        if (!adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
            return;
        }
        Storage storage = storageService.lambdaQuery()
                .eq(Storage::getCompanyWechatId, adminWebsit.getCompanyWechatId())
                .eq(Storage::getWebsitId, adminWebsit.getWebsitId())
                .eq(Storage::getType, "辅材,配件")
                .eq(Storage::getIsDefault, true)
                .last("limit 1")
                .one();

        if (Objects.isNull(storage)) {
            storage = new Storage();
            storage.setCompanyWechatId(adminWebsit.getCompanyWechatId())
                    .setCompanyName(adminWebsit.getCompanyWechatName())
                    .setWebsitId(adminWebsit.getWebsitId())
                    .setWebsitName(adminWebsit.getName())
                    .setStorageName("辅材,配件默认仓")
                    .setType("辅材,配件")
                    .setStatus(true)
                    .setIsDefault(true)
                    .insert();
        }
    }

    private void checkWebsitIdAndName(AdminWebsitNewBean adminWebsit, AdminUserCom adminUser, boolean isAdd) {
        if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey()) && isAdd) {
            if (org.apache.commons.lang3.StringUtils.isBlank(adminWebsit.getWebsitId())) {
                throw new RemoteServiceException("网点编号不能为空");
            }

            Integer existCount = adminWebsitService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()), AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                    .eq(AdminWebsit::getWebsitId, adminWebsit.getWebsitId())
                    .count();

            if (existCount > 0) {
                throw new RemoteServiceException("网点编号已存在");
            }
        }

        Integer count = adminWebsitService.lambdaQuery()
                .ne(org.apache.commons.lang3.StringUtils.isNotBlank(adminWebsit.getWebsitId()), AdminWebsit::getWebsitId, adminWebsit.getWebsitId())
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()), AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(AdminWebsit::getName, adminWebsit.getName())
                .count();

        if (count > 0) {
            throw new RemoteServiceException("名称已存在");
        }
    }

    /**
     * 编辑部门
     */
    @Transactional
    public void update(AdminWebsitNewBean adminWebsit, HttpServletRequest request) throws RemoteServiceException, WxErrorException {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        Integer count = adminWebsitService.lambdaQuery()
                .ne(AdminWebsit::getWebsitId, adminWebsit.getWebsitId())
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()), AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(AdminWebsit::getName, adminWebsit.getName())
                .count();
        if (count > 0) {
            throw new RemoteServiceException("名称已存在");
        }
        if (adminWebsit.getParentId().equals("0")) {
            throw new RemoteServiceException("请选择上级");
        }
        AdminWebsit parent = adminWebsitService.getById(adminWebsit.getParentId());
        if (Objects.isNull(parent)) {
            throw new RemoteServiceException("请选择上级");
        }
        if (parent.getType().equals(AdminWebsitTypeEnum.A.getKey()) && adminUser.getType() != 2) {
            throw new RemoteServiceException("非平台账号不能创建商户");
        }
        if (parent.getType().equals(AdminWebsitTypeEnum.B.getKey()) && adminUser.getType() == 0) {
            throw new RemoteServiceException("网点账号不能创建网点");
        }
        if (StringUtils.equals(adminWebsit.getWebsitId(), adminWebsit.getParentId())) {
            throw new RemoteServiceException("上级不允许为自己");
        }
        if (parent.getType().equals(AdminWebsitTypeEnum.A.getKey())) {
            adminWebsit.setType(AdminWebsitTypeEnum.B.getKey());
        } else if (parent.getType().equals(AdminWebsitTypeEnum.B.getKey())) {
            adminWebsit.setType(AdminWebsitTypeEnum.C.getKey());
        }

        adminWebsit.updateById();

        adminDeptWebsitService.lambdaUpdate().eq(AdminDeptWebsit::getWebsitId, adminWebsit.getWebsitId())
                .set(AdminDeptWebsit::getWebsitName, adminWebsit.getName()).update();

        AdminWebsit old = adminWebsitService.getById(adminWebsit.getWebsitId());
        //workWechatLogic.updateOrganization(adminWebsit.getWebsitId(),adminWebsit.getName(),adminWebsit.getParentId(),adminUser.getAdminCompanyWechat());
        if (old.getType().equals(AdminWebsitTypeEnum.B.getKey())) {
            adminCompanyWechatService.lambdaUpdate()
                    .set(AdminCompanyWechat::getLinkPhone, adminWebsit.getWebsitPhone())
                    .eq(AdminCompanyWechat::getCompanyWechatId, old.getCompanyWechatId()).update();
        }
        //刷新成员部门名称
//        enterpriseWechatWorkerLogic.reloadEnterpriseWechatName(adminWebsit,request);
        reloadJoinCode(old.getCompanyWechatId(), adminWebsit.getJoinCode());


    }

    /**
     * 删除部门
     */
    @Transactional
    public void delete(String websitId, HttpServletRequest request) throws WxErrorException {
        Integer count = adminWebsitService.lambdaQuery().eq(AdminWebsit::getParentId, websitId).count();
        if (count > 0) {
            throw new RemoteServiceException("当前部门存在子级，删除失败");
        }
        final Integer existUserCount = adminUserWebsitRelaService.lambdaQuery()
                .eq(AdminUserWebsitRela::getAdminWebsitId, websitId)
                .count();
        if (existUserCount > 0) {
            throw new RemoteServiceException("当前部门存在与账号绑定关系，删除失败");
        }
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        final AdminWebsit adminWebsit = adminWebsitService.getById(websitId);
        // 普通网点连带删除辅材配件仓
        if (adminWebsit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
            storageService.lambdaUpdate()
                    .eq(Storage::getCompanyWechatId, adminWebsit.getCompanyWechatId())
                    .eq(Storage::getWebsitId, adminWebsit.getWebsitId())
                    .remove();
        }

        //递归删除
        List<AdminWebsit> list = new ArrayList<>();
        list.addAll(commonLogic.queryAllChild(list, websitId));
        List<String> ids = list.stream().map(AdminWebsit::getWebsitId).collect(Collectors.toList());
        ids.add(websitId);
        if (ids.size() > 0) {
//            for(String idd : ids){
//                workWechatLogic.deleteOrganization(idd,adminUser.getAdminCompanyWechat());
//            }
            for (String id : ids) {
                final Integer existSubUserCount = adminUserWebsitRelaService.lambdaQuery()
                        .eq(AdminUserWebsitRela::getAdminWebsitId, id)
                        .count();

                if (existSubUserCount > 0) {
                    throw new RemoteServiceException(websitId + "部门的" + id + "子级部门存在与账号绑定关系，删除失败");
                }
            }
            adminWebsitService.lambdaUpdate().in(AdminWebsit::getWebsitId, ids).remove();
        }

        // 删除子级普通网点辅材配件仓
        final List<String> materialWebsitList = list.stream()
                .filter(v -> v.getType().equals(AdminWebsitTypeEnum.C.getKey()))
                .map(AdminWebsit::getWebsitId)
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(materialWebsitList)) {
            storageService.lambdaUpdate()
                    .eq(Storage::getCompanyWechatId, adminWebsit.getCompanyWechatId())
                    .in(Storage::getWebsitId, materialWebsitList)
                    .remove();

            websitUserService.lambdaUpdate()
                    .set(WebsitUser::getExamineStatus, ExamineStatusEnum.FAIL.getKey())
                    .set(WebsitUser::getExamineRemark, "网点已删除")
                    .in(WebsitUser::getWebsitId, materialWebsitList)
                    .update();
        }

        adminDeptWebsitService.lambdaUpdate().eq(AdminDeptWebsit::getWebsitId, websitId).remove();
    }

    /**
     * 详情
     *
     * @param id
     */
    public AdminWebsitNewBean detail(String id) {
        AdminWebsit adminWebsit = adminWebsitService.getById(id);
        AdminWebsitNewBean bean = new AdminWebsitNewBean();
        BeanUtils.copyProperties(adminWebsit, bean);
        if (bean.getIsUseAllinpay() && bean.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
            final List<AdminWebsitPayConfig> payConfigList = adminWebsitPayConfigService.lambdaQuery()
                    .eq(AdminWebsitPayConfig::getWebsitId, bean.getWebsitId())
                    .list();
            bean.setPayConfigList(payConfigList);
        }
        return bean;
    }

    /**
     * 刷新之后关联条码
     */
    @Transactional
    public void reloadJoinCode(String companyWechatId, String joinCode) {
        if (StringUtils.isBlank(companyWechatId) || joinCode == null) {
            return;
        }
        adminWebsitService.lambdaUpdate()
                .set(AdminWebsit::getJoinCode, joinCode)
                .eq(AdminWebsit::getCompanyWechatId, companyWechatId).update();

        adminCompanyWechatService.lambdaUpdate()
                .set(AdminCompanyWechat::getJoinCode, joinCode)
                .eq(AdminCompanyWechat::getCompanyWechatId, companyWechatId).update();

    }


    /**
     * 递归组装数据
     *
     * @param list
     * @param parentId
     * @return
     */
    private List<AdminWebsitTree> treeModule(List<AdminWebsitTree> list, String parentId) {
        //最父级资源树
        if (parentId == null || parentId.equals("0")) {
            return null;
        }
        List<AdminWebsitTree> collect = list.stream()
                .filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        if (collect.size() == 0) {
            return null;
        }
        for (AdminWebsitTree bean : collect) {
            bean.setChildren(this.treeModule(list, bean.getWebsitId()));
        }
        return collect;
    }

    public void savePayConfig(AdminWebsitPayConfig payConfig, HttpServletRequest request) {
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getCompanyWechatId())) {
            throw new RemoteServiceException("商户信息不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getCompanyWechatName())) {
            throw new RemoteServiceException("商户信息不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getWebsitId())) {
            throw new RemoteServiceException("网点编号不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getName())) {
            throw new RemoteServiceException("商户名称不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getType())) {
            throw new RemoteServiceException("请选择类别");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getMchNo())) {
            throw new RemoteServiceException("通联商户号不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(payConfig.getAppid())) {
            throw new RemoteServiceException("通联商户appid不能为空");
        }

        AdminWebsit adminWebsit = adminWebsitService.getById(payConfig.getWebsitId());
        if (!adminWebsit.getIsUseAllinpay()) {
            adminWebsit.setIsUseAllinpay(true)
                    .updateById();
        }

        payConfig.insertOrUpdate();
    }

    public void deletePayConfig(String id, HttpServletRequest request) {
        adminWebsitPayConfigService.removeById(id);
    }

    public List<AdminWebsitPayConfig> payConfigList(String websitId, String type, Boolean status) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
            throw new RemoteServiceException("请使用商户账号发现支付");
        }
        return adminWebsitPayConfigService.lambdaQuery()
                .eq(AdminWebsitPayConfig::getCompanyWechatId, adminUser.getAdminCompanyWechat().getCompanyWechatId())
                .eq(StringUtils.isNotBlank(websitId), AdminWebsitPayConfig::getWebsitId, websitId)
                .eq(StringUtils.isNotBlank(type), AdminWebsitPayConfig::getType, type)
                .eq(Objects.nonNull(status), AdminWebsitPayConfig::getStatus, status)
                .list();
    }

    @Transactional
    public void importData(MultipartFile file) throws Exception {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyWechatId() : null;
        String companyName = Objects.nonNull(adminUser.getAdminCompanyWechat()) ? adminUser.getAdminCompanyWechat().getCompanyName() : null;

        if (org.apache.commons.lang3.StringUtils.isBlank(companyWechatId)) {
            throw new RemoteServiceException("商户编号缺失，导入中止");
        }

        final AdminWebsit parentWebsit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, companyWechatId)
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.B.getKey())
                .last("limit 1")
                .one();

        if (Objects.isNull(parentWebsit)) {
            throw new RemoteServiceException("未发现上级");
        }

        List<Object> objects = ExcelUtils.importExcel(file);

        List<AdminWebsit> adminWebsitList = new ArrayList<>();
        List<AdminWebsitPayConfig> allPayConfigList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            int rowIndex = i + 2;
            List<Object> row = (List<Object>) objects.get(i);
            if (Objects.isNull(row.get(0)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(0).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 网点编号不能为空");
            }
            if (Objects.isNull(row.get(1)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(1).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 网点名称不能为空");
            }
            if (Objects.isNull(row.get(2)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(2).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 联系人不能为空");
            }
            if (Objects.isNull(row.get(3)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(3).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 联系电话不能为空");
            }
            if (Objects.isNull(row.get(4)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(4).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 详细地址不能为空");
            }
            if (Objects.isNull(row.get(5)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(5).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 电子支付商户不能为空");
            }
            if (Objects.isNull(row.get(6)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(6).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 状态不能为空");
            }
            if (Objects.isNull(row.get(7)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(7).toString())) {
                throw new RemoteServiceException("第" + rowIndex + "行, 通联支付开关不能为空");
            }

            String websitName = row.get(1).toString().trim();
            final Integer existNameCount = adminWebsitService.lambdaQuery()
                    .eq(AdminWebsit::getName, websitName)
                    .count();
            if (existNameCount > 0) {
                throw new RemoteServiceException("第" + rowIndex + "行, 网点名称已重复存在");
            }
            String address = row.get(4).toString().trim();
            String lnglat = lbsAmapLogic.getLocationByAddress(address);

            String payName = row.get(5).toString().trim();
            final AdminCompanyWechatPayConfig wechatPayConfig = adminCompanyWechatPayConfigService.lambdaQuery()
                    .eq(AdminCompanyWechatPayConfig::getPayMerchantName, payName)
                    .one();
            if (Objects.isNull(wechatPayConfig)) {
                throw new RemoteServiceException("第" + rowIndex + "行, 电子支付商户不存在");
            }
            final String statusName = row.get(6).toString().trim();
            final boolean status = statusName.equals("启用");
            final String allinpayName = row.get(7).toString().trim();
            final boolean isUseAllinpay = allinpayName.equals("开启");

            AdminWebsit addWebsit = new AdminWebsit();
            addWebsit.setWebsitId(row.get(0).toString());
            addWebsit.setName(websitName);
            addWebsit.setType(AdminWebsitTypeEnum.C.getKey());
            addWebsit.setParentId(parentWebsit.getWebsitId());
            addWebsit.setWebsitNumber(addWebsit.getWebsitId());
            addWebsit.setStatus(status);
            addWebsit.setAddress(address);
            addWebsit.setCompanyWechatId(companyWechatId);
            addWebsit.setCompanyWechatName(companyName);
            addWebsit.setLng(lnglat.split(",")[0]);
            addWebsit.setLat(lnglat.split(",")[1]);
            addWebsit.setLinkName(row.get(2).toString().trim());
            addWebsit.setWebsitPhone(row.get(3).toString().trim());
            addWebsit.setPayWorkerCodeId(wechatPayConfig.getId());
            addWebsit.setIsUseAllinpay(isUseAllinpay);

            adminWebsitList.add(addWebsit);
            List<AdminWebsitPayConfig> payConfigList = new ArrayList<>();
            if (isUseAllinpay) {
                boolean isOn = true;
                int detailIndex = 1;
                int detailStartIndex = 7;
                while (isOn) {
                    try {
                        row.get(detailStartIndex + 1);
                    } catch (IndexOutOfBoundsException e) {
                        isOn = false;
                        continue;
                    }

                    try {
                        if (Objects.isNull(row.get(detailStartIndex + 1)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 1).toString())) {
//                            throw new RemoteServiceException("第" + rowIndex + "行, 通联商户名称" + detailIndex + "不能为空");
                            isOn = false;
                        }

//                      if (Objects.isNull(row.get(detailStartIndex + 2)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 2).toString())) {
//                          throw new RemoteServiceException("第" + rowIndex + "行, 通联集团号" + detailIndex + "不能为空");
//                      }
                        if (Objects.isNull(row.get(detailStartIndex + 3)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 3).toString())) {
                            throw new RemoteServiceException("第" + rowIndex + "行, 类别" + detailIndex + "不能为空");
                        }
                        if (Objects.isNull(row.get(detailStartIndex + 4)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 4).toString())) {
                            throw new RemoteServiceException("第" + rowIndex + "行, 通联商户号" + detailIndex + "不能为空");
                        }
                        if (Objects.isNull(row.get(detailStartIndex + 5)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 5).toString())) {
                            throw new RemoteServiceException("第" + rowIndex + "行, 通联商户appid" + detailIndex + "不能为空");
                        }
                        if (Objects.isNull(row.get(detailStartIndex + 6)) || org.apache.commons.lang3.StringUtils.isBlank(row.get(detailStartIndex + 6).toString())) {
                            throw new RemoteServiceException("第" + rowIndex + "行, 状态" + detailIndex + "不能为空");
                        }
                        AdminWebsitPayConfig config = new AdminWebsitPayConfig();
                        config.setCompanyWechatId(addWebsit.getCompanyWechatId());
                        config.setCompanyWechatName(addWebsit.getCompanyWechatName());
                        config.setWebsitId(addWebsit.getWebsitId());
                        config.setName(row.get(detailStartIndex + 1).toString());
                        config.setOrgId(Optional.ofNullable(row.get(detailStartIndex + 2)).orElse("").toString().trim());
                        config.setType(row.get(detailStartIndex + 3).toString().equals(WebsitGoodsTypeEnum.M.getRemark()) ? WebsitGoodsTypeEnum.M.getKey() : WebsitGoodsTypeEnum.P.getKey());
                        config.setMchNo(row.get(detailStartIndex + 4).toString().trim());
                        config.setAppid(row.get(detailStartIndex + 5).toString().trim());
                        config.setStatus(row.get(detailStartIndex + 6).toString().trim().equals("开启"));
                        payConfigList.add(config);

                        detailIndex++;
                        detailStartIndex = detailStartIndex + 6;
                    } catch (IndexOutOfBoundsException e) {
                        throw new RemoteServiceException("第" + rowIndex + "行, 第" + (detailStartIndex + 1) + "个通联相关配置缺失");
                    }
                }
            }

            if (CollectionUtil.isNotEmpty(payConfigList)) {
                allPayConfigList.addAll(payConfigList);
            }
        }

        if (CollectionUtil.isNotEmpty(adminWebsitList)) {
            // 检查本次导入是否有重复编号和名称
            Map<String, List<AdminWebsit>> websitGroup = adminWebsitList.stream().collect(Collectors.groupingBy(AdminWebsit::getName));
            for (Map.Entry<String, List<AdminWebsit>> entry : websitGroup.entrySet()) {
                if (entry.getValue().size() > 1) {
                    throw new RemoteServiceException("导入文档有重复的网点名称" + entry.getKey());
                }
            }

            websitGroup = adminWebsitList.stream().collect(Collectors.groupingBy(AdminWebsit::getWebsitId));
            for (Map.Entry<String, List<AdminWebsit>> entry : websitGroup.entrySet()) {
                if (entry.getValue().size() > 1) {
                    throw new RemoteServiceException("导入文档有重复的网点编号" + entry.getKey());
                }
                final Integer count = adminWebsitService.lambdaQuery()
                        .eq(AdminWebsit::getCompanyWechatId, companyWechatId)
                        .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                        .eq(AdminWebsit::getWebsitId, entry.getKey())
                        .count();
                if (count > 0) {
                    throw new RemoteServiceException("网点编号" + entry.getKey() + " 在系统里已存在");
                }

                final Integer nameCount = adminWebsitService.lambdaQuery()
                        .eq(AdminWebsit::getCompanyWechatId, companyWechatId)
                        .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                        .eq(AdminWebsit::getName, entry.getValue().get(0).getName())
                        .count();
                if (nameCount > 0) {
                    throw new RemoteServiceException("网点名称" + entry.getKey() + " 在系统里已存在");
                }
            }

            for (AdminWebsit websit : adminWebsitList) {
                reloadJoinCode(websit.getCompanyWechatId(), websit.getJoinCode());

                // 初始化辅材配件默认仓
                initMaterialStorage(adminUser, websit);


                AdminDept adminDept = adminDeptService.lambdaQuery().eq(AdminDept::getCompanyWechatId, websit.getCompanyWechatId())
                        .eq(AdminDept::getPId, "1").last("limit 1").one();
                AdminDeptWebsit adminDeptWebsit = new AdminDeptWebsit();
                adminDeptWebsit.setAdminDeptId(adminDept.getAdminDeptId());
                adminDeptWebsit.setWebsitId(websit.getWebsitId());
                adminDeptWebsit.setWebsitName(websit.getName());
                adminDeptWebsit.setDeptName(adminDept.getDeptName());
                adminDeptWebsit.insert();

                // 网点新增账号
                if (websit.getType().equals(AdminWebsitTypeEnum.C.getKey())) {
                    AdminWebsitNewBean reqBean = new AdminWebsitNewBean();
                    BeanUtils.copyProperties(websit, reqBean);
                    this.addAdminUser(reqBean);
                }
            }
            if (CollectionUtil.isNotEmpty(allPayConfigList)) {
                adminWebsitPayConfigService.saveBatch(allPayConfigList);
            }

            adminWebsitService.saveBatch(adminWebsitList);
        }
    }

    public ExcelData exportData() {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<List<Object>> rows = new ArrayList<>();

        String companyId = "";
        String companyName = "";
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
            companyName = adminUser.getAdminCompanyWechat().getCompanyName();
        }

        ExcelData excelData = new ExcelData();

        final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(companyId), AdminWebsit::getCompanyWechatId, companyId)
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .in(CollectionUtil.isNotEmpty(adminUser.getAdminWebsitIds()), AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                .list();

        List<String> titleList = new ArrayList<>();
        titleList.add("网点编号");
        titleList.add("网点名称");
        titleList.add("联系人");
        titleList.add("详细地址");
        titleList.add("电子支付商户名称");
        titleList.add("状态");
        titleList.add("通联支付开关");

        if (CollectionUtil.isEmpty(websitList)) {
            excelData.setTitles(titleList);
            excelData.setRows(rows);
            return excelData;
        }

        final List<AdminWebsitPayConfig> payConfigList = adminWebsitPayConfigService.lambdaQuery()
                .in(AdminWebsitPayConfig::getWebsitId, websitList.stream()
                        .map(AdminWebsit::getWebsitId)
                        .collect(Collectors.toList()))
                .list();

        final List<AdminCompanyWechatPayConfig> wechatPayConfigs = adminCompanyWechatPayConfigService.lambdaQuery()
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(companyId), AdminCompanyWechatPayConfig::getCompanyWechatId, companyId)
                .list();

        final Map<String, AdminCompanyWechatPayConfig> wechatPayConfigMap = wechatPayConfigs.stream()
                .collect(Collectors.toMap(AdminCompanyWechatPayConfig::getId, Function.identity()));

        final Map<String, List<AdminWebsitPayConfig>> itemMap = payConfigList.stream()
                .collect(Collectors.groupingBy(AdminWebsitPayConfig::getWebsitId));

        // 计算出最多行配置数量
        int configCount = 0;
        for (Map.Entry<String, List<AdminWebsitPayConfig>> entry : itemMap.entrySet()) {
            if (entry.getValue().size() > configCount) {
                configCount = entry.getValue().size();
            }
        }

        for (int i = 0; i < configCount; i++) {
            titleList.add("通联商户名称" + (i + 1));
            titleList.add("通联集团号" + (i + 1));
            titleList.add("类别" + (i + 1));
            titleList.add("通联商户号" + (i + 1));
            titleList.add("通联商户appid" + (i + 1));
            titleList.add("状态" + (i + 1));
        }

        int requireRowSize = titleList.size();

        for (AdminWebsit websit : websitList) {
            List<Object> row = new ArrayList<>();

            final AdminCompanyWechatPayConfig wechatPayConfig = wechatPayConfigMap.get(websit.getPayWorkerCodeId());
            row.add(websit.getWebsitId());
            row.add(websit.getName());
            row.add(websit.getLinkName());
            row.add(websit.getAddress());
            row.add(Objects.nonNull(wechatPayConfig) ? wechatPayConfig.getPayMerchantName() : "无");
            row.add(websit.getStatus() ? "启用" : "禁用");
            row.add(websit.getIsUseAllinpay() ? "开启" : "关闭");

            final List<AdminWebsitPayConfig> items = itemMap.get(websit.getWebsitId());
            if (CollectionUtil.isNotEmpty(items)) {
                for (AdminWebsitPayConfig item : items) {
                    row.add(item.getName());
                    row.add(item.getOrgId());
                    row.add(item.getType().equals(WebsitGoodsTypeEnum.M.getKey()) ? WebsitGoodsTypeEnum.M.getRemark() : WebsitGoodsTypeEnum.P.getRemark());
                    row.add(item.getMchNo());
                    row.add(item.getAppid());
                    row.add(item.getStatus() ? "开启" : "关闭");
                }
            }

            if (row.size() != requireRowSize) {
                int needRowSize = requireRowSize - row.size();
                if (needRowSize > 0) {
                    for (int i = 0; i < needRowSize; i++) {
                        row.add("");
                    }
                }
            }

            rows.add(row);
        }

        excelData.setTitles(titleList);
        excelData.setRows(rows);
        return excelData;
    }

    public List<AdminWebsitList> websitList(String type, Boolean isAll, Boolean isIncre, Boolean status, String streetCode, String channelId, String categoryId,
                                            String orderSmallId, String orderSourceId) {

            AdminUserCom adminUser = commonLogic.getAdminUser();


            List<String> websitIds = new ArrayList<>();
            if (!StringUtil.isEmpty(streetCode)) {
                websitIds = websitDispatchService.lambdaQuery()
                        .eq(!StringUtil.isEmpty(adminUser.getCompanyWechatId()), WebsitDispatch::getCompanyWechatId, adminUser.getCompanyWechatId())
                        .eq(!StringUtil.isEmpty(streetCode), WebsitDispatch::getStreetCode, streetCode)
                        .eq(!StringUtil.isEmpty(channelId), WebsitDispatch::getDictCode, channelId)
                        .eq(!StringUtil.isEmpty(categoryId), WebsitDispatch::getCategoryId, categoryId)
                        .eq(!StringUtil.isEmpty(orderSmallId), WebsitDispatch::getOrderSmallId, orderSmallId)
                        .eq(!StringUtil.isEmpty(orderSourceId), WebsitDispatch::getOrderSource, orderSourceId)
                        .list().stream().map(WebsitDispatch::getWebsitId).collect(Collectors.toList());
            }


            List<AdminWebsit> list = adminWebsitService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(type), AdminWebsit::getType, type)
                  //  .in(StringUtils.isNotBlank(streetCode) && !CollectionUtils.isEmpty(websitIds), AdminWebsit::getWebsitId, websitIds)
                    .eq(isIncre != null, AdminWebsit::getIsIncre, isIncre)
                    .eq(status != null, AdminWebsit::getStatus, status)
                    .in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()) && (isAll == null || !isAll), AdminWebsit::getWebsitId, adminUser.getAdminWebsitIds())
                    .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()), AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatIds())
                    .list();


        List<AdminWebsitList> adminWebsitLists = BeanUtil.copyToList(list, AdminWebsitList.class);

        if (!CollectionUtils.isEmpty(websitIds)) {

            for (AdminWebsitList adminWebsitList : adminWebsitLists) {
                if (websitIds.contains(adminWebsitList.getWebsitId())) {
                    adminWebsitList.setIfDispatch(true);
                }
            }
        }

        return adminWebsitLists;
    }
}
