package com.yanzhu.manage.service.impl;

import com.yanzhu.common.core.constant.CacheConstants;
import com.yanzhu.common.core.constant.SecurityConstants;
import com.yanzhu.common.core.context.SecurityContextHolder;
import com.yanzhu.common.core.domain.R;
import com.yanzhu.common.core.exception.ServiceException;
import com.yanzhu.common.core.utils.DateUtils;
import com.yanzhu.common.core.utils.StringUtils;
import com.yanzhu.common.redis.service.RedisService;
import com.yanzhu.common.security.utils.SecurityUtils;
import com.yanzhu.manage.domain.ProDept;
import com.yanzhu.manage.domain.ProProjectInfo;
import com.yanzhu.manage.domain.ProProjectInfoDepts;
import com.yanzhu.manage.domain.ProProjectInfoSetting;
import com.yanzhu.manage.mapper.ProProjectInfoDeptsMapper;
import com.yanzhu.manage.mapper.ProProjectInfoMapper;
import com.yanzhu.manage.mapper.ProProjectInfoSettingMapper;
import com.yanzhu.manage.service.IProProjectInfoService;
import com.yanzhu.system.api.RemoteDeptService;
import com.yanzhu.system.api.domain.SysDept;
import com.yanzhu.system.api.domain.SysUser;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 项目信息Service业务层处理
 * 
 * @author JiangYuQi
 * @date 2024-08-25
 */
@Service
public class ProProjectInfoServiceImpl implements IProProjectInfoService 
{
    @Autowired
    private RedisService redisService;

    @Autowired
    private ProProjectInfoDeptsMapper deptsMapper;

    @Autowired
    private ProProjectInfoSettingMapper settingMapper;

    @Autowired
    private ProProjectInfoMapper proProjectInfoMapper;

