package com.tuoheng.admin.service.impl;

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.RoadInformation;
import com.tuoheng.admin.entity.Section;
import com.tuoheng.admin.entity.Structure;
import com.tuoheng.admin.mapper.RoadInformationMapper;
import com.tuoheng.admin.mapper.SectionMapper;
import com.tuoheng.admin.mapper.StructureMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.query.StructureQuery;
import com.tuoheng.admin.service.IStructureService;
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.*;
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 SectionMapper sectionMapper;

    @Autowired
    private RoadInformationMapper roadInformationMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public JsonResult queryPage(StructureQuery query) {
        if(null==(query.getPage()) && null == query.getLimit()){
            throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
        }
        //数据分页
        IPage<Structure> page = new Page<>(query.getPage(),query.getLimit());

        IPage<StructureInfoVo> 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);

        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) {
//        User user = (User) ThreadLocalUtil.get();
//        if (StringUtils.isNull(user)) {
//            return JsonResult.error("获取不到用户信息");
//        }
        //获取登录信息
//        String username = SecurityUserUtils.username();
        //校验
        if(StringUtils.isEmpty(entity.getRoadId()) && StringUtils.isEmpty(entity.getSectionId())){
            return JsonResult.error("公路和路段为空");
        }
        //查询用户信息
        if(StringUtils.isEmpty(entity.getId())){
            //新增
            entity.setCreateTime(DateUtils.now());
            entity.setCreateUser("ca");
        }else {
            //更新
            entity.setUpdateTime(DateUtils.now());
            entity.setUpdateUser("ca");
        }
        super.edit(entity);

        return JsonResult.success();
    }

    /**
     * 当前登录人对应的公路所属的构造物
     * @return
     */
    @Override
    public JsonResult getSectionInfo() {
        //获取登录信息
//        String username = SecurityUserUtils.username();
//        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery()
//                .eq(User::getUsername, username).eq(User::getMark, 1));
//        if(null==user){
//            return JsonResult.error();
//        }
//        String tenantId = user.getTenantId();
        String tenantId = "0";
        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.getRoadId())){
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            RoadInformation roadInformation = roadInformationMapper.selectById(structure.getRoadId());
            if(ObjectUtil.isNotNull(roadInformation)){
                structureInfoVo.setCode(roadInformation.getCode());
            }
            //根据路段id获取路段范围
            if(StringUtils.isEmpty(structure.getSectionId())){
                throw new ServiceException(ServiceExceptionEnum.PARAMETER_IS_NULL);
            }
            Section section = sectionMapper.selectById(structure.getSectionId());
            if(ObjectUtil.isNotNull(section)){
                structureInfoVo.setSectionRange(section.getSectionRange());
            }
            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, ",");
    }
}
