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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminDeptTree;
import com.gree.mall.manager.bean.admin.AdminDeptWebsitVO;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.commonmapper.AdminMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.AdminDept;
import com.gree.mall.manager.plus.entity.AdminDeptWebsit;
import com.gree.mall.manager.plus.entity.AdminUserPermissionsRela;
import com.gree.mall.manager.plus.entity.AdminWebsit;
import com.gree.mall.manager.plus.service.AdminDeptService;
import com.gree.mall.manager.plus.service.AdminDeptWebsitService;
import com.gree.mall.manager.plus.service.AdminUserPermissionsRelaService;
import com.gree.mall.manager.plus.service.AdminWebsitService;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.DeptZfireParamBean;
import com.gree.mall.manager.zfire.bean.QueryParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AdminDeptLogic {

    private final CommonLogic commonLogic;
    private final AdminDeptService adminDeptService;
    private final AdminMapper adminMapper;
    private final AdminDeptWebsitService adminDeptWebsitService;
    private final AdminUserPermissionsRelaService adminUserPermissionsRelaService;
    private final AdminWebsitService adminWebsitService;

    public List<AdminDeptTree> tree(HttpServletRequest request) {
        final AdminUserCom adminUser = commonLogic.getAdminUser();
        List<AdminDept> list = new ArrayList<>();
        if (!adminUser.getType().equals(1) ){
            list = adminDeptService.lambdaQuery()
                    .in(CollectionUtil.isNotEmpty(adminUser.getAdminCompanyIds()), AdminDept::getCompanyId, adminUser.getAdminCompanyIds())
                    .eq(AdminDept::getPId, "1")
                    .list();
        }else{
            list = adminDeptService.lambdaQuery()
                    .in(CollectionUtil.isNotEmpty(adminUser.getAdminCompanyIds()), AdminDept::getCompanyId, adminUser.getCompanyId())
                    .eq(AdminDept::getAdminDeptId, "1")
                    .list();
        }


        List<AdminDeptTree> trees = new ArrayList<>();
        for (AdminDept adminDept : list) {
            AdminDeptTree adminDeptTree = new AdminDeptTree();
            BeanUtils.copyProperties(adminDept, adminDeptTree);
            trees.add(adminDeptTree);
        }

        for (AdminDeptTree adminDeptTree : trees) {
            adminDeptTree.setChildren(this.treeModule(adminDeptTree.getAdminDeptId()));
        }
        return trees;
    }

    private List<AdminDeptTree> treeModule(String adminDeptId) {
        //最父级资源树
        List<AdminDept> collect = adminDeptService.lambdaQuery()
                .eq(AdminDept::getPId, adminDeptId).list();

        if (collect.size() == 0) {
            return new ArrayList<>();
        }

        List<AdminDeptTree> adminDeptTrees = new ArrayList<>();

        for (AdminDept bean : collect) {
            AdminDeptTree adminDeptTree = new AdminDeptTree();
            BeanUtils.copyProperties(bean, adminDeptTree);
            adminDeptTree.setChildren(this.treeModule(adminDeptTree.getAdminDeptId()));

            adminDeptTrees.add(adminDeptTree);
        }
        return adminDeptTrees;
    }

    public IPage<AdminDeptWebsitVO> list(Page page, DeptZfireParamBean zfireParam) {
        //获取当前登录企业id
        AdminUserCom adminUser = commonLogic.getAdminUser();

        boolean isAll = false;
        if (CollectionUtil.isNotEmpty(zfireParam.getParams())) {
            for (QueryParamBean param : zfireParam.getParams()) {
                if (param.getParam().equals("admin_dept_id") && param.getValue().equals("1")) {
                    isAll = true;
                    break;
                }
            }
        }

        //1.组装查询条件
        FieldUtils.supplyParam(zfireParam, AdminDeptWebsitVO.class);

        IPage<AdminDeptWebsitVO> adminDeptWebsitVOIPage = adminMapper.list(page, zfireParam);
        if (isAll && CollectionUtil.isEmpty(adminDeptWebsitVOIPage.getRecords())) {
            final AdminDept adminDept = adminDeptService.getById(zfireParam.getCurDeptId());
            String companyId = Objects.nonNull(adminDept) ? adminDept.getCompanyId() : null;
            final List<AdminWebsit> websitList = adminWebsitService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(companyId), AdminWebsit::getCompanyId, companyId)
                    .list();
            if (CollectionUtil.isNotEmpty(websitList)) {
                List<AdminDeptWebsitVO> voList = new ArrayList<>();
                for (AdminWebsit websit : websitList) {
                    AdminDeptWebsitVO vo = new AdminDeptWebsitVO();
                    vo.setAdminDeptId("1");
                    vo.setDeptName("平台");
                    vo.setWebsitId(websit.getWebsitId());
                    vo.setWebsitName(websit.getName());
                    voList.add(vo);
                }
                if (CollectionUtil.isNotEmpty(voList)) {
                    adminDeptWebsitVOIPage.setTotal(voList.size());
                    adminDeptWebsitVOIPage.setPages(1);
                    adminDeptWebsitVOIPage.setRecords(voList);
                }
            }
        }
        return adminDeptWebsitVOIPage;
    }

    public void add(AdminDept adminDept) {
        AdminDept adminDeptServiceById = adminDeptService.getById(adminDept.getPId());

        adminDept.setCompanyId(adminDeptServiceById.getCompanyId());
        adminDept.setCompanyName(adminDeptServiceById.getCompanyName());
        adminDept.insert();
    }

    public void update(AdminDept adminDept) {
        final AdminDept dept = adminDeptService.getById(adminDept.getAdminDeptId());
        if (dept.getPId().equals("1") && StringUtils.isNotBlank(dept.getCompanyId())) {
            throw new RemoteServiceException("商户名称不能变更");
        }
        adminDept.updateById();

        adminDeptWebsitService.lambdaUpdate()
                .eq(AdminDeptWebsit::getAdminDeptId, adminDept.getAdminDeptId())
                .set(AdminDeptWebsit::getDeptName, adminDept.getDeptName())
                .update();
    }

    public void del(String id) {
        final AdminDept dept = adminDeptService.getById(id);
        if (dept.getPId().equals("1") && StringUtils.isNotBlank(dept.getCompanyId())) {
            throw new RemoteServiceException("商户不能删除");
        }

        if (adminDeptWebsitService.lambdaQuery().eq(AdminDeptWebsit::getAdminDeptId, id).count() > 0)
            throw new RemoteServiceException("存在绑定商家");

        if (adminUserPermissionsRelaService.lambdaQuery().eq(AdminUserPermissionsRela::getAdminUserPermissionsId, id).count() > 0) {
            throw new RemoteServiceException("存在绑定账号");
        }

        adminDeptService.removeById(id);
    }


    public void updateWebsit(AdminDeptWebsit adminDeptWebsit) {

        if (adminDeptWebsitService.lambdaQuery()
                .eq(AdminDeptWebsit::getAdminDeptId, adminDeptWebsit.getAdminDeptId())
                .eq(AdminDeptWebsit::getWebsitId, adminDeptWebsit.getWebsitId())
                .count() > 0)
            return;

        adminDeptWebsit.updateById();
    }

    public void delWebsit(String adminDeptWebsitId) {
        AdminDeptWebsit adminDeptWebsit = adminDeptWebsitService.getById(adminDeptWebsitId);

        AdminDept adminDept = adminDeptService.getById(adminDeptWebsit.getAdminDeptId());
        if (adminDept.getPId().equals("1"))
            throw new RemoteServiceException("不能删除");

        adminDeptWebsitService.removeById(adminDeptWebsitId);
    }

    public void addWebsit(String adminDeptId, List<String> websitIds) {
        AdminDept adminDept = adminDeptService.getById(adminDeptId);

        List<AdminWebsit> adminWebsits = adminWebsitService.lambdaQuery()
                .in(AdminWebsit::getWebsitId, websitIds)
                .list();

        if (adminDept.getPId().equals("1") && StringUtils.isNotBlank(adminDept.getCompanyId())) {
            final long count = adminWebsits.stream().filter(v -> !v.getCompanyId().equals(adminDept.getCompanyId())).count();
            if (count > 0) {
                throw new RemoteServiceException("不同商户的商家不能添加");
            }
        }

        for (AdminWebsit adminWebsit : adminWebsits) {
            AdminDeptWebsit adminDeptWebsit = new AdminDeptWebsit();
            adminDeptWebsit.setDeptName(adminDept.getDeptName());
            adminDeptWebsit.setAdminDeptId(adminDept.getAdminDeptId());
            adminDeptWebsit.setWebsitId(adminWebsit.getWebsitId());
            adminDeptWebsit.setWebsitName(adminWebsit.getName());

            if (adminDeptWebsitService.lambdaQuery()
                    .eq(AdminDeptWebsit::getAdminDeptId, adminDeptWebsit.getAdminDeptId())
                    .eq(AdminDeptWebsit::getWebsitId, adminWebsit.getWebsitId())
                    .count() > 0)
                continue;

            adminDeptWebsit.insert();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void importData(List<Object> datas) {

        int index = 1;

        List<AdminDeptWebsit> adminDeptWebsits = new ArrayList<>();

        List<AdminDept> adminDepts = adminDeptService.lambdaQuery().list();
        List<AdminWebsit> websitList = adminWebsitService.lambdaQuery().list();
        final Map<String, AdminWebsit> websitMap = websitList.stream().collect(Collectors.toMap(AdminWebsit::getWebsitId, Function.identity()));

        for (Object o : datas) {

            index++;
            List<Object> row = (List<Object>) o;

            if (StringUtil.isEmpty((String) row.get(1)))
                throw new RemoteServiceException("第" + index + "行,部门名称为空");

            List<AdminDept> adminDeptList = adminDepts.stream().filter(item -> item.getDeptName().equals(row.get(1))).collect(Collectors.toList());


            if (CollectionUtils.isEmpty(adminDeptList))
                throw new RemoteServiceException("第" + index + "行,部门名称找不到对应部门");

            for (AdminDept adminDept : adminDeptList) {
                final AdminWebsit websit = websitMap.get((String) row.get(0));
                // 不是平台的需要判断商家是否能放入商户下面
                if (!adminDept.getCompanyId().equals("0")
                        && !websit.getCompanyId().equals(adminDept.getCompanyId())) {
                    throw new RemoteServiceException("第" + index + "行, 商家不能添加到到对应部门");
                }
                AdminDeptWebsit adminDeptWebsit = new AdminDeptWebsit();

                adminDeptWebsit.setDeptName(adminDept.getDeptName());
                adminDeptWebsit.setAdminDeptId(adminDept.getAdminDeptId());
                adminDeptWebsit.setWebsitId((String) row.get(0));

                adminDeptWebsit.setWebsitName(websit.getName());

                adminDeptWebsitService.lambdaUpdate()
                        .eq(AdminDeptWebsit::getAdminDeptId, adminDept.getAdminDeptId())
                        .eq(AdminDeptWebsit::getWebsitId, adminDeptWebsit.getWebsitId())
                        .remove();

                adminDeptWebsits.add(adminDeptWebsit);
            }
        }

        adminDeptWebsitService.saveBatch(adminDeptWebsits);


    }
}
