package com.microservices.zone.detail.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.PageUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
import com.microservices.common.httpClient.util.GitLinkRequestHelper;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.system.api.RemoteDeptService;
import com.microservices.zone.detail.domain.ZoneApplication;
import com.microservices.zone.detail.domain.ZoneDetail;
import com.microservices.zone.detail.domain.vo.ZoneApplicationCreateZoneVo;
import com.microservices.zone.detail.domain.vo.ZoneApplicationSearchVo;
import com.microservices.zone.detail.mapper.ZoneApplicationMapper;
import com.microservices.zone.detail.service.IZoneApplicationService;
import com.microservices.zone.detail.service.IZoneDetailService;
import com.microservices.zone.utils.ZoneGitLinkRequestUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 特色专区申请Service业务层处理
 *
 * @author microservices
 * @date 2023-09-13
 */
@Service
public class ZoneApplicationServiceImpl implements IZoneApplicationService
{
    @Autowired
    private ZoneApplicationMapper zoneApplicationMapper;

    @Resource
    private IZoneDetailService zoneDetailService;

    @Autowired
    private GitLinkRequestHelper gitLinkRequestHelper;

    @Autowired
    private RemoteDeptService remoteDeptService;

    /**
     * 查询特色专区申请
     * 
     * @param id 特色专区申请主键
     * @return 特色专区申请
     */
    @Override
    public ZoneApplication selectZoneApplicationById(Long id)
    {
        ZoneApplication zoneApplication = zoneApplicationMapper.selectZoneApplicationById(id);
        if (zoneApplication == null) {
            throw new ServiceException("该专区申请不存在(专区申请id[" + id + "])");
        }
        return zoneApplication;
    }

    /**
     * 查询特色专区申请列表
     * 
     * @param zoneApplication 特色专区申请
     * @return 特色专区申请
     */
    @Override
    public List<ZoneApplication> selectZoneApplicationList(ZoneApplication zoneApplication)
    {
        return zoneApplicationMapper.selectZoneApplicationList(zoneApplication);
    }

    @Override
    public GenericsTableDataInfo<ZoneApplication> selectZoneApplicationListBySearchInput(ZoneApplicationSearchVo zoneApplicationSearchVo) {
        PageUtils.startPage();
        List<ZoneApplication> zoneApplications = zoneApplicationMapper.selectZoneApplicationListBySearchInput(zoneApplicationSearchVo);
        return PageUtils.toPage(zoneApplications);
    }

    /**
     * 新增特色专区申请
     * 
     * @param zoneApplication 特色专区申请
     * @return 结果
     */
    @Override
    public int insertZoneApplication(ZoneApplication zoneApplication)
    {
        // 当用户未填写专区标识时，自动生成专区标识
        if (StringUtils.isEmpty(zoneApplication.getKey())) {
            zoneApplication.setKey(zoneDetailService.genZoneKey(zoneApplication.getName()));
        } else {
            zoneDetailService.checkZoneKey(zoneApplication.getKey());
        }
        ZoneDetail zoneDetail = zoneDetailService.selectZoneDetailByKey(zoneApplication.getKey());
        JSONObject requestBody = new JSONObject();
        requestBody.put("text", zoneApplication.getKey());
        JSONObject result = gitLinkRequestHelper.doPost(ZoneGitLinkRequestUrl.CHECK_PROJECT_KEYWORDS(), requestBody);
        if (result != null && StringUtils.isNotEmpty(result.getString("data")) && "false".equals(result.getString("data"))) {
            throw new ServiceException("专区标识：" + zoneApplication.getKey() + " 无法使用，请重新命名");
        }
        if (zoneDetail != null) {
            throw new ServiceException("专区标识：" + zoneApplication.getKey() + " 已存在");
        }
        ZoneDetail zoneDetail1 = zoneDetailService.selectZoneDetailByName(zoneApplication.getName());
        if (zoneDetail1 != null) {
            throw new ServiceException("专区名称：" + zoneApplication.getName() + " 已存在");
        }
        zoneApplication.setCreateTime(DateUtils.getNowDate());
        zoneApplication.setCreateBy(SecurityUtils.getUsername());
        return zoneApplicationMapper.insertZoneApplication(zoneApplication);
    }

    /**
     * 修改特色专区申请
     * 
     * @param zoneApplication 特色专区申请
     * @return 结果
     */
    @Override
    public int updateZoneApplication(ZoneApplication zoneApplication)
    {
        zoneApplication.setUpdateTime(DateUtils.getNowDate());
        zoneApplication.setUpdateBy(SecurityUtils.getUsername());
        return zoneApplicationMapper.updateZoneApplication(zoneApplication);
    }

    /**
     * 批量删除特色专区申请
     * 
     * @param ids 需要删除的特色专区申请主键
     * @return 结果
     */
    @Override
    public int deleteZoneApplicationByIds(Long[] ids)
    {
        return zoneApplicationMapper.deleteZoneApplicationByIds(ids);
    }

    /**
     * 删除特色专区申请信息
     * 
     * @param id 特色专区申请主键
     * @return 结果
     */
    @Override
    public int deleteZoneApplicationById(Long id)
    {
        return zoneApplicationMapper.deleteZoneApplicationById(id);
    }

    @Override
    public Long createZoneByApplication(Long id, ZoneApplicationCreateZoneVo zoneApplicationCreateZoneVo) {
        checkZoneName(zoneApplicationCreateZoneVo.getName());
        zoneDetailService.checkZoneKey(zoneApplicationCreateZoneVo.getKey());
        ZoneApplication zoneApplication = selectZoneApplicationById(id);
        if (zoneApplication.getZoneId() != null) {
            throw new ServiceException("已基于该专区申请创建专区，不可重复创建(专区申请id[%d],专区id[%d])"
                    , zoneApplication.getId(), zoneApplication.getZoneId());
        }
        Long zoneId = zoneDetailService.createZoneByApplication(zoneApplicationCreateZoneVo);
        zoneApplication.setZoneId(zoneId);
        updateZoneApplication(zoneApplication);
        return zoneId;
    }

    private void checkZoneName(String name) {
        if (name.isEmpty() || name.length() > 30) {
            throw new ServiceException("专区名称长度应该为1-30(组织名称[" + name + "])");
        }
        String NAME_REGEX = "^[a-zA-Z0-9_\u4e00-\u9fa5\\-\\.]+$";
        boolean isValidName = Pattern.matches(NAME_REGEX, name);
        if (!isValidName) {
            throw new ServiceException("专区名称不符合规范，当前仅支持：中文、英文、数字、下划线、中划线和英文句号(专区名称[" + name + "])");
        }
    }
}
