package com.gxwebsoft.cms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.cms.entity.Design;
import com.gxwebsoft.cms.mapper.NavigationMapper;
import com.gxwebsoft.cms.service.DesignService;
import com.gxwebsoft.cms.service.NavigationService;
import com.gxwebsoft.cms.entity.Navigation;
import com.gxwebsoft.cms.param.NavigationParam;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;
import java.util.UUID;

/**
 * 导航Service实现
 *
 * @author 科技小王子
 * @since 2024-03-04 21:27:55
 */
@Service
public class NavigationServiceImpl extends ServiceImpl<NavigationMapper, Navigation> implements NavigationService {
    @Resource
    private DesignService designService;
    @Resource
    private NavigationMapper navigationMapper;

    @Override
    public PageResult<Navigation> pageRel(NavigationParam param) {
        PageParam<Navigation, NavigationParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc,navigation_id asc");
        List<Navigation> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Navigation> listRel(NavigationParam param) {
        List<Navigation> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Navigation, NavigationParam> page = new PageParam<>();
        page.setDefaultOrder("top asc,sort_number asc,navigation_id asc");
        return page.sortRecords(list);
    }

    @Override
    public Navigation getByIdRel(Integer navigationId) {
        NavigationParam param = new NavigationParam();
        param.setNavigationId(navigationId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    /**
     * 配置路由生成规则
     * path：/模型/导航ID
     * component: /pages/模型/index.vue
     */
    @Override
    public void saveAsync(Navigation navigation) {
      // TODO 1.设计path和component生产规则
      String path = "";
      String component = "";

      // 1.手动配置优先
      if (StrUtil.isNotBlank(navigation.getPath())) {
        component = navigation.getComponent();
        path = navigation.getPath();
        path = StrUtil.trimStart(path);  //去除字符串前面的空格
        path = path.replace(" ", "-");  //把空格转为横杆
        if (!navigation.getModel().equals("links")) {
          final char charAt = path.charAt(0);
          if (charAt != '/' && charAt != '#') {
            path = "/".concat(path);
          }
        }

        if (path.equals("/")) {
          component = "/pages/index.vue"; // 指定首页组件路径
          navigation.setHome(1);
        }
      }

      // 2.自动配置
      if (StrUtil.isBlank(navigation.getPath())) {
        path = MessageFormat.format("/{0}/{1}", navigation.getModel() , navigation.getNavigationId());
        component = MessageFormat.format("/pages/{0}/{1}", navigation.getModel(), "index.vue");
        // 通用模型
        if (navigation.getModel().equals("custom")) {
          path = MessageFormat.format("/{0}-{1}",navigation.getModel(), navigation.getNavigationId());
          component = "/pages/[custom]/index.vue";
        }
      }

      // 更新
      navigation.setPath(path);
      navigation.setComponent(component);
      updateById(navigation);

      // 查重
      final int count = count(new LambdaQueryWrapper<Navigation>().eq(Navigation::getPath, path));
      if(count > 1){
        throw new BusinessException("路由地址(" + path + ")已存在！");
      }

      // TODO 2.同步添加页面
      final Design one = designService.getOne(new LambdaQueryWrapper<Design>().eq(Design::getCategoryId, navigation.getNavigationId()).eq(Design::getDeleted, 0).last("limit 1"));
      if (ObjectUtil.isEmpty(one)) {
        final Design design = new Design();
        design.setName(navigation.getTitle());
        design.setCategoryId(navigation.getNavigationId());
        design.setKeywords(navigation.getTitle());
        design.setDescription(navigation.getComments());
        design.setPath(navigation.getPath());
        design.setComponent(navigation.getComponent());
        design.setTenantId(navigation.getTenantId());
        designService.save(design);
      }

      // 面包屑
      final Navigation parent = getById(navigation.getParentId());
      if (ObjectUtil.isNotEmpty(parent) && navigation.getParentId() > 0) {
        navigation.setParentName(parent.getTitle());
        navigation.setParentPath(parent.getPath());
        navigation.setParentId(parent.getNavigationId());
        updateById(parent);
      }
    }
}
