package com.mcwl.resource.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mcwl.common.constant.Constants;
import com.mcwl.common.constant.DictConstants;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.common.utils.baidu.BaiduCensor;
import com.mcwl.common.utils.http.HttpUtils;
import com.mcwl.resource.domain.*;
import com.mcwl.resource.domain.dto.ModelImagePageRes;
import com.mcwl.resource.domain.request.RequestModel;
import com.mcwl.resource.domain.response.ResponseModelProduct;
import com.mcwl.resource.domain.vo.MallProductVo;
import com.mcwl.resource.domain.vo.ModelVo;
import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.mapper.*;
import com.mcwl.resource.service.ModelService;
import com.mcwl.resource.service.ToActivityService;
import com.mcwl.system.init.DictInit;
import com.mcwl.system.service.ISysUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;


/**模型 业务实现层
 * @Author：ChenYan
 * @Project：McWl
 * @Package：com.mcwl.resource.service.impl
 * @Filename：MallProductServiceImpl
 * @Description TODO
 * @Date：2024/12/30 18:22
 */
@Log4j2
@Service
public class ModelServiceImpl extends ServiceImpl<ModelMapper,ModelProduct> implements ModelService {

    @Autowired
    private ToActivityService toActivityService;
    @Autowired
    private ModelVersionMapper modelVersionMapper;
    @Autowired
    private ModelMapper postMapper;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private DownloadRecordServiceImpl downloadRecordService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private SysUserAttentionMapper sysUserAttentionMapper;

    @Autowired
    private ModelLikeMapper modelLikeMapper;

    @Autowired
    private CollectServiceImpl collectService;


    @Value("${mcwl.encryptUrl}")
    private String encryptUrl;


    /**
     * 设置模型置顶状态
     *
     * @param id 模型ID
     * @param isTop 是否置顶
     */
    @Override
    public void setModelTop(Long id, boolean isTop) {
        postMapper.updateTopStatus(id, isTop ? 1 : 0);
    }
    /**
     * 获取模型列表
     *
     * @param
     * @return 模型列表
     */

    @Override
    public List<ModelProduct> fetchModelsSortedByTopStatus() {
        return postMapper.selectAllModelsSortedByTopStatus();
    }

    @Override
    public PageInfo<ResponseModelProduct> modelSquare(PageVo pageVo) {
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageVo.getPageNumber(),pageVo.getPageSize());

        Long userIdMax = SecurityUtils.getUserIdMax();
        List<ResponseModelProduct> responseModelProductList = postMapper.modelSquare(pageVo);
        for (ResponseModelProduct responseModelProduct : responseModelProductList) {
            if (responseModelProduct.getModelType() != null){

                responseModelProduct.setType(DictInit.getDictValue(DictConstants.MODEL_TYPE,responseModelProduct.getModelType()+""));
            }

            //查询该模型第一个版本信息
            if (pageVo.getIsCollect() == 0){

                ModelVersion modelVersion = modelVersionMapper.selectByProductId(responseModelProduct.getId());

                if (modelVersion == null){

                    //跳出循环
                    continue;
                }

                if (userIdMax == 0){
                    //收藏为空
                    modelVersion.setIsCollect(0);

                    //下载为空
                    modelVersion.setIsDownload(0);
                }else {
                    //查询是否收藏
                    Collect collect = collectService.selectCollectById(modelVersion.getId(), userIdMax, 0);

                    if (collect == null){

                        modelVersion.setIsCollect(0);
                    }else {
                        modelVersion.setIsCollect(1);
                    }

                    //校验是否下载
                    modelVersion.setIsDownload(downloadRecordService.selectDownloadByUser(userIdMax,modelVersion.getModelId(),0));

                }

                responseModelProduct.setModelVersion(modelVersion);
            }

        }

