/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.basic.info.modular.unitInfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.auth.core.util.StpClientUtil;
import com.unis.auth.modular.login.entity.UserCollectLogin;
import com.unis.basic.info.modular.grainPriceCollectCategory.entity.GrainPriceCollectCategory;
import com.unis.basic.info.modular.grainPriceCollectCitySum.entity.GrainPriceCollectCitySum;
import com.unis.basic.info.modular.unitInfo.entity.BasicEnum;
import com.unis.basic.info.modular.unitInfo.entity.BasicEnumExample;
import com.unis.basic.info.modular.unitInfo.mapper.EnumMapper;
import com.unis.basic.info.modular.unitInfo.vo.BasicEnumVo;
import com.unis.common.pojo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.basic.info.modular.unitInfo.entity.UnitInfo;
import com.unis.basic.info.modular.unitInfo.mapper.UnitInfoMapper;
import com.unis.basic.info.modular.unitInfo.param.UnitInfoAddParam;
import com.unis.basic.info.modular.unitInfo.param.UnitInfoEditParam;
import com.unis.basic.info.modular.unitInfo.param.UnitInfoIdParam;
import com.unis.basic.info.modular.unitInfo.param.UnitInfoPageParam;
import com.unis.basic.info.modular.unitInfo.service.UnitInfoService;

import java.util.*;

/**
 * 单位信息表Service接口实现类
 *
 * @author hujinachun
 * @date 2024/04/16 09:08
 **/
@Slf4j
@Service
public class UnitInfoServiceImpl extends ServiceImpl<UnitInfoMapper, UnitInfo> implements UnitInfoService {


    @Autowired
    private UnitInfoMapper unitInfoMapper;

    @Autowired
    private EnumMapper enumMapper;


