package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.store.annotation.TrackEvent;
import shop.alien.store.service.StorePriceService;
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.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用价目表
 *
 * @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;

    @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 (storePriceService.save(storePrice)) {
            return R.data(storePrice, "新增成功");
        }
        return R.fail("新增失败");
    }

    @ApiOperation("修改通用价目")
    @ApiOperationSupport(order = 2)
    @PostMapping("/update")
    public R<String> update(@RequestBody StorePrice storePrice) {
        log.info("StorePriceController.update?storePrice={}", storePrice);
        
        // 校验ID不能为空
        if (storePrice.getId() == null) {
            log.error("修改通用价目失败：ID不能为空");
            return R.fail("ID不能为空");
        }
        
        // 检查记录是否存在
        StorePrice existingPrice = storePriceService.getById(storePrice.getId());
        if (existingPrice == null) {
            log.error("修改通用价目失败：ID={} 的记录不存在", storePrice.getId());
            return R.fail("记录不存在，无法修改");
        }
        
        // 执行更新
        boolean result = storePriceService.updateById(storePrice);
        if (result) {
            return R.success("修改成功");
        }
        
        log.error("修改通用价目失败：ID={}，更新操作返回false", storePrice.getId());
        return R.fail("修改失败，请检查数据是否正确");
    }

    @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")
    })
    @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) {
        log.info("StorePriceController.getPage?pageNum={},pageSize={},storeId={},name={},status={},shelfStatus={}",
                pageNum, pageSize, storeId, name, status, shelfStatus);
        Page<StorePrice> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<StorePrice> queryWrapper = new LambdaQueryWrapper<>();
        if(null==origin){
            queryWrapper.eq(StorePrice::getShelfStatus, 1);
        }
        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);
        }
        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("操作失败");
    }


}

