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.core.toolkit.Wrappers;
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.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.resource.domain.*;
import com.mcwl.resource.domain.dto.AddRequestWorkFlow;
import com.mcwl.resource.domain.dto.AddWorkFlowVersion;
import com.mcwl.resource.domain.dto.ModelImagePageRes;
import com.mcwl.resource.domain.request.RequestWorkFlow;
import com.mcwl.resource.domain.response.ResponseWorkFlow;
import com.mcwl.resource.domain.vo.PageVo;
import com.mcwl.resource.domain.vo.WorkFlowVo;
import com.mcwl.resource.mapper.SysUserAttentionMapper;
import com.mcwl.resource.mapper.WorkFlowMapper;
import com.mcwl.resource.mapper.WorkFlowVersionMapper;
import com.mcwl.resource.service.WorkFlowService;
import com.mcwl.system.init.DictInit;
import com.mcwl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

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

/**
 * 工作流 业务实现层
 *
 * @author DaiZibo
 * @date 2025/1/9
 * @apiNote
 */

@Slf4j
@Service
public class WorkFlowServiceImpl extends ServiceImpl<WorkFlowMapper, WorkFlow> implements WorkFlowService {

    @Autowired
    private WorkFlowMapper flowMapper;

    @Autowired
    private CollectServiceImpl collectService;

    @Autowired
    private WorkFlowVersionMapper workFlowVersionMapper;

    @Autowired
    private WorkFlowLikeServiceImpl workFlowLikeService;

