package shop.alien.store.controller;

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.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreInfo;
import shop.alien.entity.store.StorePrice;
import shop.alien.mapper.StoreInfoMapper;
import shop.alien.mapper.StorePriceMapper;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.StorePriceService;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.util.encryption.Decrypt;
import shop.alien.util.encryption.Encrypt;
import shop.alien.util.encryption.JasyptEncryptorUtil;
import shop.alien.util.encryption.StandardAesUtil;
import shop.alien.util.encryption.properties.EncryptProperties;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通用价目表
 *
 * @author auto-generated
 * @since 2025-01-01
 */
@Slf4j
@Api(tags = {"通用价目表"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/store/price")
@RequiredArgsConstructor
public class StorePriceController {

    private final StorePriceService storePriceService;

    private final StoreInfoMapper storeInfoMapper;

    private final EncryptProperties encryptProperties;

    private final AiContentModerationUtil aiContentModerationUtil;

    private final StorePriceMapper storePriceMapper;

    @Value("${test1}")
    private String dbPassword;

    @ApiOperation("读取配置自动解密与手动加解密-测试接口")
    @GetMapping("/testConfig")
    public R<Map<String, Object>> testConfig(@RequestParam String salt, @RequestParam String text) {
        Map<String, Object> result = new HashMap<>();
        
        // 1. 测试配置文件的value自动解密（Jasypt 注入的结果）
        result.put("configPassword", dbPassword);

        // 2. 调用 utils 里的封装进行手动加解密逻辑
        try {
            String encrypted = JasyptEncryptorUtil.encode(salt, text);
            String decrypted = JasyptEncryptorUtil.decode(salt, encrypted);

            result.put("inputSalt", salt);
            result.put("inputText", text);
            result.put("manualEncrypted", encrypted);
            result.put("manualDecrypted", decrypted);
        } catch (Exception e) {
            return R.fail("加解密调试失败: " + e.getMessage());
        }

        return R.data(result, "调试成功");
    }

    @ApiOperation("AES加密-测试接口")
    @PostMapping("/aes/encrypt")
    public R<String> aesEncrypt(@RequestParam String text) {
        return R.data(StandardAesUtil.encrypt(text, encryptProperties.getKey(), encryptProperties.getIv()));
    }

    @ApiOperation("AES解密-测试接口")
    @PostMapping("/aes/decrypt")
    public R<String> aesDecrypt(@RequestParam String text) {
        return R.data(StandardAesUtil.decrypt(text, encryptProperties.getKey(), encryptProperties.getIv()));
    }

    @ApiOperation("AES加密请求体和解密响应体-测试接口")
    @ApiOperationSupport(order = 10)
    @PostMapping("/testEncryption")
    @Decrypt
    @Encrypt
    public R<StorePrice> testEncryption(@RequestBody StorePrice storePrice) {
        log.info("加解密测试接口接收数据: {}", storePrice);
        // 原样返回，测试响应加密
        return R.data(storePrice, "加解密测试成功");
    }


    @ApiOperation("新增通用价目")
    @ApiOperationSupport(order = 1)
    @PostMapping("/save")
    public R<StorePrice> save(@RequestBody StorePrice storePrice) {
        log.info("StorePriceController.save?storePrice={}", storePrice);
        
        // 参数验证
        if (storePrice == null) {
            log.error("新增通用价目失败：参数不能为空");
            return R.fail("参数不能为空");
        }
        
        try {
            // 保存数据
            boolean saveResult = storePriceService.save(storePrice);
            if (!saveResult) {
                log.error("新增通用价目失败：保存操作返回false");
                return R.fail("新增失败");
            }
            
            // MyBatis-Plus 的 save 方法会自动将生成的主键ID填充到对象中
            Integer savedId = storePrice.getId();
            if (savedId == null) {
                log.error("新增通用价目失败：保存后ID为空");
                return R.fail("新增失败：ID生成失败");
            }
            
            // 重新查询一次，确保返回包含完整数据（包括ID和所有数据库字段）的对象
            StorePrice savedPrice = storePriceService.getById(savedId);
            if (savedPrice == null) {
                log.error("新增通用价目失败：保存后查询不到数据，ID={}", savedId);
                return R.fail("新增失败：数据保存异常");
            }
            
            // 将状态置为"审核中"（0）
            LambdaUpdateWrapper<StorePrice> auditingWrapper = new LambdaUpdateWrapper<>();
            auditingWrapper.eq(StorePrice::getId, savedPrice.getId());
            auditingWrapper.set(StorePrice::getStatus, 0);
            auditingWrapper.set(StorePrice::getRejectionReason, null);
            auditingWrapper.set(StorePrice::getAuditTime, new Date());
            storePriceMapper.update(null, auditingWrapper);
            
            // 组装 AI 审核文本和图片
            StringBuilder textContent = new StringBuilder();
            if (StringUtils.isNotEmpty(storePrice.getName())) {
                textContent.append(storePrice.getName()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getDetailContent())) {
                textContent.append(storePrice.getDetailContent()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getExtraNote())) {
                textContent.append(storePrice.getExtraNote()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getReserveRule())) {
                textContent.append(storePrice.getReserveRule()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getUsageRule())) {
                textContent.append(storePrice.getUsageRule()).append(" ");
            }

            List<String> imageUrls = new ArrayList<>();

            if (StringUtils.isNotEmpty(storePrice.getImages())) {
                String[] urls = storePrice.getImages().split(",");
                for (String url : urls) {
                    if (StringUtils.isNotEmpty(url.trim())) {
                        String trimmedUrl = url.trim();
                        imageUrls.add(trimmedUrl);
                    }
                }
            }

            if (StringUtils.isNotEmpty(storePrice.getImageContent())) {
                String[] urls = storePrice.getImageContent().split(",");
                for (String url : urls) {
                    if (StringUtils.isNotEmpty(url.trim())) {
                        String trimmedUrl = url.trim();
                        imageUrls.add(trimmedUrl);
                    }
                }
            }

            // AI：价目图前端审；auditContent 仅 textContent，第二参固定 null
            if (StringUtils.isNotEmpty(textContent.toString()) || imageUrls.size() > 0) {
                AiContentModerationUtil.AuditResult auditResult = aiContentModerationUtil.auditContent(textContent.toString(), null);
//                boolean allPassed = (auditResult != null);
                
                LambdaUpdateWrapper<StorePrice> auditUpdateWrapper = new LambdaUpdateWrapper<>();
                auditUpdateWrapper.eq(StorePrice::getId, savedPrice.getId());
                auditUpdateWrapper.set(StorePrice::getRejectionReason, auditResult.getFailureReason());
                auditUpdateWrapper.set(StorePrice::getAuditTime, new Date());
                
                if (auditResult.isPassed()) {
                    // 审核通过 审核状态为1 上架状态为1 已上架
                    auditUpdateWrapper.set(StorePrice::getStatus, 1);
                    auditUpdateWrapper.set(StorePrice::getShelfStatus, 1);
                    log.info("AI审核通过，ID: {}", savedPrice.getId());
                } else {
                    // 审核拒绝 审核状态为2 上架状态为0 没有上下架状态
                    auditUpdateWrapper.set(StorePrice::getStatus, 2);
                    auditUpdateWrapper.set(StorePrice::getShelfStatus, 0);
                    log.info("AI审核拒绝，ID: {}", savedPrice.getId());
                }
                storePriceMapper.update(null, auditUpdateWrapper);
            }
            
            // 重新查询一次，返回最新的数据
            StorePrice finalPrice = storePriceService.getById(savedPrice.getId());
            if (finalPrice != null) {
                log.info("新增成功，返回ID: {}", finalPrice.getId());
                return R.data(finalPrice, "新增成功");
            }
            
            // 如果查询失败，返回保存后的对象（至少包含ID）
            log.warn("新增成功但最终查询失败，返回保存后的对象，ID: {}", savedId);
            return R.data(savedPrice, "新增成功");
            
        } catch (Exception e) {
            log.error("新增通用价目异常", e);
            return R.fail("新增失败：" + e.getMessage());
        }
    }

    @ApiOperation("修改通用价目")
    @ApiOperationSupport(order = 2)
    @PostMapping("/update")
    public R<String> update(@RequestBody StorePrice storePrice) {
        log.info("StorePriceController.update?storePrice={}", storePrice);
        
        // 参数验证
        if (storePrice == null) {
            log.error("修改通用价目失败：参数不能为空");
            return R.fail("参数不能为空");
        }
        
        // 校验ID不能为空
        if (storePrice.getId() == null) {
            log.error("修改通用价目失败：ID不能为空");
            return R.fail("ID不能为空");
        }
        
        try {
            // 检查记录是否存在
            StorePrice existingPrice = storePriceService.getById(storePrice.getId());
            if (existingPrice == null) {
                log.error("修改通用价目失败：ID={} 的记录不存在", storePrice.getId());
                return R.fail("记录不存在，无法修改");
            }
            
            // 执行更新
            boolean updateResult = storePriceService.updateById(storePrice);
            if (!updateResult) {
                log.error("修改通用价目失败：ID={}，更新操作返回false", storePrice.getId());
                return R.fail("修改失败，请检查数据是否正确");
            }
            
            // 查询更新后的记录
            StorePrice updatedPrice = storePriceService.getById(storePrice.getId());
            if (updatedPrice == null) {
                log.error("修改通用价目失败：更新后查询不到数据，ID={}", storePrice.getId());
                return R.fail("修改失败：数据更新异常");
            }
            
            // 将状态置为"审核中"（0）
            LambdaUpdateWrapper<StorePrice> auditingWrapper = new LambdaUpdateWrapper<>();
            auditingWrapper.eq(StorePrice::getId, updatedPrice.getId());
            auditingWrapper.set(StorePrice::getStatus, 0);
            auditingWrapper.set(StorePrice::getRejectionReason, null);
            auditingWrapper.set(StorePrice::getAuditTime, new Date());
            storePriceMapper.update(null, auditingWrapper);
            
            // 组装 AI 审核文本和图片
            StringBuilder textContent = new StringBuilder();
            if (StringUtils.isNotEmpty(storePrice.getName())) {
                textContent.append(storePrice.getName()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getDetailContent())) {
                textContent.append(storePrice.getDetailContent()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getExtraNote())) {
                textContent.append(storePrice.getExtraNote()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getReserveRule())) {
                textContent.append(storePrice.getReserveRule()).append(" ");
            }
            if (StringUtils.isNotEmpty(storePrice.getUsageRule())) {
                textContent.append(storePrice.getUsageRule()).append(" ");
            }

            List<String> imageUrls = new ArrayList<>();

            if (StringUtils.isNotEmpty(storePrice.getImages())) {
                String[] urls = storePrice.getImages().split(",");
                for (String url : urls) {
                    if (StringUtils.isNotEmpty(url.trim())) {
                        String trimmedUrl = url.trim();
                        imageUrls.add(trimmedUrl);
                    }
                }
            }

            if (StringUtils.isNotEmpty(storePrice.getImageContent())) {
                String[] urls = storePrice.getImageContent().split(",");
                for (String url : urls) {
                    if (StringUtils.isNotEmpty(url.trim())) {
                        String trimmedUrl = url.trim();
                        imageUrls.add(trimmedUrl);
                    }
                }
            }

            // AI：价目图前端审；auditContent 仅 textContent，第二参固定 null
            if (StringUtils.isNotEmpty(textContent.toString()) || imageUrls.size() > 0) {
                AiContentModerationUtil.AuditResult auditResult = aiContentModerationUtil.auditContent(textContent.toString(), null);
//                boolean allPassed = (auditResult != null);
                
                LambdaUpdateWrapper<StorePrice> auditUpdateWrapper = new LambdaUpdateWrapper<>();
                auditUpdateWrapper.eq(StorePrice::getId, updatedPrice.getId());
                auditUpdateWrapper.set(StorePrice::getRejectionReason, auditResult.getFailureReason());
                auditUpdateWrapper.set(StorePrice::getAuditTime, new Date());
                
                if (auditResult.isPassed()) {
                    // 审核通过 审核状态为1 上架状态为1 已上架
                    auditUpdateWrapper.set(StorePrice::getStatus, 1);
                    auditUpdateWrapper.set(StorePrice::getShelfStatus, 1);
                    log.info("AI审核通过，ID: {}", updatedPrice.getId());
                } else {
                    // 审核拒绝 审核状态为2 上架状态为0 没有上下架状态
                    auditUpdateWrapper.set(StorePrice::getStatus, 2);
                    auditUpdateWrapper.set(StorePrice::getShelfStatus, 0);
                    log.info("AI审核拒绝，ID: {}", updatedPrice.getId());
                }
                storePriceMapper.update(null, auditUpdateWrapper);
            }
            
            return R.success("修改成功");
            
        } catch (Exception e) {
            log.error("修改通用价目异常", e);
            return R.fail("修改失败：" + e.getMessage());
        }
    }

    @TrackEvent(
            eventType = "PRICE_VIEW",
            eventCategory = "PRICE",
            storeId = "#{result.data.storeId}",
            targetId = "#{#id}",
            targetType = "PRICE"
    )
    @ApiOperation("根据ID查询通用价目")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "通用价目id", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getById")
    public R<StorePrice> getById(@RequestParam Integer id) {
        log.info("StorePriceController.getById?id={}", id);
        StorePrice storePrice = storePriceService.getById(id);
        if (storePrice != null) {
            List<StorePrice> storePrices = storePriceService.list(new LambdaQueryWrapper<StorePrice>().eq(StorePrice :: getStoreId, storePrice.getStoreId()));
            storePrice.setStorePriceList(storePrices);
            //查询门店 获取 门店电话和门店名称
            StoreInfo storeInfo = storeInfoMapper.selectOne(new LambdaQueryWrapper<StoreInfo>().eq(StoreInfo :: getId, storePrice.getStoreId()));
            if(storeInfo != null){
                storePrice.setStorePhone(storeInfo.getStoreTel());
                storePrice.setStoreName(storeInfo.getStoreName());
            }
            return R.data(storePrice);
        }
        return R.fail("查询失败");
    }

    @ApiOperation("删除通用价目")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "通用价目id", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/delete")
    public R<String> delete(@RequestParam Integer id) {
        log.info("StorePriceController.delete?id={}", id);
        if (storePriceService.removeById(id)) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @ApiOperation("批量删除通用价目")
    @ApiOperationSupport(order = 5)
    @PostMapping("/deleteBatch")
    public R<String> deleteBatch(@RequestBody List<Integer> ids) {
        log.info("StorePriceController.deleteBatch?ids={}", ids);
        if (storePriceService.removeByIds(ids)) {
            return R.success("批量删除成功");
        }
        return R.fail("批量删除失败");
    }

    @ApiOperation("分页查询通用价目")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "名字", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：0-待审核 1-审核通过 2-审核拒绝", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "shelfStatus", value = "上下架状态：1-上架，2-下架", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "startCreatedTime", value = "创建时间开始（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endCreatedTime", value = "创建时间结束（yyyy-MM-dd HH:mm:ss）", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/getPage")
    public R<IPage<StorePrice>> getPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer storeId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer shelfStatus,
            @RequestParam(required = false) Integer origin,
            @RequestParam(required = false) String startCreatedTime,
            @RequestParam(required = false) String endCreatedTime) {
        log.info("StorePriceController.getPage?pageNum={},pageSize={},storeId={},name={},status={},shelfStatus={},startCreatedTime={},endCreatedTime={}",
                pageNum, pageSize, storeId, name, status, shelfStatus, startCreatedTime, endCreatedTime);
        
        // 解析时间参数
        Date startTime = null;
        Date endTime = null;
        if (startCreatedTime != null && !startCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                startTime = sdf.parse(startCreatedTime);
            } catch (Exception e) {
                log.warn("解析开始时间失败: {}", startCreatedTime, e);
            }
        }
        if (endCreatedTime != null && !endCreatedTime.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endTime = sdf.parse(endCreatedTime);
            } catch (Exception e) {
                log.warn("解析结束时间失败: {}", endCreatedTime, e);
            }
        }
        
        Page<StorePrice> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<StorePrice> queryWrapper = new LambdaQueryWrapper<>();
        if(null==origin){
            queryWrapper.eq(StorePrice::getShelfStatus, 1);
        }else if(origin==0){
            queryWrapper.in(StorePrice::getShelfStatus, 0,1,2);
        }else{
            queryWrapper.eq(StorePrice::getShelfStatus, origin);
        }
        if (storeId != null) {
            queryWrapper.eq(StorePrice::getStoreId, storeId);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(StorePrice::getName, name);
        }
        if (status != null) {
            queryWrapper.eq(StorePrice::getStatus, status);
        }
        if (shelfStatus != null) {
            queryWrapper.eq(StorePrice::getShelfStatus, shelfStatus);
        }
        // 创建时间范围查询
        if (startTime != null) {
            queryWrapper.ge(StorePrice::getCreatedTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(StorePrice::getCreatedTime, endTime);
        }
        queryWrapper.orderByDesc(StorePrice::getCreatedTime);
        IPage<StorePrice> result = storePriceService.page(page, queryWrapper);
        return R.data(result);
    }

    @ApiOperation("查询所有通用价目")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：0-待审核 1-审核通过 2-审核拒绝", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "shelfStatus", value = "上下架状态：1-上架，2-下架", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/list")
    public R<List<StorePrice>> list(
            @RequestParam(required = false) Integer storeId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer shelfStatus) {
        log.info("StorePriceController.list?storeId={},status={},shelfStatus={}", storeId, status, shelfStatus);
        LambdaQueryWrapper<StorePrice> queryWrapper = new LambdaQueryWrapper<>();
        if (storeId != null) {
            queryWrapper.eq(StorePrice::getStoreId, storeId);
        }
        if (status != null) {
            queryWrapper.eq(StorePrice::getStatus, status);
        }
        if (shelfStatus != null) {
            queryWrapper.eq(StorePrice::getShelfStatus, shelfStatus);
        }
        queryWrapper.orderByDesc(StorePrice::getCreatedTime);
        List<StorePrice> list = storePriceService.list(queryWrapper);
        return R.data(list);
    }

    @ApiOperation("上下架操作：1-上架，2-下架")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "通用价目id", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "shelfStatus", value = "上下架状态：1-上架，2-下架", dataType = "Integer", paramType = "query", required = false)
    })
    @PostMapping("/changeShelfStatus")
    public R<String> changeShelfStatus(@RequestParam("id") Integer id, @RequestParam("shelfStatus") Integer shelfStatus) {
        log.info("StorePriceController.changeShelfStatus?id={},shelfStatus={}", id, shelfStatus);
        if (shelfStatus == null || (shelfStatus != 1 && shelfStatus != 2)) {
            return R.fail("上下架状态不合法（只能为1或2）");
        }
        StorePrice storePrice = new StorePrice();
        storePrice.setId(id);
        storePrice.setShelfStatus(shelfStatus);
        if (storePriceService.updateById(storePrice)) {
            return R.success("操作成功");
        }
        return R.fail("操作失败");
    }

    @ApiOperation("审核操作：0-待审核 1-审核通过 2-审核拒绝")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "通用价目id", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "状态：0-待审核 1-审核通过 2-审核拒绝", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "rejectionReason", value = "拒绝原因", dataType = "String", paramType = "query")
    })
    @PostMapping("/changeStatus")
    public R<String> changeStatus(@RequestParam Integer id,
                                   @RequestParam Integer status,
                                   @RequestParam(required = false) String rejectionReason) {
        log.info("StorePriceController.changeStatus?id={},status={},rejectionReason={}", id, status, rejectionReason);
        if (status == null || (status != 0 && status != 1 && status != 2)) {
            return R.fail("状态不合法（只能为0、1或2）");
        }
        StorePrice storePrice = new StorePrice();
        storePrice.setId(id);
        storePrice.setStatus(status);
        if (status == 2 && rejectionReason != null) {
            storePrice.setRejectionReason(rejectionReason);
        }
        if (storePriceService.updateById(storePrice)) {
            return R.success("操作成功");
        }
        return R.fail("操作失败");
    }


}

