package com.gxwebsoft.cms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.cms.entity.CmsDesign;
import com.gxwebsoft.cms.mapper.CmsNavigationMapper;
import com.gxwebsoft.cms.service.CmsDesignService;
import com.gxwebsoft.cms.service.CmsNavigationService;
import com.gxwebsoft.cms.entity.CmsNavigation;
import com.gxwebsoft.cms.param.CmsNavigationParam;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.service.UserService;
import org.springframework.stereotype.Service;

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

/**
 * 网站导航记录表Service实现
 *
 * @author 科技小王子
 * @since 2024-09-10 20:47:57
 */
@Service
public class CmsNavigationServiceImpl extends ServiceImpl<CmsNavigationMapper, CmsNavigation> implements CmsNavigationService {
  @Resource
  private CmsDesignService cmsDesignService;
  @Resource
  private CmsNavigationMapper cmsNavigationMapper;
  @Resource
  private UserService userService;

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

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

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

    /**
     * 配置路由生成规则
     * path：/模型/导航ID
     * component: /pages/模型/index.vue
     */
    @Override
    public void saveAsync(CmsNavigation 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";
        }
      }

      // 3.密码可见
      if(StrUtil.isNotBlank(navigation.getPassword())){
        navigation.setPassword(userService.encodePassword(navigation.getPassword()));
      }

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

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

      // TODO 2.同步添加页面
      final CmsDesign one = cmsDesignService.getOne(new LambdaQueryWrapper<CmsDesign>().eq(CmsDesign::getCategoryId, navigation.getNavigationId()).eq(CmsDesign::getDeleted, 0).last("limit 1"));
      if (ObjectUtil.isEmpty(one)) {
        final CmsDesign design = new CmsDesign();
        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());
        cmsDesignService.save(design);
      }

      // 面包屑
      final CmsNavigation 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);
      }
    }

}
