package cd.casic.ci.process.process.service.testCase.impl;


import cd.casic.ci.process.dto.req.testCase.TestCaseInfoQueryReq;
import cd.casic.ci.process.dto.req.testCase.TestCaseInfoReq;
import cd.casic.ci.process.dto.resp.testCase.TestCaseInfoResp;
import cd.casic.ci.process.process.converter.TestCaseInfoConverter;
import cd.casic.ci.process.process.dao.testCase.TestCaseInfoDao;
import cd.casic.ci.process.process.dataObject.testCase.TestCaseInfo;
import cd.casic.ci.process.process.service.testCase.TestCaseInfoService;
import cd.casic.ci.process.util.FileUtil;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.security.dal.user.AdminUserDO;
import cd.casic.framework.tenant.core.service.AdminUserServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author HopeLi
 * @version v1.0
 * @ClassName PipelineServiceImpl
 * @Date: 2025/5/13 10:31
 * @Description:
 */
@Service
@Slf4j
public class TestCaseInfoServiceImpl extends ServiceImpl<TestCaseInfoDao, TestCaseInfo> implements TestCaseInfoService {

    @Resource
    private TestCaseInfoDao testCaseInfoDao;

    @Resource
    private AdminUserServiceImpl adminUserService;

    @Override
    public String create(TestCaseInfoReq req) {
        TestCaseInfo testCaseInfo = TestCaseInfoConverter.INSTANCE.toBean(req);
        testCaseInfoDao.insert(testCaseInfo);
        return testCaseInfo.getId();
    }

    @Override
    public void delete(String id) {
        TestCaseInfo testCaseInfo = testCaseInfoDao.selectById(id);
        if (ObjectUtils.isEmpty(testCaseInfo)){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"数据错误请联系管理员");
        }
        testCaseInfoDao.deleteById(id);
    }

    @Override
    public void updateTestCaseInfo(TestCaseInfoReq req) {
        TestCaseInfo testCaseInfo = testCaseInfoDao.selectById(req.getId());
        if (ObjectUtils.isEmpty(testCaseInfo)){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"数据错误请联系管理员");
        }

        TestCaseInfoConverter.INSTANCE.updateReqCopyToBean(req,testCaseInfo);
        testCaseInfoDao.updateById(testCaseInfo);
    }

    @Override
    public List<TestCaseInfoResp> findList(TestCaseInfoQueryReq query) {
        QueryWrapper<TestCaseInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(query.getTestFileType())){
            wrapper.eq("test_file_type", query.getTestFileType());
        }
        if (!StringUtils.isEmpty(query.getTestCaseManagerId())){
            wrapper.eq("test_case_manager_id", query.getTestCaseManagerId());
        }
        List<TestCaseInfo> testCaseInfos = testCaseInfoDao.selectList(wrapper);


        if (ObjectUtils.isEmpty(testCaseInfos)){
            return new ArrayList<>();
        }
        List<TestCaseInfoResp> respList = TestCaseInfoConverter.INSTANCE.toRespList(testCaseInfos);
        respList.forEach(this::setUserName);
        return respList;
    }



    @Override
    public PageResult<TestCaseInfoResp> findPage(TestCaseInfoQueryReq query) {
        QueryWrapper<TestCaseInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(query.getTestFileType())){
            wrapper.eq("test_file_type", query.getTestFileType());
        }
        if (!StringUtils.isEmpty(query.getTestCaseManagerId())){
            wrapper.eq("test_case_manager_id", query.getTestCaseManagerId());
        }
        Page<TestCaseInfo> testCaseInfoPage = testCaseInfoDao.selectPage(new Page<>(query.getPageNo(), query.getPageSize()), wrapper);
        if (ObjectUtils.isEmpty(testCaseInfoPage)){
            return new PageResult<>();
        }
        List<TestCaseInfoResp> respList = TestCaseInfoConverter.INSTANCE.toRespList(testCaseInfoPage.getRecords());
        respList.forEach(this::setUserName);
        return new PageResult<>(respList,testCaseInfoPage.getTotal(),testCaseInfoPage.getCurrent(),testCaseInfoPage.getSize());
    }

    @Override
    public TestCaseInfoResp findById(String id) {
        TestCaseInfo testCaseInfo = testCaseInfoDao.selectById(id);
        if (ObjectUtils.isEmpty(testCaseInfo)){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"数据错误请联系管理员");
        }
        TestCaseInfoResp testCaseInfoResp = TestCaseInfoConverter.INSTANCE.toResp(testCaseInfo);
        setUserName(testCaseInfoResp);
        return testCaseInfoResp;
    }

    @Override
    public List<String> findFileTypeList() {
        List<TestCaseInfo> testCaseInfos = testCaseInfoDao.selectList(new QueryWrapper<>());

        if (ObjectUtils.isEmpty(testCaseInfos)){
            return new ArrayList<>();
        }

        //将文件类型取出并去重
        List<String> fileTypeList = testCaseInfos.stream().map(TestCaseInfo::getTestFileType).distinct().toList();

        if (CollectionUtils.isEmpty(fileTypeList)){
            return new ArrayList<>();
        }
        return fileTypeList;
    }

    @Override
    public List<TestCaseInfoResp> findByManagerIds(List<String> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<TestCaseInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TestCaseInfo::getTestCaseManagerId,idList);
        List<TestCaseInfo> testCaseInfos = testCaseInfoDao.selectList(wrapper);
        return TestCaseInfoConverter.INSTANCE.toRespList(testCaseInfos);
    }

    @Override
    public String checkTestCaseExist(MultipartFile file) {
        try{
            InputStream inputStream = file.getInputStream();
            String md5Str = FileUtil.getMD5Str(inputStream);
            if (!checkMd5Exist(md5Str)) {
                return md5Str;
            }
        } catch (Exception e ){
            log.error("校验文件内容出现错误",e);
        }
        return "";
    }
    private Boolean checkMd5Exist(String sign){
        if (StringUtils.isEmpty(sign)) {
            return false;
        }
        LambdaQueryWrapper<TestCaseInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestCaseInfo::getSign,sign);
        return testCaseInfoDao.exists(wrapper);
    }

    private void setUserName(TestCaseInfoResp testCaseInfoResp) {
        if (!StringUtils.isEmpty(testCaseInfoResp.getCreator())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(testCaseInfoResp.getCreator()));
            if (!ObjectUtils.isEmpty(user)){
                testCaseInfoResp.setCreatorName(user.getUsername());
            }
        }

        if (!StringUtils.isEmpty(testCaseInfoResp.getUpdater())){
            AdminUserDO user = adminUserService.getUser(Long.valueOf(testCaseInfoResp.getUpdater()));
            if (!ObjectUtils.isEmpty(user)){
                testCaseInfoResp.setUpdaterName(user.getUsername());
            }
        }
    }
}
