package com.tuoheng.admin.service.structure;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.DataPermissionEnum;
import com.tuoheng.admin.enums.LegEnum;
import com.tuoheng.admin.enums.StructureEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.StructureQuery;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.StructureInfoVo;
import com.tuoheng.common.core.common.BaseServiceImpl;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.enums.ServiceExceptionEnum;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.CommonUtils;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/11/17
 */
@Service
public class StructureServiceImpl extends BaseServiceImpl<StructureMapper, Structure> implements IStructureService {

    @Autowired
    private StructureMapper structureMapper;

    @Autowired
    private LegMapper legMapper;

    @Autowired
    private ChannelMapper channelMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private LegDeptMapper legDeptMapper;

    @Override
    public JsonResult queryPage(StructureQuery query) {
        if (null == (query.getPage()) && null == query.getLimit()) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //获取登录信息
        User user = CurrentUserUtil.getUserInfo();
        if (ObjectUtil.isNull(user)) {
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //租户id
        String tenantId = user.getTenantId();
        query.setTenantId(tenantId);

        //获取用户角色
        Integer type = user.getDataPermission();
        IPage<Structure> page = new Page<>(query.getPage(), query.getLimit());
        IPage<StructureInfoVo> pageData = null;
        //如果是超级管理员，查看所有构造物
        if (DataPermissionEnum.ALL.getCode() == type) {
            //数据分页
            pageData = structureMapper.queryPage(page, query);
            List<StructureInfoVo> list = pageData.getRecords().stream().map((item) -> {
                StructureInfoVo structureInfoVo = new StructureInfoVo();
                BeanUtils.copyProperties(item, structureInfoVo);
                //获取构造物图片，对图片进行处理
                if (StringUtils.isNotEmpty(item.getImageUrl())) {
                    String[] imageUrls = item.getImageUrl().split(",");
                    if (StringUtils.isNotEmpty(imageUrls)) {
                        for (int i = 0; i < imageUrls.length; i++) {
                            if (StringUtils.isNotEmpty(imageUrls[i])) {
                                imageUrls[i] = CommonConfig.imageURL + imageUrls[i];
                            }
                        }
                    }
                    structureInfoVo.setImageUrl(StringUtils.join(imageUrls, ","));
                }
//            if (StringUtils.isNotEmpty(item.getImageUrl())) {
//                String imageUrl = getMultipleUrl(item.getImageUrl());
//                structureInfoVo.setImageUrl(imageUrl);
//            }
                return structureInfoVo;
            }).collect(Collectors.toList());
            pageData.setRecords(list);

        }
        //如果是部门管理员或普通用户，查询本部门及子部门包含的航段及航段对应的构造物
        if (DataPermissionEnum.DEPT_AND_SUB_DEPT.getCode() == type || DataPermissionEnum.DEPT.getCode() == type) {
            String deptId = user.getDeptId();
            if (StringUtils.isEmpty(deptId)) {
                return JsonResult.error(StructureEnum.DEPT_IS_NOT_EXIST.getCode(), StructureEnum.DEPT_IS_NOT_EXIST.getMsg());
            }
            //获取当前登录用户对应的部门及子部门
            List<String> deptList = deptMapper.selectAllChildListById(deptId);
            if (StringUtils.isEmpty(deptList) && deptList.size() <= 0) {
                return JsonResult.error(LegEnum.DEPT_ID_IS_NULL.getCode(), LegEnum.DEPT_ID_IS_NULL.getMsg());
            }
            //根据部门列表查对应的部门航段数据列表
            List<LegDept> legDeptList = legDeptMapper.selectList(Wrappers.<LegDept>lambdaQuery()
                    .eq(LegDept::getTenantId, tenantId)
                    .in(LegDept::getDeptId, deptList));
            if (StringUtils.isEmpty(legDeptList) && legDeptList.size() <= 0) {
                return JsonResult.error(LegEnum.DEPT_SECTION_IS_NOT_EXIST.getCode(), LegEnum.DEPT_SECTION_IS_NOT_EXIST.getMsg());
            }
            //查询对应的航段列表
            List<String> legIdList = legDeptList.stream().map(t -> t.getLegId()).distinct().collect(Collectors.toList());
            if (StringUtils.isEmpty(legIdList)) {
                return JsonResult.error(LegEnum.SECTION_ID_IS_NULL.getCode(), LegEnum.SECTION_ID_IS_NULL.getMsg());
            }
            List<StructureInfoVo> list = new ArrayList<>();
            //根据航段id查询对应的构造物列表
            for (String legId : legIdList) {
                query.setLegId(legId);
                pageData = structureMapper.queryPageBySectionId(page, query);
                List<StructureInfoVo> records = pageData.getRecords();
                for (StructureInfoVo record : records) {
                    //获取构造物图片，对图片进行处理
                    if (StringUtils.isNotEmpty(record.getImageUrl())) {
                        String[] imageUrls = record.getImageUrl().split(",");
                        if (StringUtils.isNotEmpty(imageUrls)) {
                            for (int i = 0; i < imageUrls.length; i++) {
                                if (StringUtils.isNotEmpty(imageUrls[i])) {
                                    imageUrls[i] = CommonConfig.imageURL + imageUrls[i];
                                }
                            }
                        }
                        record.setImageUrl(StringUtils.join(imageUrls, ","));
                    }
                    list.add(record);
                }
            }
            pageData.setRecords(list);
        }


        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult getListInfo(StructureQuery query) {
        List<Structure> structureList = structureMapper.selectList(new LambdaQueryWrapper<Structure>()
                .eq(Structure::getMark, 1)
                .orderByDesc(Structure::getCreateTime));

        return JsonResult.success(structureList);
    }

    @Override
    public JsonResult editInfo(Structure entity) {
        //获取登录信息
        String userId = CurrentUserUtil.getUserId();
        if (StringUtils.isEmpty(userId)) {
            return JsonResult.error(StructureEnum.USER_ID_IS_NULL.getCode(), StructureEnum.USER_ID_IS_NULL.getMsg());
        }

        //校验
        if (StringUtils.isEmpty(entity.getChannelId()) && StringUtils.isEmpty(entity.getLegId())) {
            return JsonResult.error("航道和航段为空");
        }
        //获取租户id
        String tenantId = CurrentUserUtil.getTenantId();
        //查询用户信息
        if (StringUtils.isEmpty(entity.getId())) {
            //新增
            entity.setCreateTime(DateUtils.now());
            entity.setCreateUser(userId);
            entity.setTenantId(tenantId);
        } else {
            //更新
            entity.setUpdateTime(DateUtils.now());
            entity.setUpdateUser(userId);
            entity.setTenantId(tenantId);
        }
        super.edit(entity);

        return JsonResult.success();
    }

    /**
     * 当前登录人对应的航道所属的构造物
     *
     * @return
     */
    @Override
    public JsonResult getSectionInfo() {
        //获取登录信息
        String tenantId = CurrentUserUtil.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            JsonResult.error(StructureEnum.TENANT_ID_IS_NULL.getCode(), StructureEnum.TENANT_ID_IS_NULL.getMsg());
        }
        List<Structure> structures = structureMapper.selectList(Wrappers.<Structure>lambdaQuery().eq(Structure::getMark, 1)
                .eq(Structure::getTenantId, tenantId));
        if (null == structures) {
            return JsonResult.error();
        }
        List<StructureInfoVo> list = new ArrayList<>();
        for (Structure structure : structures) {
            StructureInfoVo structureInfoVo = new StructureInfoVo();
            BeanUtils.copyProperties(structure, structureInfoVo);
            //设置图片
            if (StringUtils.isNotEmpty(structure.getImageUrl())) {
                String[] imageUrls = structure.getImageUrl().split(",");
                if (StringUtils.isNotEmpty(imageUrls)) {
                    for (int i = 0; i < imageUrls.length; i++) {
                        if (StringUtils.isNotEmpty(imageUrls[i])) {
                            imageUrls[i] = CommonConfig.imageURL + imageUrls[i];
                        }
                    }
                }
                structureInfoVo.setImageUrl(StringUtils.join(imageUrls, ","));
            }
            //根据航道id获取航道code
            if (StringUtils.isEmpty(structure.getChannelId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            Channel channel = channelMapper.selectById(structure.getChannelId());
            if (ObjectUtil.isNotNull(channel)) {
                structureInfoVo.setCode(channel.getCode());
            }
            //根据航段id获取航段范围
            if (StringUtils.isEmpty(structure.getLegId())) {
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            Leg leg = legMapper.selectById(structure.getLegId());
            if (ObjectUtil.isNotNull(leg)) {
                structureInfoVo.setLegRange(leg.getLegRange());
            }
            list.add(structureInfoVo);
        }

        return JsonResult.success(list);
    }


    /**
     * 多个url进行转换,用,号隔开
     *
     * @param url
     * @return
     */
    private String getMultipleUrl(String url) {

        List<String> collect = Arrays.asList(url.split(",")).stream().map(
                s -> CommonUtils.getImageURL(s)).collect(Collectors.toList());
        //返回
        return org.apache.commons.lang3.StringUtils.join(collect, ",");
    }
}