    @Autowired
    private SysUserAttentionMapper sysUserAttentionMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Override
    public R<Object> addWorkFlow(AddRequestWorkFlow addRequestWorkFlo) {

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

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


        for (AddWorkFlowVersion addWorkFlowVersion : addRequestWorkFlo.getWorkFlowVersionList()) {

            //校验名字
            WorkFlowVersion workFlowVersion1 = workFlowVersionMapper.selectByFileName(addWorkFlowVersion.getFileName());
            if (workFlowVersion1 != null) {

                return R.fail(HttpStatus.SHOW_ERROR_MSG,"文件名字重复");
            }
            //校验hash
            WorkFlowVersion workFlowVersion2 = workFlowVersionMapper.selectByHash(addWorkFlowVersion.getFileHash());
            if (workFlowVersion2 != null){

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

        RequestWorkFlow requestWorkFlow = new RequestWorkFlow();
        BeanUtil.copyProperties(addRequestWorkFlo, requestWorkFlow);
//        RequestWorkFlow requestWorkFlow = JSON.parseObject(JSON.toJSONString(addRequestWorkFlo), RequestWorkFlow.class);
        //获取封面图
        String filePath = requestWorkFlow.getWorkFlowVersionList().get(0).getImagePaths();

        String[] split = filePath.split(",");

        WorkFlow workFlow = requestWorkFlow.getWorkFlow();
        workFlow.setUserId(SecurityUtils.getUserId());
        workFlow.setCoverPath(split[0]);

        workFlow.setCreateTime(new Date());
        //添加模型表数据
        flowMapper.insert(workFlow);

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

        //批量添加版本
        workFlowVersionMapper.addWorkFlowVersion(requestWorkFlow.getWorkFlow(), addRequestWorkFlo.getWorkFlowVersionList());

        audit(requestWorkFlow);


        return R.ok();
    }

    private void audit(RequestWorkFlow requestWorkFlow) {
        // 执行审核操作
        threadPoolTaskExecutor.submit(() -> {
            WorkFlow workFlow = requestWorkFlow.getWorkFlow();

            if (workFlow != null) {

//                //判断是否删除
//                if (workFlow.getDelFlag().equals("2")) {
//                    //不做审核
//                    log.info("删除工作流信息,不做审核校验");
//                    return;
//                }

                if (workFlow.getWorkflowName() != null) {

                    //审核名称
                    String s = BaiduCensor.TextCensor(workFlow.getWorkflowName());
                    // 解析 JSON 字符串
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    //获取状态码
                    String code = jsonObject.getString("code");
                    if (code != null) {
                        //审核失败，数据有问题
                        workFlow.setAuditStatus(4);
                        workFlow.setAuditText("审核失败");
                        flowMapper.updateById(workFlow);
                        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);
                        workFlow.setAuditText(concatenatedReasons);

                        //修改状态以及失败原因
                        workFlow.setAuditStatus(4);
                        flowMapper.updateById(workFlow);
                        log.info("工作流审核未通过");
                        //结束任务
                        return;
                    }

                }
            }


            List<WorkFlowVersion> workFlowVersionList = requestWorkFlow.getWorkFlowVersionList();

            if (workFlowVersionList != null) {
                //审核版本
                for (WorkFlowVersion workFlowVersion : workFlowVersionList) {

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

                    workFlowVersion.setWorkFlowId(workFlow.getId());
                    //版本名称
                    String s1 = BaiduCensor.TextCensor(workFlowVersion.getVersionName() + "," + workFlowVersion.getVersionDescription());
                    // 解析 JSON 字符串
                    JSONObject jsonObject1 = JSONObject.parseObject(s1);
                    String code = jsonObject1.getString("code");
                    if (code != null) {
                        //审核失败，数据有问题
                        workFlow.setAuditStatus(4);
                        workFlow.setAuditText("审核失败");
                        flowMapper.updateById(workFlow);
                        log.info("工作流审核未通过");
                        return;
                    }
                    // 获取 '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);
                        workFlow.setAuditText(concatenatedReasons);

                        //修改状态以及失败原因
                        workFlow.setAuditStatus(4);
                        flowMapper.updateById(workFlow);

                        log.info("版本审核文字未通过");
                        return;
                    }

                    //审核版本图片
                    String[] split = workFlowVersion.getImagePaths().split(",");
                    for (String path : split) {
                        String s2 = BaiduCensor.ImageCnesor(path);
                        JSONObject jsonObject2 = JSONObject.parseObject(s2);
                        String code1 = jsonObject2.getString("code");
                        if (code1 != null) {
                            //审核失败，数据有问题
                            workFlow.setAuditStatus(4);
                            workFlow.setAuditText("审核失败");
                            flowMapper.updateById(workFlow);
                            log.info("工作流审核未通过");
                            return;
                        }
                        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);
                            workFlow.setAuditText(concatenatedReasons);

                            //修改状态以及失败原因
                            workFlow.setAuditStatus(4);
                            flowMapper.updateById(workFlow);

                            log.info("工作流图片审核未通过");
                            return;
                        }
                    }


                    //修改为合格
                    workFlow.setAuditText("");
                    workFlow.setAuditStatus(workFlow.getJurisdiction());
                    flowMapper.updateById(workFlow);
                }
            }

        });
    }

    @Override
    public void updateWorkFlow(RequestWorkFlow requestWorkFlow) {
        WorkFlow workFlows = requestWorkFlow.getWorkFlow();
        //修改工作流的信息
        if (ObjectUtils.isEmpty(workFlows)) {
            return;
        }
        if (StringUtils.isNotNull(workFlows.getId())) {

            workFlows.setUpdateTime(new Date());
            workFlows.setAuditStatus(3);
//            flowMapper.updateWorkFlow(requestWorkFlow.getWorkFlow());
            flowMapper.updateById(requestWorkFlow.getWorkFlow());
        }
        if (workFlows.getDelFlag().equals("2")) {

            return;
        }

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

            //批量修改
            for (WorkFlowVersion workFlowVersion : requestWorkFlow.getWorkFlowVersionList()) {
//                workFlowVersionMapper.updateWorkFlowVersion(workFlowVersion);
                if (workFlowVersion.getId() != null) {
                    workFlowVersionMapper.updateById(workFlowVersion);
                } else {
                    workFlowVersion.setWorkFlowId(workFlows.getId());
                    workFlowVersionMapper.insert(workFlowVersion);
                }

            }

            WorkFlow workFlow = WorkFlow.builder().id(requestWorkFlow.getWorkFlowVersionList().get(0).getWorkFlowId())
                    .updateTime(new Date()).build();
            //更新时间
            flowMapper.updateById(workFlow);
        }

        //审核修改后的数据
        audit(requestWorkFlow);

    }

    @Override
    public void deleteWorkFlow(Long id) {

        WorkFlow workFlow = WorkFlow.builder().id(id)
                .delFlag(2).build();

        flowMapper.updateById(workFlow);
    }

    @Override
    public R<Page<WorkFlow>> selectWorkFlow(PageVo pageVo) {

        Page<WorkFlow> page = new Page<>(pageVo.getPageNumber(), pageVo.getPageSize());

        LambdaQueryWrapper<WorkFlow> lambdaQueryWrapper = Wrappers.<WorkFlow>lambdaQuery()
                .like(StringUtils.isNotBlank(pageVo.getName()), WorkFlow::getWorkflowName, pageVo.getName())
                .eq(WorkFlow::getAuditStatus,1)
                .eq(WorkFlow::getDelFlag, 0);

        if (pageVo.getOrder() == 1) {
            lambdaQueryWrapper.orderByDesc(WorkFlow::getUseNumber);
        } else {
            lambdaQueryWrapper.orderByDesc(WorkFlow::getId);
        }

        lambdaQueryWrapper.select(WorkFlow::getId, WorkFlow::getWorkflowName, WorkFlow::getCoverPath);

        return R.ok(flowMapper.selectPage(page, lambdaQueryWrapper));
    }

    @Override
    public R<WorkFlow> selectWorkFlowById(Long id) {

        //查询详情
        WorkFlow workFlow = flowMapper.selectById(id);
        if (workFlow == null) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"工作流不存在");
        }

        //类别
        if (StringUtils.isNotEmpty(workFlow.getType())) {
            ArrayList<String> strings = new ArrayList<>();
            String[] split = workFlow.getType().split(",");
            for (String s : split) {
                if (!s.equals("")) {
                    strings.add(DictInit.getDictValue(DictConstants.WORK_FLOW_TYPE_CHILD, s));
                }
            }
            workFlow.setTypeList(strings);
        }
        workFlow.setIsAttention(1);
        SysUserAttention sysUserAttention = sysUserAttentionMapper.selectAttention(SecurityUtils.getUserIdMax(), workFlow.getUserId());
        if (sysUserAttention == null) {
            workFlow.setIsAttention(0);
        }

        WorkFlowLike workFlowLike = workFlowLikeService.selectWorkFlowLikeById(SecurityUtils.getUserIdMax(), workFlow.getId());
        workFlow.setIsLike(1);
        if (workFlowLike == null) {
            workFlow.setIsLike(0);
        }
        return R.ok(workFlow);
    }


    @Override
    public TableDataInfo listByPage(ModelImagePageRes imagePageRes) {

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

        Page<WorkFlow> 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<WorkFlow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(imagePageRes.getStatus() != null && imagePageRes.getStatus() != 0, WorkFlow::getAuditStatus, imagePageRes.getStatus())
                .eq(WorkFlow::getUserId, imagePageRes.getUserId())
                .ge(imagePageRes.getStartTime() != null, WorkFlow::getCreateTime, imagePageRes.getStartTime())
                .le(imagePageRes.getEndTime() != null, WorkFlow::getCreateTime, imagePageRes.getEndTime())
                .eq(WorkFlow::getDelFlag, 0);

        baseMapper.selectPage(page, lqw);
        // 获取分页数据
        List<WorkFlow> workFlowList = page.getRecords();

        // WorkFlow数据转为WorkFlowVo
        List<WorkFlowVo> workFlowVoList = new ArrayList<>();
        for (WorkFlow workFlow : workFlowList) {
            WorkFlowVo workFlowVo = new WorkFlowVo();
            BeanUtil.copyProperties(workFlow, workFlowVo);
            // 获取用户信息
            SysUser sysUser = sysUserService.selectUserById(workFlow.getUserId());
            if (Objects.isNull(sysUser)) {
                page.setTotal(page.getTotal() - 1);
                continue;
            }
            workFlowVo.setUserId(sysUser.getUserId());
            workFlowVo.setUserName(sysUser.getNickName());
            workFlowVo.setUserAvatar(sysUser.getAvatar());
            workFlowVoList.add(workFlowVo);
        }

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

        return rspData;

    }

    @Override
    public void setworkFlowTop(Long id, boolean isTop) {
        flowMapper.setworkFlowTop(id, isTop ? 1 : 0);
    }

    @Override
    public List<WorkFlow> fetchWorkFlowSortedByTopStatus() {
        return flowMapper.fetchWorkFlowSortedByTopStatus();
    }

    @Override
    public Long selectWorkFlowByName(String name) {

        LambdaQueryWrapper<WorkFlow> workFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();

        workFlowLambdaQueryWrapper.eq(WorkFlow::getWorkflowName, name);
        workFlowLambdaQueryWrapper.eq(WorkFlow::getDelFlag, 0);
        return baseMapper.selectCount(workFlowLambdaQueryWrapper);
    }

    @Override
    public R<RequestWorkFlow> selectWorkFlowVersionById(Long id) {

        RequestWorkFlow requestWorkFlow = new RequestWorkFlow();
        WorkFlow workFlow = baseMapper.selectById(id);
        if (workFlow == null) {

            return R.fail(HttpStatus.SHOW_ERROR_MSG,"数据不存在");
        }

        if (workFlow.getDelFlag() == 2) {

            return R.fail(HttpStatus.SHOW_ERROR_MSG,"数据不存在");
        }

        LambdaQueryWrapper<WorkFlowVersion> workFlowVersionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        workFlowVersionLambdaQueryWrapper.eq(WorkFlowVersion::getWorkFlowId, id);
        workFlowVersionLambdaQueryWrapper.eq(WorkFlowVersion::getDelFlag, 0);
        List<WorkFlowVersion> workFlowVersions = workFlowVersionMapper.selectList(workFlowVersionLambdaQueryWrapper);
        requestWorkFlow.setWorkFlow(workFlow);
        requestWorkFlow.setWorkFlowVersionList(workFlowVersions);
        return R.ok(requestWorkFlow);
    }

    @Override
    public PageInfo<ResponseWorkFlow> workFlowList(PageVo pageVo) {

        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(pageVo.getPageNumber(), pageVo.getPageSize());

        List<ResponseWorkFlow> responseWorkFlowList = baseMapper.workFlowList(pageVo);

        Long userIdMax = SecurityUtils.getUserIdMax();

        for (ResponseWorkFlow responseWorkFlow : responseWorkFlowList) {

            responseWorkFlow.setType(DictInit.getDictValue(DictConstants.WORK_FLOW_TYPE_CHILD, responseWorkFlow.getType()));
            //查询工作流型第一个版本信息
            if (pageVo.getIsCollect() == 0){

                WorkFlowVersion workFlowVersion = workFlowVersionMapper.selectByWorkFlowId(responseWorkFlow.getId());

                if (userIdMax == 0){
                    //收藏为空
                    workFlowVersion.setIsCollect(0);
                }else {
                    //查询是否收藏
                    Collect collect = collectService.selectCollectById(workFlowVersion.getId(), userIdMax, 1);

                    if (collect == null){

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

                }

                responseWorkFlow.setWorkFlowVersion(workFlowVersion);
            }

        }


        return new PageInfo<ResponseWorkFlow>(responseWorkFlowList);

    }



}
