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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.resource.domain.ModelImage;
import com.mcwl.resource.domain.ModelImageLike;
import com.mcwl.resource.domain.dto.ModelImagePageRes;
import com.mcwl.resource.domain.dto.ModelImageRes;
import com.mcwl.resource.domain.vo.ModelImageVo;
import com.mcwl.resource.mapper.ModelImageCommentMapper;
import com.mcwl.resource.mapper.ModelImageMapper;
import com.mcwl.resource.service.ModelImageLikeService;
import com.mcwl.resource.service.ModelImageService;
import com.mcwl.system.service.ISysDictDataService;
import com.mcwl.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class ModelImageServiceImpl extends ServiceImpl<ModelImageMapper, ModelImage> implements ModelImageService {

    private final ModelImageCommentMapper modelImageCommentMapper;

    private final ModelImageMapper modelImageMapper;

    private final ModelImageLikeService modelImageLikeService;

    private final ISysUserService sysUserService;

    private final ISysDictDataService sysDictDataService;

    private final ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Override
    public void updateById(ModelImageRes modelImageRes) {
        if (Objects.isNull(modelImageRes.getId())) {
            return;
        }
        ModelImage modelImage = new ModelImage();
        BeanUtil.copyProperties(modelImageRes, modelImage);
        modelImageMapper.updateById(modelImage);
        audit(modelImage);
    }

    @Override
    public R publish(ModelImageRes modelImageRes) {

        //校验是否实名
        SysUser sysUser = sysUserService.selectUserInfoById(SecurityUtils.getUserId());
        if (sysUser.getName() == null){

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


        ModelImage modelImage = new ModelImage();
        BeanUtil.copyProperties(modelImageRes, modelImage);
        modelImage.setUserId(SecurityUtils.getUserId());
        modelImage.setStatus(3);
        modelImageMapper.insert(modelImage);

        audit(modelImage);

        return R.ok();
    }

    private void audit(ModelImage modelImage) {

        // 执行审核操作
        threadPoolTaskExecutor.execute(() -> {
            if (modelImage != null) {

                if (modelImage.getTitle() != null) {

                    //审核名称
                    String s = BaiduCensor.TextCensor(modelImage.getTitle() + "," + modelImage.getTags() + ","
                            + modelImage.getDescription());
                    // 解析 JSON 字符串
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    // 获取 '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);
                        modelImage.setAuditText(concatenatedReasons);

                        //修改状态以及失败原因
                        modelImage.setStatus(4);
                        log.info("执行111");
                        modelImageMapper.updateById(modelImage);
                        log.info("图片审核未通过");
                        //结束任务
                        return;
                    }

                    //修改为合格
                    modelImage.setAuditText("");
                    modelImage.setStatus(1);
                    baseMapper.updateById(modelImage);
                }
            }

            if (modelImage.getImagePaths() == null) {
                return;
            }
            //审核图片
            String[] split = modelImage.getImagePaths().split(",");
            for (String path : split) {
                String s2 = BaiduCensor.ImageCnesor(path);
                JSONObject jsonObject2 = JSONObject.parseObject(s2);
                if (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);
                    modelImage.setAuditText(concatenatedReasons);
                    modelImage.setStatus(4);
                    baseMapper.updateById(modelImage);
                    log.info("图片审核未通过");
                    return;
                }
            }

            //修改版本成功审核状态
            modelImage.setAuditText("");
            modelImage.setStatus(1);
            baseMapper.updateById(modelImage);
            log.info("全部通过审核");
        });

    }


    /**
     * 分页查询
     *
     * @param imagePageRes 分页参数
     * @return 分页数据
     */
    @Override
    public TableDataInfo listByPage(ModelImagePageRes imagePageRes) {
        if (Objects.isNull(imagePageRes.getUserId())) {
            imagePageRes.setUserId(SecurityUtils.getUserIdMax());
        }
        Page<ModelImage> 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<ModelImage> lqw = new LambdaQueryWrapper<>();
        lqw.eq(imagePageRes.getStatus() != null && imagePageRes.getStatus() != 0, ModelImage::getStatus, imagePageRes.getStatus())
                .eq(ModelImage::getUserId, imagePageRes.getUserId())
                .ge(imagePageRes.getStartTime() != null, ModelImage::getCreateTime, imagePageRes.getStartTime())
                .le(imagePageRes.getEndTime() != null, ModelImage::getCreateTime, imagePageRes.getEndTime());

        modelImageMapper.selectPage(page, lqw);
        // 获取分页数据
        List<ModelImage> modelImageList = page.getRecords();

        // ModelImage数据转为ModelImagePageVo
        List<ModelImageVo> modelImageVoList = new ArrayList<>();
        for (ModelImage modelImage : modelImageList) {
            ModelImageVo modelImageVo = new ModelImageVo();
            BeanUtil.copyProperties(modelImage, modelImageVo);
            // 获取用户信息
            SysUser sysUser = sysUserService.selectUserById(modelImage.getUserId());
            if (Objects.isNull(sysUser)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            modelImageVo.setUserId(sysUser.getUserId());
            modelImageVo.setUserName(sysUser.getNickName());
            modelImageVo.setUserAvatar(sysUser.getAvatar());
            modelImageVoList.add(modelImageVo);
        }

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

        return rspData;
    }

    @Override
    public ModelImageVo getDetail(Long imageId) {

        ModelImageVo modelImageVo = new ModelImageVo();
        ModelImage modelImage = modelImageMapper.selectById(imageId);
        if (Objects.isNull(modelImage)) {
            return null;
        }
        BeanUtil.copyProperties(modelImage, modelImageVo);

        ModelImageLike modelImageLike = modelImageLikeService.lambdaQuery()
                .eq(ModelImageLike::getUserId, SecurityUtils.getUserIdMax())
                .eq(ModelImageLike::getModelImageId, imageId)
                .one();

        if (Objects.nonNull(modelImageLike)) {
            modelImageVo.setIsLike(1);
        } else {
            modelImageVo.setIsLike(0);
        }

        // 设置标签
        List<String> tagList = new ArrayList<>();
        if (StringUtils.isNotEmpty(modelImage.getTags())) {
            String[] tagValueList = modelImage.getTags().split(",");
            tagList.addAll(Arrays.asList(tagValueList));
        }
        modelImageVo.setTags(tagList);

        SysUser sysUser = sysUserService.selectUserById(modelImage.getUserId());
        modelImageVo.setUserId(sysUser.getUserId());
        modelImageVo.setUserName(sysUser.getNickName());
        modelImageVo.setUserAvatar(sysUser.getAvatar());
        return modelImageVo;
    }


}
