package com.zg.project.wisdom.service.impl;

import com.zg.common.utils.LocalPhotoUtil;
import com.zg.common.utils.LocalPhotoUtil.SaveResult;
import com.zg.project.wisdom.domain.StockPhoto;
import com.zg.project.wisdom.mapper.StockPhotoMapper;
import com.zg.project.wisdom.service.PhotoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

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

/**
 * 【照片上传服务实现】
 * 核心流程：
 *  1) 使用 LocalPhotoUtil 将文件保存到本地（按：photo/yyyy-MM-dd/）
 *  2) 拼接可访问URL（/photo/** 静态映射）
 *  3) 批量写入 stock_photo（只存一个 url）
 *  4) 返回 URL 列表
 */
@Service
public class PhotoServiceImpl implements PhotoService {

    @Resource
    private LocalPhotoUtil localPhotoUtil;

    @Resource
    private StockPhotoMapper stockPhotoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> uploadAndSave(List<MultipartFile> files,
                                      String photoType,
                                      String billNo,
                                      String xmMs,
                                      String documentType,
                                      String gysMc) {

        // 1. 基础校验
        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException("请选择要上传的图片");
        }
        if (!("0".equals(photoType) || "1".equals(photoType))) {
            throw new IllegalArgumentException("photoType 只能为 0(入库) 或 1(出库)");
        }
        if (StringUtils.isBlank(billNo)) {
            throw new IllegalArgumentException("billNo 不能为空");
        }
        if (StringUtils.isBlank(documentType)) {
            documentType = "default"; // 硬编码兜底
        }

        // 2. xmMs / gysMc 兜底处理
        String safeXmMs  = StringUtils.isBlank(xmMs)  ? "无" : xmMs;
        String safeGysMc = StringUtils.isBlank(gysMc) ? "无" : gysMc;

        // 3. 基础名（入库用供应商，出库用项目）
        final String baseName = localPhotoUtil.buildBaseName(photoType, billNo, safeXmMs, safeGysMc);

        try {
            // 4. 保存文件
            List<LocalPhotoUtil.SaveResult> saved = localPhotoUtil.saveBatch(files, documentType, baseName);

            // 5. 拼 URL + 入库对象
            List<String> urls = new ArrayList<>(saved.size());
            List<StockPhoto> rows = new ArrayList<>(saved.size());

            for (LocalPhotoUtil.SaveResult s : saved) {
                String url = ServletUriComponentsBuilder.fromCurrentContextPath()
                        .path("/photo/")
                        .path(s.getWebPath())
                        .toUriString();
                urls.add(url);

                StockPhoto p = new StockPhoto();
                p.setBillNo(billNo);
                p.setPhotoType(photoType);
                p.setFileName(s.getFileName());
                p.setUrl(url);
                rows.add(p);
            }

            if (!rows.isEmpty()) {
                stockPhotoMapper.batchInsert(rows);
            }

            return urls;
        } catch (Exception e) {
            throw new RuntimeException("上传/保存失败：" + e.getMessage(), e);
        }
    }

    @Override
    public List<String> listUrlsByBill(String billNo, String photoType) {
        if (StringUtils.isBlank(billNo)) {
            throw new IllegalArgumentException("billNo 不能为空");
        }
        return stockPhotoMapper.selectByBillNo(billNo,
                        StringUtils.isBlank(photoType) ? null : photoType)
                .stream()
                .map(StockPhoto::getUrl)
                .collect(Collectors.toList());
    }

    /**
     * 批量删除
     * @param urls 待删URL列表
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteByUrls(List<String> urls) {
        if (urls == null || urls.isEmpty()) {
            throw new IllegalArgumentException("urls 不能为空");
        }
        // 仅数据库软删
        int dbUpdated = stockPhotoMapper.softDeleteByUrls(urls);

        Map<String, Object> ret = new HashMap<String, Object>(2);
        ret.put("total", urls.size());
        ret.put("dbUpdated", dbUpdated);
        return ret;
    }
}
