package com.haha.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haha.entity.dto.NewProductApplyQueryDTO;
import com.haha.entity.dto.NewProductApplySubmitDTO;
import com.haha.common.enums.ApplyStatus;
import com.haha.common.exception.BusinessException;
import com.haha.entity.NewProductApply;
import com.haha.mapper.NewProductApplyMapper;
import com.haha.sdk.HahaClient;
import com.haha.sdk.exception.HahaException;
import com.haha.service.NewProductApplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新品申请服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NewProductApplyServiceImpl extends ServiceImpl<NewProductApplyMapper, NewProductApply> implements NewProductApplyService {

    private final HahaClient hahaClient;

    @Override
    public IPage<NewProductApply> getPage(int page, int pageSize, NewProductApplyQueryDTO queryDTO) {
        LambdaQueryWrapper<NewProductApply> wrapper = new LambdaQueryWrapper<>();
        
        // 条形码模糊查询
        if (StringUtils.hasText(queryDTO.getBarcode())) {
            wrapper.like(NewProductApply::getBarcode, queryDTO.getBarcode());
        }
        
        // 商品名称模糊查询
        if (StringUtils.hasText(queryDTO.getName())) {
            wrapper.like(NewProductApply::getName, queryDTO.getName());
        }
        
        // 状态筛选
        if (queryDTO.getStatus() != null) {
            wrapper.eq(NewProductApply::getStatus, queryDTO.getStatus());
        }
        
        // 分类筛选
        if (StringUtils.hasText(queryDTO.getCategory())) {
            wrapper.eq(NewProductApply::getCategory, queryDTO.getCategory());
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc(NewProductApply::getCreateTime);
        
        return page(new Page<>(page, pageSize), wrapper);
    }

    // ========== DTO → Entity 转换 ==========

    private NewProductApply dtoToEntity(NewProductApplySubmitDTO dto) {
        NewProductApply entity = new NewProductApply();
        entity.setName(dto.getProductName());
        entity.setBarcode(dto.getBarcode());
        entity.setCategory(dto.getCategory());
        entity.setBrand(dto.getBrand());
        entity.setUnit(dto.getUnit());
        entity.setSpecification(dto.getSpecification());
        entity.setPrice(dto.getPrice());
        entity.setCost(dto.getCostPrice());
        entity.setDescription(dto.getDescription());
        entity.setProductType(dto.getProductType());
        entity.setStandard(dto.getStandard());
        entity.setStickerNum(dto.getStickerNum());
        entity.setLength(dto.getLength());
        entity.setWidth(dto.getWidth());
        entity.setHeight(dto.getHeight());
        entity.setExhibitHeight(dto.getExhibitHeight());
        entity.setColumns(dto.getColumns());
        entity.setNumbers(dto.getNumbers());
        entity.setReason(dto.getReason());

        // 拆分逗号分隔的图片字符串到9个独立字段
        if (StringUtils.hasText(dto.getImages())) {
            String[] urls = dto.getImages().split(",");
            if (urls.length > 0) entity.setImageUrl(urls[0].trim());
            if (urls.length > 1) entity.setImageUrl2(urls[1].trim());
            if (urls.length > 2) entity.setImageUrl3(urls[2].trim());
            if (urls.length > 3) entity.setImageUrl4(urls[3].trim());
            if (urls.length > 4) entity.setImageUrl5(urls[4].trim());
            if (urls.length > 5) entity.setOriginalImageUrl1(urls[5].trim());
            if (urls.length > 6) entity.setOriginalImageUrl2(urls[6].trim());
            if (urls.length > 7) entity.setOriginalImageUrl3(urls[7].trim());
            if (urls.length > 8) entity.setOriginalImageUrl4(urls[8].trim());
        }

        return entity;
    }

    // ========== DTO 版本的服务方法 ==========

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitApply(NewProductApplySubmitDTO dto, Long applicantId, String applicantName) {
        NewProductApply apply = dtoToEntity(dto);
        return submitApply(apply, applicantId, applicantName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveDraft(NewProductApplySubmitDTO dto, Long applicantId, String applicantName) {
        NewProductApply apply = dtoToEntity(dto);
        apply.setStatus(ApplyStatus.DRAFT.getCode());
        apply.setApplicantId(applicantId);
        apply.setApplicantName(applicantName);
        apply.setCreateTime(LocalDateTime.now());
        save(apply);
        return apply.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateApply(Long id, NewProductApplySubmitDTO dto) {
        NewProductApply apply = dtoToEntity(dto);
        apply.setId(id);
        apply.setUpdateTime(LocalDateTime.now());
        updateById(apply);
        log.info("新品申请更新成功，ID: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitApply(NewProductApply apply, Long applicantId, String applicantName) {
        // 设置申请人信息
        apply.setApplicantId(applicantId);
        apply.setApplicantName(applicantName);
        apply.setStatus(ApplyStatus.PENDING.getCode());
        apply.setCreateTime(LocalDateTime.now());
        apply.setSubmitTime(LocalDateTime.now());
        
        // 先保存到本地数据库
        save(apply);
        
        try {
            // 构建哈哈平台API请求参数
            Map<String, String> params = new HashMap<>();
            params.put("type", apply.getProductType() != null ? String.valueOf(apply.getProductType()) : "0");
            params.put("name", apply.getName());
            params.put("bar_code", apply.getBarcode() != null ? apply.getBarcode() : "");
            params.put("standard", apply.getStandard() != null ? String.valueOf(apply.getStandard()) : "1");
            
            // 设置图片，使用URL方式
            params.put("img_type", "url");
            params.put("pic_1", apply.getImageUrl() != null ? apply.getImageUrl() : "");
            params.put("pic_2", apply.getImageUrl2() != null ? apply.getImageUrl2() : "");
            params.put("pic_3", apply.getImageUrl3() != null ? apply.getImageUrl3() : "");
            params.put("pic_4", apply.getImageUrl4() != null ? apply.getImageUrl4() : "");
            params.put("pic_5", apply.getImageUrl5() != null ? apply.getImageUrl5() : "");
            params.put("ori_pic_1", apply.getOriginalImageUrl1() != null ? apply.getOriginalImageUrl1() : "");
            params.put("ori_pic_2", apply.getOriginalImageUrl2() != null ? apply.getOriginalImageUrl2() : "");
            params.put("ori_pic_3", apply.getOriginalImageUrl3() != null ? apply.getOriginalImageUrl3() : "");
            params.put("ori_pic_4", apply.getOriginalImageUrl4() != null ? apply.getOriginalImageUrl4() : "");
            
            // 规格信息
            if (StringUtils.hasText(apply.getSpecification())) {
                params.put("specification", apply.getSpecification());
            }
            
            // 学习机号
            if (StringUtils.hasText(apply.getStickerNum())) {
                params.put("sticker_num", apply.getStickerNum());
            }
            
            // 尺寸信息
            if (apply.getLength() != null) {
                params.put("length", String.valueOf(apply.getLength()));
            }
            if (apply.getWidth() != null) {
                params.put("width", String.valueOf(apply.getWidth()));
            }
            if (apply.getHeight() != null) {
                params.put("height", String.valueOf(apply.getHeight()));
            }
            if (apply.getExhibitHeight() != null) {
                params.put("exhibit_height", String.valueOf(apply.getExhibitHeight()));
            }
            if (apply.getColumns() != null) {
                params.put("columns", String.valueOf(apply.getColumns()));
            }
            if (apply.getNumbers() != null) {
                params.put("numbers", String.valueOf(apply.getNumbers()));
            }
            
            // 价格信息
            if (apply.getPrice() != null) {
                params.put("retail_price", apply.getPrice().toString());
            }
            if (apply.getCost() != null) {
                params.put("cost_price", apply.getCost().toString());
            }
            
            // 备注
            if (StringUtils.hasText(apply.getReason())) {
                params.put("remark", apply.getReason());
            }
            
            // 扩展字段
            if (StringUtils.hasText(apply.getProductExtends())) {
                params.put("product_extends", apply.getProductExtends());
            }
            
            // 调用哈哈平台新品申请API
            Map<String, Object> result = hahaClient.getGoodsApi().applyNew(params);
            
            // 更新工单编号
            String hahaApplyId = (String) result.get("id");
            apply.setHahaApplyId(hahaApplyId);
            apply.setUpdateTime(LocalDateTime.now());
            updateById(apply);
            
            log.info("新品申请提交成功，本地ID: {}, 哈哈工单ID: {}", apply.getId(), hahaApplyId);
            
        } catch (HahaException e) {
            log.error("新品申请提交到哈哈平台失败: {}", e.getMessage());
            // 提交失败，更新状态为待提交
            apply.setStatus(ApplyStatus.DRAFT.getCode());
            apply.setUpdateTime(LocalDateTime.now());
            updateById(apply);
            throw new BusinessException(500, "新品申请提交失败: " + e.getMessage());
        }
        
        return apply.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByCallback(String hahaApplyId, Integer status, String hahaCode, String rejectReason) {
        LambdaUpdateWrapper<NewProductApply> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(NewProductApply::getHahaApplyId, hahaApplyId)
               .set(NewProductApply::getStatus, status)
               .set(NewProductApply::getAuditTime, LocalDateTime.now())
               .set(NewProductApply::getUpdateTime, LocalDateTime.now());
        
        if (StringUtils.hasText(hahaCode)) {
            wrapper.set(NewProductApply::getHahaCode, hahaCode);
        }
        
        if (StringUtils.hasText(rejectReason)) {
            wrapper.set(NewProductApply::getRejectReason, rejectReason);
        }
        
        update(wrapper);
        log.info("新品申请状态更新，工单ID: {}, 状态: {}", hahaApplyId, status);
    }

    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总申请数
        long total = count();
        stats.put("total", total);
        
        // 审核中
        long pending = count(new LambdaQueryWrapper<NewProductApply>()
                .eq(NewProductApply::getStatus, ApplyStatus.PENDING.getCode()));
        stats.put("pending", pending);
        
        // 已通过
        long passed = count(new LambdaQueryWrapper<NewProductApply>()
                .eq(NewProductApply::getStatus, ApplyStatus.APPROVED.getCode()));
        stats.put("passed", passed);
        
        // 已拒绝
        long rejected = count(new LambdaQueryWrapper<NewProductApply>()
                .eq(NewProductApply::getStatus, ApplyStatus.REJECTED.getCode()));
        stats.put("rejected", rejected);
        
        return stats;
    }

    @Override
    public Map<String, Object> checkBarcodeInTotalList(String barcode) {
        try {
            // 调用哈哈平台API查询商品总库
            Map<String, Object> result = hahaClient.getGoodsApi().getTotalList(1, 1, barcode, null, null, null);

            if (result != null) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("data");
                if (list != null && !list.isEmpty()) {
                    return list.get(0);
                }
            }
            return null;
        } catch (HahaException e) {
            log.error("查询商品总库失败: {}", e.getMessage());
            return null;
        }
    }

    @Override
    public Map<String, Object> getNewGoodsInfo(String code, String id) {
        try {
            Map<String, Object> result = hahaClient.getGoodsApi().getNewGoodsInfo(code, id);
            log.info("主动查询新品申请状态 - code: {}, id: {}, result: {}", code, id, result);
            return result;
        } catch (HahaException e) {
            log.error("查询新品申请信息失败 - code: {}, id: {}, error: {}", code, id, e.getMessage());
            return null;
        }
    }
}
