/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 运维系统
 * 创建日期:2022/8/22
 */
package org.springblade.modules.baseinfo.region.whole.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.etl.EtlRegionDataTask;
import org.springblade.etl.entity.EtlAdCdEntity;
import org.springblade.etl.service.IEtlAdCdService;
import org.springblade.jobtask.TaskManager;
import org.springblade.modules.baseinfo.org.entity.DeptRegionEntity;
import org.springblade.modules.baseinfo.org.service.IDeptRegionService;
import org.springblade.modules.baseinfo.region.tree.entity.RegionTreeNodeEntity;
import org.springblade.modules.baseinfo.region.whole.entity.BaseRegionInfoEntity;
import org.springblade.modules.baseinfo.region.whole.service.IBaseRegionInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.FutureTask;


/***
 * Date:2022/8/22
 * Title:行政区划管理
 * Description：包括内蒙所有行政区划
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@Slf4j
@RequestMapping("galaxy-business/baseinfo/region/whole")
@RequiredArgsConstructor
@Api(value = "行政区划管理", tags = "行政区划管理")
public class BaseRegionController extends BladeController {
    private final IEtlAdCdService etlAdCdService;
    private final IBaseRegionInfoService baseRegionInfoService;
    private final IDeptRegionService deptRegionService;
    @Resource
    private TaskManager taskManager;


    @GetMapping("/list")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "")
    public R<List<BaseRegionInfoEntity>> getList(BaseRegionInfoEntity entity) {
        BladeUser user = AuthUtil.getUser();
        LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper = Wrappers.<BaseRegionInfoEntity>query().lambda();
        if (Func.isNull(entity.getParentCode())) {
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                queryWrapper.eq(BaseRegionInfoEntity::getParentCode, BusinessConstant.REGION_NM_ADCODE);
            } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getParentCode,deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_YJ_SERVICE_PERSON.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getParentCode,deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_QI_ADMIN.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getParentCode,deptRegionEntity.getAdcd());
            }else{
                return R.fail("查询失败");
            }
        } else {
            queryWrapper.eq(BaseRegionInfoEntity::getParentCode, entity.getParentCode());
        }
        List<BaseRegionInfoEntity> list = baseRegionInfoService.list(queryWrapper);
        return R.data(list);
    }


    @GetMapping("/yj/list")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "")
    public R<List<BaseRegionInfoEntity>> getYjList(BaseRegionInfoEntity entity) {
        BladeUser user = AuthUtil.getUser();
        LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper = Wrappers.<BaseRegionInfoEntity>query().lambda();
        if (Func.isNull(entity.getParentCode())) {
            if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
                queryWrapper.eq(BaseRegionInfoEntity::getParentCode, BusinessConstant.REGION_NM_ADCODE);
            } else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getAdcd,deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_YJ_SERVICE_PERSON.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getAdcd,deptRegionEntity.getAdcd());
            }else if(BusinessConstant.ROLE_QI_ADMIN.equals(user.getRoleName())){
                LambdaQueryWrapper<DeptRegionEntity> wrapper = Wrappers.<DeptRegionEntity>query().lambda();
                wrapper.eq(DeptRegionEntity::getDeptId, Func.toLong(user.getDeptId()));
                wrapper.last("limit 1");
                DeptRegionEntity deptRegionEntity = deptRegionService.getOne(wrapper);
                if (Func.isNull(deptRegionEntity)){
                    return R.fail("查询失败");
                }
                queryWrapper.eq(BaseRegionInfoEntity::getAdcd,deptRegionEntity.getAdcd());
            }else{
                return R.fail("查询失败");
            }
        } else {
            queryWrapper.eq(BaseRegionInfoEntity::getParentCode, entity.getParentCode());
        }
        List<BaseRegionInfoEntity> list = baseRegionInfoService.list(queryWrapper);
        return R.data(list);
    }

    /**
     * 懒加载
     *
     * @param entity
     * @return
     */
    @GetMapping("/lazy-tree")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "树")
    public R<List<RegionTreeNodeEntity>> lazyTree(BaseRegionInfoEntity entity) {
        if (Func.isNull(entity.getParentCode())) {
            return R.fail("参数错误");
        }
        List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
        LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper = Wrappers.<BaseRegionInfoEntity>query().lambda();
        queryWrapper.eq(BaseRegionInfoEntity::getParentCode, entity.getParentCode());
        List<BaseRegionInfoEntity> list = baseRegionInfoService.list(queryWrapper);
        for (BaseRegionInfoEntity regionInfoEntity : list) {
            RegionTreeNodeEntity node = new RegionTreeNodeEntity();
            node.setId(regionInfoEntity.getAdcd());
            node.setValue(regionInfoEntity.getAdcd());
            node.setTitle(regionInfoEntity.getAdnm());
            node.setText(regionInfoEntity.getAdnm());
            node.setKey(regionInfoEntity.getAdcd());
            node.setParentId(regionInfoEntity.getParentCode());
            LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper2 = Wrappers.<BaseRegionInfoEntity>query().lambda();
            queryWrapper2.eq(BaseRegionInfoEntity::getParentCode, regionInfoEntity.getAdcd());
            long count = baseRegionInfoService.count(queryWrapper2);
            if (count > 0) {
                node.setHasChildren(true);
            } else {
                node.setHasChildren(false);
            }
            nodeEntities.add(node);
        }
        return R.data(nodeEntities);
    }

    /**
     * 加载树
     *
     * @return
     */
    @GetMapping("/tree")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "树")
    public R<List<RegionTreeNodeEntity>> tree() {
        List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
        //根节点
        LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper = Wrappers.<BaseRegionInfoEntity>query().lambda();
        queryWrapper.eq(BaseRegionInfoEntity::getAdcd, BusinessConstant.REGION_NM_ADCODE);
        BaseRegionInfoEntity nmRegion = baseRegionInfoService.getOne(queryWrapper);
        RegionTreeNodeEntity nmEntity = new RegionTreeNodeEntity();
        nmEntity.setId(nmRegion.getAdcd());
        nmEntity.setValue(nmRegion.getAdcd());
        nmEntity.setTitle(nmRegion.getAdnm());
        nmEntity.setText(nmRegion.getAdnm());
        nmEntity.setKey(nmRegion.getAdcd());
        nmEntity.setParentId(nmRegion.getParentCode());
        //查找子节点
        if (getChildren(nmEntity, nmRegion)) {
            if (nmEntity.getChildren() != null && nmEntity.getChildren().size() > 0) {
                nmEntity.setHasChildren(true);
            } else {
                nmEntity.setHasChildren(false);
            }
        }
        nodeEntities.add(nmEntity);
        return R.data(nodeEntities);
    }

    private boolean getChildren(RegionTreeNodeEntity nodeEntity, BaseRegionInfoEntity regionInfoEntity) {
        LambdaQueryWrapper<BaseRegionInfoEntity> queryWrapper = Wrappers.<BaseRegionInfoEntity>query().lambda();
        queryWrapper.eq(BaseRegionInfoEntity::getParentCode, regionInfoEntity.getAdcd());
        List<BaseRegionInfoEntity> list = baseRegionInfoService.list(queryWrapper);
        if (null != list && list.size() > 0) {
            List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
            for (BaseRegionInfoEntity entity : list) {
                RegionTreeNodeEntity node = new RegionTreeNodeEntity();
                node.setId(entity.getAdcd());
                node.setValue(entity.getAdcd());
                node.setTitle(entity.getAdnm());
                node.setText(entity.getAdnm());
                node.setKey(entity.getAdcd());
                node.setParentId(entity.getParentCode());
                if (getChildren(node, entity)) {
                    if (node.getChildren() != null && node.getChildren().size() > 0) {
                        node.setHasChildren(true);
                    } else {
                        node.setHasChildren(false);
                    }
                }
                nodeEntities.add(node);
            }
            nodeEntity.setChildren(nodeEntities);
        }
        return true;
    }

    @GetMapping("/create/region")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "", notes = "")
    public R createRegion() {
        EtlRegionDataTask task = new EtlRegionDataTask(etlAdCdService, baseRegionInfoService);
        FutureTask<Integer> futureTask = new FutureTask<>(task);
        taskManager.submitTask(futureTask);
        return R.success("ok");
    }

    private void crateChildRegion(BaseRegionInfoEntity root, String ancestors) {
        EtlAdCdEntity etlAdCdEntity = new EtlAdCdEntity();
        etlAdCdEntity.setSuperioradcd(root.getAdcd());
        List<EtlAdCdEntity> list = etlAdCdService.selectList(etlAdCdEntity);
        for (EtlAdCdEntity entity : list) {
            BaseRegionInfoEntity baseRegionInfoEntity = new BaseRegionInfoEntity();
            baseRegionInfoEntity.setAdcd(entity.getAdcd());
            baseRegionInfoEntity.setAdnm(entity.getAdnm());
            baseRegionInfoEntity.setParentCode(root.getAdcd());
            baseRegionInfoEntity.setAncestors(ancestors + "," + root.getAdcd());
            baseRegionInfoEntity.setAddType(entity.getAddtype());
            baseRegionInfoEntity.setLgtd(entity.getLgtd());
            baseRegionInfoEntity.setLttd(entity.getLttd());
            baseRegionInfoService.save(baseRegionInfoEntity);
            crateChildRegion(baseRegionInfoEntity, baseRegionInfoEntity.getAncestors());
        }
    }

}
