package com.zt.plat.module.qms.resource.clientManage.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.clientManage.VersionManagementConst;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.VersionManagementPageReqVO;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.VersionManagementRespVO;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.VersionManagementSaveReqVO;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.UploadFileVo;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import com.zt.plat.module.qms.resource.clientManage.dal.dataobject.VersionManagementDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.resource.clientManage.dal.mapper.VersionManagementMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception0;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 客户端版本管理 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class VersionManagementServiceImpl implements VersionManagementService {

    @Resource
    private VersionManagementMapper versionManagementMapper;
    @Resource private BusinessFileService businessFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VersionManagementRespVO createVersionManagement(VersionManagementSaveReqVO createReqVO) {
        //多条数据取第一条

        // 插入
        VersionManagementDO versionManagement = BeanUtils.toBean(createReqVO, VersionManagementDO.class);
        //        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();//获取当前登录人通用方法
//        systemVersionManagement.setCreator(String.valueOf(SecurityFrameworkUtils.getLoginUser().getId()));
        handleFileParam(createReqVO);
        versionManagementMapper.insert(versionManagement);
        // 返回
        return BeanUtils.toBean(versionManagement, VersionManagementRespVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVersionManagement(VersionManagementSaveReqVO updateReqVO) {
        // 校验存在
        validateVersionManagementExists(updateReqVO.getId());
        handleFileParam(updateReqVO);
        // 更新
        VersionManagementDO updateObj = BeanUtils.toBean(updateReqVO, VersionManagementDO.class);
//        updateObj.setUpdater(String.valueOf(SecurityFrameworkUtils.getLoginUser().getId()));
        versionManagementMapper.updateById(updateObj);

        businessFileService.deleteBusinessFileList(updateReqVO.getDeleteFileIdList());

    }

    //处理附件参数
    private void handleFileParam(VersionManagementSaveReqVO reqVO){
        List<UploadFileVo> files = reqVO.getFiles();
        if (files == null || files.isEmpty())
            return;
        UploadFileVo uploadFileVo = files.get(0);
        reqVO.setDownloadUrl(uploadFileVo.getUrl());
        reqVO.setFileMd5(uploadFileVo.getMd5());
        reqVO.setFileEncryptAlgorithm(uploadFileVo.getSha1());
        reqVO.setDownloadId(uploadFileVo.getId());
    }

    @Override
    public void deleteVersionManagement(Long id) {
        // 校验存在
        validateVersionManagementExists(id);
        // 删除
        versionManagementMapper.deleteById(id);
    }

    @Override
    public void deleteSystemVersionManagementListByIds(List<Long> ids) {
        // 校验存在
        validateVersionManagementExists(ids);
        // 删除
        versionManagementMapper.deleteByIds(ids);
    }

    private void validateVersionManagementExists(List<Long> ids) {
        List<VersionManagementDO> list = versionManagementMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(SYSTEM_VERSION_MANAGEMENT_NOT_EXISTS);
        }
    }

    private void validateVersionManagementExists(Long id) {
        if (versionManagementMapper.selectById(id) == null) {
            throw exception(SYSTEM_VERSION_MANAGEMENT_NOT_EXISTS);
        }
    }

    @Override
    public VersionManagementDO getVersionManagement(Long id) {
        return versionManagementMapper.selectById(id);
    }

    @Override
    public PageResult<VersionManagementDO> getVersionManagementPage(VersionManagementPageReqVO pageReqVO) {
        return versionManagementMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<VersionManagementDO> getList(VersionManagementPageReqVO pageReqVO) {


        return versionManagementMapper.selectList(pageReqVO);
    }


    /*
    * 发布*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executePublish(Long id) {
        // 校验存在
        validateVersionManagementExists(id);
        // 下线当前发布的版本
        VersionManagementDO entity = versionManagementMapper.selectById(id);
        if(ObjectUtils.isEmpty( entity.getDownloadUrl()) || ObjectUtils.isEmpty( entity.getDownloadId()))
            throw exception0(SYSTEM_VERSION_MANAGEMENT_NOT_EXISTS.getCode(), "请上传附件后再发布！");
        String code = entity.getApplicationCode();
        LambdaQueryWrapper<VersionManagementDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VersionManagementDO::getApplicationCode, code);
        queryWrapper.eq(VersionManagementDO::getPublishFlag, VersionManagementConst.PUBLISH_FLAG_PUBLISH);
        queryWrapper.ne(VersionManagementDO::getId, id);
        List<VersionManagementDO> list = versionManagementMapper.selectList(queryWrapper);
        if(!list.isEmpty()){
            for(VersionManagementDO versionManagementDO : list){
                versionManagementDO.setPublishFlag(VersionManagementConst.PUBLISH_FLAG_OFFLINE);
            }
            versionManagementMapper.updateBatch(list);
        }
        entity.setPublishFlag(VersionManagementConst.PUBLISH_FLAG_PUBLISH);
        versionManagementMapper.updateById(entity);
    }
}