    @Autowired
    private RemoteDeptService remoteDeptService;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingProjectsCache();
    }

    /**
     * 加载地址信息到缓存
     */
    @Override
    public void loadingProjectsCache(){
        List<ProProjectInfo> list = proProjectInfoMapper.selectProProjectInfoList(new ProProjectInfo());
        if(StringUtils.isNotEmpty(list)){
            for(ProProjectInfo info:list){
                redisService.setCacheObject(CacheConstants.PRO_PROJECT+info.getId(),info);
            }
        }
    }

    /**
     * 查询项目信息
     * 
     * @param id 项目信息主键
     * @return 项目信息
     */
    @Override
    public ProProjectInfo selectProProjectInfoById(Long id)
    {
        return proProjectInfoMapper.selectProProjectInfoById(id);
    }

    /**
     * 查询项目信息列表
     * 
     * @param proProjectInfo 项目信息
     * @return 项目信息
     */
    @Override
    public List<ProProjectInfo> selectProProjectInfoList(ProProjectInfo proProjectInfo)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if(!SecurityUtils.isAdmin(sysUser.getUserId())){
            proProjectInfo.setActiveComId(sysUser.getComId());
            if(!SecurityUtils.isGSAdmin()){
                proProjectInfo.setCurrentUserId(sysUser.getUserId());
            }
        }
        return proProjectInfoMapper.selectProProjectInfoList(proProjectInfo);
    }

    /**
     * 新增项目信息
     * 
     * @param proProjectInfo 项目信息
     * @return 结果
     */
    @Override
    public int insertProProjectInfo(ProProjectInfo proProjectInfo)
    {
        R<SysDept> deptResult = remoteDeptService.getDeptInfo(proProjectInfo.getDisDeptId(), SecurityConstants.INNER);
        SysDept sysDept = deptResult.getData();
        ProDept proDept = new ProDept();
        proDept.setParentId(proProjectInfo.getDisDeptId());
        proDept.setAncestors(sysDept.getAncestors()+","+proProjectInfo.getDisDeptId());
        proDept.setDeptName(proProjectInfo.getProjectName());
        proDept.setDeptShortName(proProjectInfo.getSimpleName());
        proDept.setDeptType("4");
        proDept.setOrderNum(100);
        proDept.setLeader(proProjectInfo.getProjectPerson());
        proDept.setPhone(proProjectInfo.getProjectPersonPhone());
        proDept.setCreateBy(SecurityUtils.getUsername());
        int res = proProjectInfoMapper.insertDept(proDept);
        if(res>0){
            proProjectInfo.setId(proDept.getDeptId());
            proProjectInfo.setComId(sysDept.getComId());
            proProjectInfo.setProjectPackage(projectPackage(proProjectInfo.getProjectName(),proDept.getDeptId()));
            proProjectInfo.setCreateTime(DateUtils.getNowDate());
            res = proProjectInfoMapper.insertProProjectInfo(proProjectInfo);
            loadingProjectsCache();
            return res;
        }else{
            throw new ServiceException("项目信息保存失败！！！");
        }
    }

    /**
     * 修改项目信息
     * 
     * @param proProjectInfo 项目信息
     * @return 结果
     */
    @Override
    public int updateProProjectInfo(ProProjectInfo proProjectInfo)
    {
        proProjectInfo.setUpdateTime(DateUtils.getNowDate());
        proProjectInfo.setUpdateBy(SecurityContextHolder.getUserName());
        List<ProProjectInfoDepts> depts = proProjectInfo.getProjectDeptsList();
        if(depts!=null){
            depts.forEach(dept->{
                dept.setProjectId(proProjectInfo.getId());
                if(dept.getId()!=null){
                    deptsMapper.updateProProjectInfoDepts(dept);
                }else{
                    deptsMapper.insertProProjectInfoDepts(dept);
                }
            });
        }
        ProProjectInfoSetting setting = proProjectInfo.getSetting();
        if(setting!=null){
            setting.setProjectId(proProjectInfo.getId());
            if(setting.getId()!=null){
                settingMapper.updateProProjectInfoSetting(setting);
            }else{
                settingMapper.insertProProjectInfoSetting(setting);
            }
        }
        int res = proProjectInfoMapper.updateProProjectInfo(proProjectInfo);
        if(res>0){
            R<SysDept> deptResult = remoteDeptService.getDeptInfo(proProjectInfo.getDisDeptId(), SecurityConstants.INNER);
            SysDept sysDept = deptResult.getData();
            ProDept proDept = new ProDept();
            proDept.setDeptId(proProjectInfo.getId());
            proDept.setParentId(proProjectInfo.getDisDeptId());
            proDept.setAncestors(sysDept.getAncestors()+","+proProjectInfo.getDisDeptId());
            proDept.setDeptName(proProjectInfo.getProjectName());
            proDept.setDeptShortName(proProjectInfo.getSimpleName());
            proDept.setLeader(proProjectInfo.getProjectPerson());
            proDept.setPhone(proProjectInfo.getProjectPersonPhone());
            proProjectInfoMapper.updateDept(proDept);
        }
        loadingProjectsCache();
        return res;
    }

    /**
     * 批量删除项目信息
     * 
     * @param ids 需要删除的项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProProjectInfoByIds(Long[] ids)
    {
        return proProjectInfoMapper.deleteProProjectInfoByIds(ids);
    }

    /**
     * 删除项目信息信息
     * 
     * @param id 项目信息主键
     * @return 结果
     */
    @Override
    public int deleteProProjectInfoById(Long id)
    {
        return proProjectInfoMapper.deleteProProjectInfoById(id);
    }

    /**
     * 查询用户名称
     * @param name
     * @return
     */
    private String projectPackage(String name,Long deptId){
        // 设置不带声调的输出选项
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder output = new StringBuilder();
        for (char c : name.toCharArray()) {
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    output.append(pinyinArray[0]);
                } else {
                    output.append(c);
                }
            } catch (Exception e) {
                output.append(c);
            }
        }
        output.append("_"+deptId);
        return output.toString();
    }
}
