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

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.admin.AdminWebsitTree;
import com.zfire.mall.manager.bean.admin.respDto.AdminWebsitDto;
import com.zfire.mall.manager.bean.wallet.CustomerWalletBean;
import com.zfire.mall.manager.enums.SysDictEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.AdminUserWebsitRela;
import com.zfire.mall.manager.plus.entity.AdminWebsit;
import com.zfire.mall.manager.plus.entity.AdminWebsitProductTypeRela;
import com.zfire.mall.manager.plus.entity.SysDict;
import com.zfire.mall.manager.plus.service.AdminUserWebsitRelaService;
import com.zfire.mall.manager.plus.service.AdminWebsitProductTypeRelaService;
import com.zfire.mall.manager.plus.service.AdminWebsitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminWebsitLogic {

    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    AdminWebsitProductTypeRelaService adminWebsitProductTypeRelaService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    CommonLogic commonLogic;


    /**
     * 部门树
     */
    public List<AdminWebsitTree> tree(HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        AdminWebsit websit = adminWebsitService.getById(adminUser.getAdminWebsitId());
        String parentId = websit == null ? "0" : websit.getParentId();

        List<AdminWebsit> list = getAllAdminWebsit(adminUser.getAdminWebsitId());

        List<AdminWebsitTree> trees = new ArrayList<>();
        for(AdminWebsit adminWebsit : list){
            AdminWebsitTree adminWebsitTree = new AdminWebsitTree();
            BeanUtils.copyProperties(adminWebsit,adminWebsitTree);
            trees.add(adminWebsitTree);
        }

        List<AdminWebsitTree> parentList = trees.stream().filter(x -> x.getParentId().equals(parentId)).collect(Collectors.toList());
        for(AdminWebsitTree adminWebsit:parentList){
            adminWebsit.setChildren(this.treeModule(trees,adminWebsit.getAdminWebsitId(),adminWebsit.getAdminCompanyId()));
        }
        return parentList;
    }


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

        Integer count = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getName, adminWebsit.getName())
                .count();
        if(count > 0){
            throw new RemoteServiceException("部门名称已存在");
        }
        if(StringUtils.isEmpty(adminWebsit.getParentId())){
            throw new RemoteServiceException("请选择父部门");
        }
        //保存部门的业务线
        String s = this.saveWebsitProductType(adminWebsit.getMainIds(), this.getAllAdminWebsitIds(adminWebsit.getAdminWebsitId()));

        adminWebsit.setAdminCompanyId(adminUser.getAdminCompanyId());
        adminWebsit.setAdminCompanyName(adminUser.getAdminCompanyName());
        adminWebsit.setMainNames(s);
        //父级部门
        AdminWebsit parentWebsit = adminWebsitService.getById(adminWebsit.getParentId());
        if(parentWebsit != null && StringUtils.isNotEmpty(parentWebsit.getWebsitNumber())){
            adminWebsit.setWebsitNumber(parentWebsit.getWebsitNumber());
        }
        adminWebsit.insert();
    }
    /**
     * 编辑部门
     */
    @Transactional
    public void update(AdminWebsitDto adminWebsit,HttpServletRequest request) throws RemoteServiceException {
        Integer count = adminWebsitService.lambdaQuery()
                .ne(AdminWebsit::getAdminWebsitId,adminWebsit.getAdminWebsitId())
                .eq(AdminWebsit::getName, adminWebsit.getName())
                .count();
        if(count > 0){
            throw new RemoteServiceException("部门名称已存在");
        }
        if(StringUtils.isEmpty(adminWebsit.getParentId())){
            throw new RemoteServiceException("请选择父部门");
        }

        //保存部门的业务线
        String s = this.saveWebsitProductType(adminWebsit.getMainIds(), this.getAllAdminWebsitIds(adminWebsit.getAdminWebsitId()));
        adminWebsit.setMainNames(s);
        //父级部门
        List<String> allAdminWebsitIds = this.getAllAdminWebsitIds(adminWebsit.getAdminWebsitId());
        //父级部门
        AdminWebsit parentWebsit = adminWebsitService.getById(adminWebsit.getParentId());
        if(parentWebsit != null && StringUtils.isNotEmpty(parentWebsit.getWebsitNumber())){
            adminWebsit.setWebsitNumber(parentWebsit.getWebsitNumber());
            //所有我的子级也更新
            adminWebsitService.lambdaUpdate().set(AdminWebsit::getWebsitNumber,parentWebsit.getWebsitNumber()).in(AdminWebsit::getAdminWebsitId,allAdminWebsitIds).update();
        }

        adminWebsit.updateById();
    }

    /**
     * 删除部门
     */
    @Transactional
    public void delete(String adminWebsitId,HttpServletRequest request) {
        Integer count = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminWebsitId, adminWebsitId).count();
        if(count > 0){
            throw new RemoteServiceException("部门下存在帐号，不可删除");
        }
        //递归删除
        List<String> ids = this.getAllAdminWebsitIds(adminWebsitId);
        if(ids.size() > 0) {
            adminWebsitService.lambdaUpdate().in(AdminWebsit::getAdminWebsitId, ids).remove();
        }
    }


    /**
     * 根据父部门查询部门
     */
    public List<AdminWebsit> getbyParentId(String parentId){
        if(StringUtils.isEmpty(parentId)){
            parentId = "1";
        }
        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getParentId, parentId)
                .orderByDesc(AdminWebsit::getCreateTime,AdminWebsit::getAdminWebsitId)
                .list();
        return list;
    }




    private String saveWebsitProductType(List<String> mainIds,List<String> adminWebsitIds){
        if(CollectionUtils.isEmpty(mainIds)){
            return "";
        }
        Map<String, String> productTypeMap = commonLogic.getProductTypeMap();
        //1.先删除旧的部门业务线
        if(adminWebsitIds.size() > 0 ) {
            adminWebsitProductTypeRelaService.lambdaUpdate().in(AdminWebsitProductTypeRela::getAdminWebsitId, adminWebsitIds).remove();
        }
        //2.保存新的部门业务线
        List<AdminWebsitProductTypeRela> relas = new ArrayList<>();
        String mainNames = "";
        for(String mainId : mainIds){
            String mainName = productTypeMap.get(mainId);
            for(String adminWebsitId : adminWebsitIds){
                AdminWebsitProductTypeRela rela = new AdminWebsitProductTypeRela();
                rela.setAdminWebsitId(adminWebsitId);
                rela.setMainId(mainId);
                rela.setMainName(mainName);
                relas.add(rela);
            }
            mainNames += mainName+"，";
        }
        adminWebsitProductTypeRelaService.saveBatch(relas);
        if(mainNames.length() > 0){
            return mainNames.substring(0,mainNames.length() - 1);
        }
        return "";
    }


    /**
     * 详情
     * @param id
     */
    public AdminWebsitDto detail(String id){
        AdminWebsit adminWebsit = adminWebsitService.getById(id);

        AdminWebsitDto adminWebsitDto = new AdminWebsitDto();
        BeanUtils.copyProperties(adminWebsit,adminWebsitDto);

        //查询业务线ids
//        List<AdminWebsitProductTypeRela> list = adminWebsitProductTypeRelaService.lambdaQuery()
//                .eq(AdminWebsitProductTypeRela::getAdminWebsitId, id).list();
//        List<String> mainIds = list.stream().map(AdminWebsitProductTypeRela::getMainId).collect(Collectors.toList());
//        adminWebsitDto.setMainIds(mainIds);
        return adminWebsitDto;
    }


    /**
     * 查询部门以及部门下面所有的 部门id
     */
    public List<String> getAllAdminWebsitIds(String adminWebsitId){
        List<AdminWebsit> allAdminWebsits = this.getAllAdminWebsit(adminWebsitId);
        List<String> adminWebsitIds = allAdminWebsits.stream().map(AdminWebsit::getAdminWebsitId).collect(Collectors.toList());
        return adminWebsitIds;
    }

    /**
     * 查询部门以及部门下面所有的部门
     */
    public List<AdminWebsit> getAllAdminWebsit(String adminWebsitId){
        List<AdminWebsit> all = adminWebsitService.list();

        if(StringUtils.isNotEmpty(adminWebsitId)) {
            List<AdminWebsit> adminWebsits = new ArrayList<>();
            this.queryAllChild(adminWebsits,all, adminWebsitId);

            adminWebsits.add(adminWebsitService.getById(adminWebsitId));
            return adminWebsits;
        }
        return new ArrayList<>();
    }


    /**
     * 递归查询所有数据
     */
    public List<AdminWebsit> queryAllChild(List<AdminWebsit> adminWebsits,List<AdminWebsit> list,String parentId){
        //最父级资源树
        if(parentId == null) {
            return adminWebsits;
        }
        List<AdminWebsit> collect = list.stream()
                .filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        if(collect.size() == 0){
            return adminWebsits;
        }
        adminWebsits.addAll(collect);
        for(AdminWebsit bean : collect){
            this.queryAllChild(adminWebsits,list, bean.getAdminWebsitId());
        }
        return adminWebsits;
    }

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





}
