package jnpf.workflow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jnpf.attendance.service.AttendanceClockInPicService;
import jnpf.entity.attendance.AttendanceClockInPic;
import jnpf.util.FtbUtil;
import jnpf.workflow.service.ApplyPicService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 审批图片服务实现
 *
 * @author yanwenfu
 * @create 2025-09-22
 */
@Service
public class ApplyPicServiceImpl implements ApplyPicService {

    @Resource
    private AttendanceClockInPicService attendanceClockInPicService;

    @Override
    public List<String> getPicList(List<String> picUrlList) {

        if (null != picUrlList && !picUrlList.isEmpty()) {
            String str = picUrlList.get(0);
            JSONArray array = new JSONArray(str);
            List<String> list = new ArrayList<>();
            array.forEach(v -> {
                JSONObject json = new JSONObject(v);
                Object o = json.get("previewUrl");
                if (null != o) {
                    list.add(o.toString());
                }
                json.clear();
            });
            array.clear();
            return list;
        }
        return List.of();
    }

    @Override
    public void saveClockPic(String taskId, List<String> urlList) {

        if (CollUtil.isNotEmpty(urlList)) {
            List<AttendanceClockInPic> picUrlList = CollUtil.newArrayList();
            picUrlList.addAll(urlList.stream().map(item -> {
                AttendanceClockInPic clickInPic = AttendanceClockInPic.builder()
                        .approvalCode(taskId)
                        .picUrl(item)
                        .build();
                clickInPic.setId(FtbUtil.getId());
                return clickInPic;
            }).collect(Collectors.toList()));
            attendanceClockInPicService.remove(new LambdaQueryWrapper<AttendanceClockInPic>().eq(AttendanceClockInPic::getApprovalCode, taskId));
            attendanceClockInPicService.saveBatch(picUrlList);
        }
    }
}