    @Override
    public Page<UnitInfo> page(UnitInfoPageParam pageParam) {
        QueryWrapper<UnitInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageParam.getDwmc())) {
            queryWrapper.like("dwmc", pageParam.getDwmc());
        }
        if (StringUtils.isNotBlank(pageParam.getFddbr())) {
            queryWrapper.like("fddbr", pageParam.getFddbr());
        }
        if (ObjectUtil.isAllNotEmpty(pageParam.getSortField(), pageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(pageParam.getSortOrder());
            queryWrapper.orderBy(true, pageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(pageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(UnitInfo::getCreateTime);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    /**
     * @author: hujianchun
     * @Description:
     * @param:
     * @return: 添加企业信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(UnitInfoAddParam unitInfoAddParam) {
       /* UnitInfo unitInfo = BeanUtil.toBean(unitInfoAddParam, UnitInfo.class);
        this.save(unitInfo);*/
        List<UnitInfo> unitInfos = unitInfoMapper.selectList(Wrappers.
                lambdaQuery(UnitInfo.class).
                eq(UnitInfo::getDwdm, unitInfoAddParam.getDwdm()));
        if (!CollectionUtils.isEmpty(unitInfos)) {
            throw new CommonException("单位统一社会信用代码重复，请重新输入");
        }
        List<UnitInfo> unitInfoList = unitInfoMapper.selectList(Wrappers.lambdaQuery(UnitInfo.class).eq(UnitInfo::getDwmc, unitInfoAddParam.getDwmc()));
        if (!CollectionUtils.isEmpty(unitInfoList)) {
            throw new CommonException("单位名称重复，请重新输入");
        }
        if (unitInfoAddParam.getDwdm().length() != 18 && StringUtils.isNotEmpty(unitInfoAddParam.getDwdm())) {
            throw new CommonException("统一社会信用代码输入错误,请输入18位编码");
        }
       /* if (unitInfoAddParam.getSjdwdm().length() != 18 && StringUtils.isNotEmpty(unitInfoAddParam.getSjdwdm())){
            throw new CommonException("上级单位代码代码输入错误,请输入18位编码");
        }*/
        if (unitInfoAddParam.getTydwbm().length() != 18 && StringUtils.isNotEmpty(unitInfoAddParam.getTydwbm())) {
            throw new CommonException("统一单位编码输入错误,请输入18位编码");
        }
        if (unitInfoAddParam.getFrsfzh().length() != 18) {
            throw new CommonException("身份证号输入错误");
        }
        if (unitInfoAddParam.getXzqhdm().length() != 6) {
            throw new CommonException("行政区划代码输入错误");
        }

        //获取省级id
        String areaId = unitInfoAddParam.getZcdzArea();
        //获取子类记录
        BasicEnum basicEnum = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                .eq(BasicEnum::getId, areaId));
        if (ObjectUtil.isEmpty(basicEnum)) {
            throw new CommonException("所在地区不存在");
        }

        String momNode = this.getMomNode(basicEnum.getId(), basicEnum.getDictLabel());

        UnitInfo unitInfo = new UnitInfo();
        BeanUtils.copyProperties(unitInfoAddParam, unitInfo);
        unitInfo.setZhgxsj(new Date());
        unitInfo.setCreateTime(new Date());
        unitInfo.setCzbz("i");
        unitInfo.setZcdz(momNode);
        try {
            unitInfoMapper.insert(unitInfo);
        } catch (Exception e) {
            log.error("单位管理信息新增操作数据库失败:[{}]", e.getMessage());
            throw new CommonException("单位管理信息新增操作数据库失败");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(UnitInfoEditParam unitInfoEditParam) {
       /* UnitInfo unitInfo = this.queryEntity(unitInfoEditParam.getId());
        BeanUtil.copyProperties(unitInfoEditParam, unitInfo);
        this.updateById(unitInfo);*/
        List<UnitInfo> unitInfos = unitInfoMapper.selectList(Wrappers.lambdaQuery(UnitInfo.class)
                .eq(UnitInfo::getDwdm, unitInfoEditParam.getDwdm()));
        if (!CollectionUtils.isEmpty(unitInfos)) {
            throw new CommonException("单位统一社会信用代码重复，请重新输入");
        }
        List<UnitInfo> unitInfoList = unitInfoMapper.selectList(Wrappers.lambdaQuery(UnitInfo.class)
                .eq(UnitInfo::getDwmc, unitInfoEditParam.getDwmc()));
        if (!CollectionUtils.isEmpty(unitInfoList)) {
            throw new CommonException("单位名称重复，请重新输入");
        }
        //获取地区id
        String areaId = unitInfoEditParam.getZcdzArea();
        String momNode = null;
        if (StringUtils.isNotEmpty(areaId)) {
            //获取子类记录
            BasicEnum basicEnum = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                    .eq(BasicEnum::getId, areaId));
            if (ObjectUtil.isEmpty(basicEnum)) {
                throw new CommonException("所在地区不存在");
            }
            momNode = this.getMomNode(basicEnum.getId(), basicEnum.getDictLabel());
        }

        String zcdzCityId = unitInfoEditParam.getZcdzCity();
        String provinceId = unitInfoEditParam.getZcdzProvince();
        if (StringUtils.isNotEmpty(zcdzCityId) && StringUtils.isNotEmpty(provinceId)) {
            //获取子类记录
            BasicEnum basicEnum = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                    .eq(BasicEnum::getId, zcdzCityId));
            if (ObjectUtil.isEmpty(basicEnum)) {
                throw new CommonException("所在地区不存在");
            }
            momNode = this.getMomNode(basicEnum.getId(), basicEnum.getDictLabel());
        }

        if (StringUtils.isNotEmpty(provinceId) && StringUtils.isEmpty(areaId) && StringUtils.isEmpty(zcdzCityId)) {
            //获取子类记录
            BasicEnum basicEnum = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                    .eq(BasicEnum::getId, provinceId));
            if (ObjectUtil.isEmpty(basicEnum)) {
                throw new CommonException("所在地区不存在");
            }
            momNode = this.getMomNode(basicEnum.getId(), basicEnum.getDictLabel());
        }

        UnitInfo unitInfo = new UnitInfo();
        BeanUtils.copyProperties(unitInfoEditParam, unitInfo);
        unitInfo.setCzbz("u");
        unitInfo.setId(unitInfoEditParam.getId());
        unitInfo.setUpdateTime(new Date());
        unitInfo.setZhgxsj(new Date());
        unitInfo.setZcdz(momNode);
        try {
            unitInfoMapper.updateById(unitInfo);
        } catch (Exception e) {
            log.error("单位管理信息修改操作数据库失败异常信息[{}],id:[{}]", e.getMessage(), unitInfoEditParam.getId());
            throw new CommonException("单位管理信息新增操作数据库失败");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<UnitInfoIdParam> unitInfoIdParamList) {

        // 执行删除
        this.removeByIds(CollStreamUtil.toList(unitInfoIdParamList, UnitInfoIdParam::getId));

    }

    @Override
    public UnitInfo detail(UnitInfoIdParam unitInfoIdParam) {
        return this.queryEntity(unitInfoIdParam.getId());
    }

    @Override
    public UnitInfo queryEntity(String id) {
        UnitInfo unitInfo = this.getById(id);
        if (ObjectUtil.isEmpty(unitInfo)) {
            throw new CommonException("单位信息表不存在，id值为：{}", id);
        }
        return unitInfo;
    }

    //获取对应站点信息
    @Override
    public List<BasicEnumVo> queryAllChildren(String enumid, boolean isQueryFristNode) {
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.eq("PARENT_ID", enumid);
        basicEnumQueryWrapper.select().orderByAsc("SORT_CODE");
        List<BasicEnum> basicEnums = enumMapper.selectList(basicEnumQueryWrapper);
        List<BasicEnumVo> basicEnumVos = new ArrayList<>();
        if (!isQueryFristNode) {
            if (CollectionUtils.isEmpty(basicEnums)) {
                log.info("未找到下级子目录");
                BasicEnumVo basicEnumVo = new BasicEnumVo();
                basicEnumVo.setSign(true);
                basicEnumVos.add(basicEnumVo);
                return basicEnumVos;
            }
            for (BasicEnum basicEnum : basicEnums) {
                List<BasicEnumVo> children = this.getChildren(basicEnum);
                BasicEnumVo anEnum = new BasicEnumVo();
                BeanUtils.copyProperties(basicEnum, anEnum);
                if (CollectionUtils.isEmpty(children)) {
                    log.info("该子目录为空");
                    basicEnumVos.add(anEnum);
                    continue;
                }
                anEnum.setChildren(children);
                basicEnumVos.add(anEnum);
            }
        } else {
            for (BasicEnum basicEnum : basicEnums) {
                BasicEnumVo basicEnumVo = new BasicEnumVo();
                BeanUtils.copyProperties(basicEnum, basicEnumVo);
                basicEnumVos.add(basicEnumVo);
            }
        }

        return basicEnumVos;
    }


    private List<BasicEnumVo> getChildren(BasicEnum node) {
        String parendId = node.getId(); //做为父级id
        QueryWrapper<BasicEnum> basicEnumQueryWrapper = new QueryWrapper<>();
        basicEnumQueryWrapper.eq("PARENT_ID", parendId);
        basicEnumQueryWrapper.select().orderByDesc("PARENT_ID").orderByAsc("CATEGORY");
        List<BasicEnum> list = enumMapper.selectList(basicEnumQueryWrapper); //查询到所有正常数据
        List<BasicEnumVo> basicEnumVos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                BasicEnum node_ = list.get(i);
                List<BasicEnumVo> childrenList = this.getChildren(node_);
//                if (CollectionUtils.isEmpty(childrenList)) {
//                    continue; //表明没有下级了，跳出当前循环
//                }
                BasicEnumVo anEnum = new BasicEnumVo();
                BeanUtils.copyProperties(node_, anEnum);
                anEnum.setChildren(childrenList);
                basicEnumVos.add(anEnum);
            }
        }
        return basicEnumVos;
    }


    //获取父类id
    private String getMomNode(String id, String addrName) {
        //获取子类记录
        BasicEnum anEnum = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                .eq(BasicEnum::getId, id));

        if ("1781533421287342082".equals(anEnum.getParentId())) {
            return addrName;
        }

        //获取父类记录
        String parentId = anEnum.getParentId();
        BasicEnum upNode = enumMapper.selectOne(new LambdaQueryWrapper<BasicEnum>()
                .eq(BasicEnum::getId, parentId));

        addrName = upNode.getDictLabel() + addrName;
        return this.getMomNode(parentId, addrName);
    }


}