        return new PageInfo<ResponseModelProduct>(responseModelProductList);
    }

    @Override
    public R selectModelByName(String name) {

        //根绝名字查找数据
        LambdaQueryWrapper<ModelProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ModelProduct::getModelName,name);
        queryWrapper.eq(ModelProduct::getDelFlag,0);

        List<ModelProduct> modelProducts = postMapper.selectList(queryWrapper);

        if (modelProducts.size()>0){
            return R.ok(0);
        }
        return R.ok(1);
    }

    @Override
    public Page<ModelProduct> selectByUserId(MallProductVo mallProductVo) {

        // 创建分页对象
        Page<ModelProduct> mallProductPage = new Page<>(mallProductVo.getPageNumber(), mallProductVo.getPageSize());

        //获取当前登录人ID
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<ModelProduct> mallProductLambdaQueryWrapper = new LambdaQueryWrapper<>();

        mallProductLambdaQueryWrapper.eq(ModelProduct::getUserId,userId);
        mallProductLambdaQueryWrapper.eq(ModelProduct::getDelFlag,0);

        // 开始时间和结束时间过滤
        if (mallProductVo.getStartTime() != null && mallProductVo.getEndTime() != null) {
            // 查询开始时间和结束时间之间的商品
            mallProductLambdaQueryWrapper.between(ModelProduct::getCreateTime, mallProductVo.getStartTime(), mallProductVo.getEndTime());
        } else if (mallProductVo.getStartTime() != null) {
            // 只有开始时间，查询大于等于开始时间的商品
            mallProductLambdaQueryWrapper.ge(ModelProduct::getCreateTime, mallProductVo.getStartTime());
        } else if (mallProductVo.getEndTime() != null) {
            // 只有结束时间，查询小于等于结束时间的商品
            mallProductLambdaQueryWrapper.le(ModelProduct::getCreateTime, mallProductVo.getEndTime());
        }

        return postMapper.selectPage(mallProductPage, mallProductLambdaQueryWrapper);
    }

    @Override
    public Page<ModelProduct> pageLike(MallProductVo mallProductVo, List<Long> list) {
        return null;
    }


    /**
     * 分页查询
     *
     * @param imagePageRes 分页参数
     * @return 分页数据
     */
    @Override
    public TableDataInfo listByPage(ModelImagePageRes imagePageRes) {

        if (Objects.isNull(imagePageRes.getUserId())) {
            imagePageRes.setUserId(SecurityUtils.getUserIdMax());
        }

        Page<ModelProduct> page = new Page<>(imagePageRes.getPageNum(), imagePageRes.getPageSize());
        if (StringUtils.isEmpty(imagePageRes.getOrderByColumn())) {
            imagePageRes.setOrderByColumn("create_time");
        }
        // 设置排序
        List<OrderItem> orderItemList = new ArrayList<>();
        orderItemList.add(OrderItem.desc("is_top"));
        orderItemList.add(OrderItem.desc(imagePageRes.getOrderByColumn()));
        page.addOrder(orderItemList);

        LambdaQueryWrapper<ModelProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(imagePageRes.getStatus() != null && imagePageRes.getStatus() != 0, ModelProduct::getAuditStatus, imagePageRes.getStatus())
                .eq( ModelProduct::getUserId, imagePageRes.getUserId())
                .ge(imagePageRes.getStartTime() != null, ModelProduct::getCreateTime, imagePageRes.getStartTime())
                .le(imagePageRes.getEndTime() != null, ModelProduct::getCreateTime, imagePageRes.getEndTime());
        postMapper.selectPage(page, lqw);
        // 获取分页数据
        List<ModelProduct> modelImageList = page.getRecords();

        // Model数据转为ModelPageVo
        List<ModelVo> modelVoList = new ArrayList<>();
        for (ModelProduct modelImage : modelImageList) {
            ModelVo modelVo = new ModelVo();
            BeanUtil.copyProperties(modelImage, modelVo);

            // 设置模型类型
            if (Objects.nonNull(modelImage.getModelType())) {
                String modelTypeName = DictInit.getDictValue(DictConstants.MODEL_TYPE, modelImage.getModelType().toString());
                modelVo.setModelType(modelTypeName);
            }

            // 获取用户信息
            SysUser sysUser = sysUserService.selectUserById(modelImage.getUserId());
            if (Objects.isNull(sysUser)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            modelVo.setUserId(sysUser.getUserId());
            modelVo.setUserName(sysUser.getNickName());
            modelVo.setUserAvatar(sysUser.getAvatar());
            modelVoList.add(modelVo);
        }

        // 封装分页数据
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(modelVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }

    @Override
    public R<String> addModel(RequestModel requestModel) {

        //校验是否实名
        SysUser sysUser = sysUserService.selectUserInfoById(SecurityUtils.getUserId());
        log.info("查询到的个人数据:{}",sysUser);
        if (StringUtils.isEmpty(sysUser.getName())){

            return R.fail(HttpStatus.SHOW_ERROR_MSG,"实名制后才可以发布");
        }


        for (ModelVersion modelVersion : requestModel.getModelVersionList()) {

            //校验名字
            ModelVersion modelVersion1 = modelVersionMapper.selectByFileName(modelVersion.getFileName());
            if (modelVersion1 != null) {

                return R.fail(HttpStatus.SHOW_ERROR_MSG,"文件名字重复");
            }
            //校验hash
            ModelVersion modelVersion2 = modelVersionMapper.selectByHash(modelVersion.getFileHash());
            if (modelVersion2 != null){

                return R.fail(HttpStatus.SHOW_ERROR_MSG,"文件内容重复");
            }
        }



        //获取封面图
        String filePath = requestModel.getModelVersionList().get(0).getSampleImagePaths();
        String[] split = filePath.split(",");
        ModelProduct modelProduct = requestModel.getModelProduct();
        modelProduct.setSurfaceUrl(split[0]);
        modelProduct.setCreateTime(new Date());


        //添加模型表数据
        postMapper.insert(requestModel.getModelProduct());

        log.info("获取到的入参:{}",requestModel.getModelProduct());

        //批量添加版本
//        modelVersionMapper.addModelVersion(requestModel.getModelProduct(),requestModel.getModelVersionList());
        for (ModelVersion modelVersion : requestModel.getModelVersionList()) {
            modelVersion.setModelId(requestModel.getModelProduct().getId());
            modelVersionMapper.addModelVersion(modelVersion);
        }

        //执行审核方法
        audit(requestModel);

        return R.ok("添加成功，等待审核");
    }

    @Override
    public void updaModel(RequestModel requestModel) {
        //修改模版的信息
        ModelProduct modelProduct = requestModel.getModelProduct();
        if (ObjectUtils.isNotEmpty(modelProduct)){

            if (StringUtils.isNotNull(modelProduct.getId())){
                modelProduct.setAuditStatus(3);
                modelProduct.setUpdateTime(new Date());
                postMapper.updateById(requestModel.getModelProduct());
            }
        }

        //修改工作流版本的信息
        if (requestModel.getModelVersionList().size() != 0){

            //批量修改
            for (ModelVersion modelVersion : requestModel.getModelVersionList()) {


                if (modelVersion.getId() != null){
                    modelVersionMapper.updateById(modelVersion);
                }else {
                    modelVersion.setModelId(modelProduct.getId());
                    modelVersionMapper.insert(modelVersion);
                }

            }

            ModelProduct model = ModelProduct.builder().
            id(requestModel.getModelVersionList().get(0).
            getModelId()).build();
            model.setUpdateTime(new Date());
            postMapper.updateById(model);
        }

        //审核
        audit(requestModel);

    }
    private void audit(RequestModel requestModel) {

        // 执行审核操作
        threadPoolTaskExecutor.submit(() -> {
            ModelProduct modelProduct = requestModel.getModelProduct();

            if (modelProduct != null){


                if (modelProduct.getModelName() != null){

                    //审核名称
                    String s = BaiduCensor.TextCensor(modelProduct.getModelName()+","+modelProduct.getTags());
                    // 解析 JSON 字符串
                    JSONObject jsonObject = JSONObject.parseObject(s);

                    //获取状态码
                    String code = jsonObject.getString("code");
                    if (code != null){
                        //审核失败，数据有问题
                        modelProduct.setAuditStatus(4);
                        modelProduct.setAuditText("审核失败");
                        baseMapper.updateById(modelProduct);
                        log.info("模型审核未通过");
                        return;
                    }

                    // 获取 'conclusion' 字段的值
                    String conclusion = jsonObject.getString("conclusion");

                    if (conclusion.equals("不合规")) {

                        //更改状态,添加原因 -> 结束任务
                        // 获取 'data' 数组
                        JSONArray dataArray = jsonObject.getJSONArray("data");

                        // 存储所有的失败原因
                        List<String> failureReasons = new ArrayList<>();
                        // 遍历 'data' 数组中的每个元素
                        for (Object itemObj : dataArray) {
                            JSONObject item = (JSONObject) itemObj;
                            String msg = item.getString("msg");
                            failureReasons.add(msg);
                        }
                        // 使用逗号拼接所有的失败原因
                        String concatenatedReasons = String.join(", ", failureReasons);
                        modelProduct.setAuditText(concatenatedReasons);

                        //修改状态以及失败原因
                        modelProduct.setAuditStatus(4);
                        baseMapper.updateById(modelProduct);
                        log.info("模型审核未通过");
                        //结束任务
                        return;
                    }

                }
            }


            List<ModelVersion> modelVersionList = requestModel.getModelVersionList();

            if (modelVersionList != null){
                //审核版本
                for (ModelVersion modelVersion : modelVersionList) {

                    //判断版本是否删除
                    if (modelVersion.getDelFlag().equals("2")){
                        //不做审核
                        log.info("删除模型版本信息,不做审核校验");
                        continue;
                    }

                    modelVersion.setModelId(modelProduct.getId());
                    //版本名称
                    String s1 = BaiduCensor.TextCensor(modelVersion.getVersionName() + "," +
                            modelVersion.getVersionDescription()+","+modelVersion.getTriggerWords());
                    // 解析 JSON 字符串
                    JSONObject jsonObject1 = JSONObject.parseObject(s1);
                    // 获取 'conclusion' 字段的值
                    String conclusion1 = jsonObject1.getString("conclusion");
                    if (conclusion1.equals("不合规")) {

                        //更改版本状态->跳出循环 审核下一个版本
                        // 获取 'data' 数组
                        JSONArray dataArray1 = jsonObject1.getJSONArray("data");
                        // 存储所有的失败原因
                        List<String> failureReasons = new ArrayList<>();
                        // 遍历 'data' 数组中的每个元素
                        for (Object itemObj : dataArray1) {
                            JSONObject item = (JSONObject) itemObj;
                            String msg = item.getString("msg");
                            failureReasons.add(msg);
                        }
                        // 使用逗号拼接所有的失败原因
                        String concatenatedReasons = String.join(", ", failureReasons);
                        modelProduct.setAuditText(concatenatedReasons);

                        //修改状态以及失败原因
                        modelProduct.setAuditStatus(4);
                        baseMapper.updateById(modelProduct);
                        log.info("模型版本审核未通过");
                        return;
                    }

                    //审核版本图片
                    String[] split = modelVersion.getSampleImagePaths().split(",");
                    for (String path : split) {
                        String s2 = BaiduCensor.ImageCnesor(path);
                        JSONObject jsonObject2 = JSONObject.parseObject(s2);
                        if (jsonObject2.getString("conclusion").equals("不合规")
                        || jsonObject2.getString("conclusion").equals("审核失败") ) {

                            //修改状态->跳出循环 判断下一个版本
                            // 获取 'data' 数组
                            JSONArray dataArray2 = jsonObject2.getJSONArray("data");
                            // 存储所有的失败原因
                            List<String> failureReasons = new ArrayList<>();
                            // 遍历 'data' 数组中的每个元素
                            for (Object itemObj : dataArray2) {
                                JSONObject item = (JSONObject) itemObj;
                                String msg = item.getString("msg");
                                failureReasons.add(msg);
                            }
                            String concatenatedReasons = String.join(", ", failureReasons);
                            modelProduct.setAuditText(concatenatedReasons);

                            //修改状态以及失败原因
                            modelProduct.setAuditStatus(4);
                            baseMapper.updateById(modelProduct);
                            log.info("模型版本审核未通过");
                            return;
                        }
                    }

                    //获取出key准备拉取文件
                    String key = modelVersion.getObjectKey();

                    //审核成功，查看时候加密，拉取文件到ui
                    if (modelVersion.getIsEncrypt() == 1){

                        //调用加密/创建参数
                        HashMap<String, String> param = new HashMap<>();
                        param.put("objectKey",modelVersion.getObjectKey());
                        param.put("id",modelVersion.getId()+"");
                        param.put("fileType", Constants.MODEL);

                        String s = HttpUtils.pythonPost(encryptUrl, param);

                        log.info("调用加密服务结果:{}",s);

//                        JSONObject jsonObject = JSONObject.parseObject(s);
//                        JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
//                        String objectKey = data.getString("objectKey");
//                        String path = data.getString("path");
//                        String secretKey = data.getString("secret_key");
//
//                        key = objectKey;
//
//                        ModelVersion modelVersion1 = ModelVersion.builder().id(modelVersion.getId())
//                                .encryptionObjectKey(objectKey)
//                                .encryptionFilePath(path)
//                                .keyRate(secretKey).build();
//                        //更新加密后数据
//                        modelVersionMapper.updateById(modelVersion1);
                    }

//                    //调用ui拉取文件接口
//                    log.info("开始拉取文件...");
//                    HashMap<String, String> hashMap = new HashMap<>();
//                    hashMap.put("objectKey",key);
//                    log.info("整体版本数据:{}",modelVersion);
//                    log.info("拉取文件数据:{}",key);
//                    hashMap.put("type",DictInit.getDictValue(DictConstants.MODEL_TYPE,modelProduct.getModelType()+""));
//                    String s = HttpUtils.pythonPost("http://1.13.246.108:8188/api/experiment/models/upload", hashMap);
//                    log.info("文件拉取结果:{}",s);

                    //修改为合格
                    modelProduct.setAuditText("");
                    modelProduct.setAuditStatus(modelProduct.getJurisdiction());
                    baseMapper.updateById(modelProduct);
                    log.info("模型全部通过审核");
                }
            }

        });

    }




    @Override
    public R<ModelProduct> selectModelById(Long id) {
        //查询详情
        ModelProduct modelProduct = postMapper.selectById(id);
        if (modelProduct == null){

            return R.fail(HttpStatus.SHOW_ERROR_MSG,"该模型不存在");
        }

        //翻译属性  垂类
        if (StringUtils.isNotEmpty(modelProduct.getCategory())){
            modelProduct.setCategory(DictInit.getDictValue(DictConstants.MODEL_CHILD_CATEGORY,modelProduct.getCategory()));
        }

        //功能
        if (StringUtils.isNotEmpty(modelProduct.getFunctions())){
            modelProduct.setCategory(DictInit.getDictValue(DictConstants.WORK_FLOW_FUNCTIONS,modelProduct.getFunctions()));
        }

        //活动
        if (StringUtils.isNotEmpty(modelProduct.getActivityId())){
            modelProduct.setActivityId(toActivityService.getById(modelProduct.getActivityId()).getActivityName());
        }

        modelProduct.setIsAttention(1);
        SysUserAttention sysUserAttention = sysUserAttentionMapper.selectAttention(SecurityUtils.getUserIdMax(), modelProduct.getUserId());
        if (sysUserAttention == null){
            modelProduct.setIsAttention(0);
        }

        WorkFlowLike workFlowLike = modelLikeMapper.selectModelLikeById(SecurityUtils.getUserIdMax(),modelProduct.getId());
        modelProduct.setIsLike(1);
        if (workFlowLike == null){
            modelProduct.setIsLike(0);
        }

        return R.ok(modelProduct);
    }




}
