package com.rf.psychological.miniapp.browse.controller;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.miniapp.browse.model.BrowseEntity;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.rf.psychological.miniapp.browse.service.BrowseService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * @Description:浏览记录接口
 * @Author: mimang
 * @Date: 2023/5/17
 */
@Slf4j
@RestController
@RequestMapping("/browse")
@Api(tags = "最近浏览管理")
public class BrowseController extends BaseController {

    @Autowired
    private BrowseService  browseService;

    @SafetyProcess
    @ApiOperation(value = "搜索保存",notes = "json字符串形式传参(加密)，" +
            "data参数中包括(必传)：userId:用户id,businessId:量表或者认知任务id,flag:量表或者认知任务id,type:类型0量表1认知任务")
    @PostMapping("/save")
    public Result save(@RequestBody String paramJson){
        try {
            String paramData = AesEncryptUtils.decrypt(JSONObject.parseObject(paramJson).getString("data"));
            log.info(paramData);
            if (StringUtils.isEmpty(paramData)){
                return fail(null,"参数不能为空");
            }
            BrowseEntity entity = JSONObject.parseObject(paramData,BrowseEntity.class);
            //先判断有没有
            BrowseEntity browseEntity = browseService.findByUserIdAndBusinessId(entity.getUserId(),entity.getBusinessId());
            if (browseEntity == null){
                entity = browseService.save(entity);

            }else {
                entity =browseService.update(browseEntity);
            }
            return success(entity);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }

    @SafetyProcess
    @ApiOperation(value = "查询浏览记录",notes = " userId:用户id,page:页码,pageSize:数量")
    @GetMapping("/query")
    public Result queryByOpenId(@RequestParam String userId,@RequestParam int page,@RequestParam int pageSize){
        try {
            Page<BrowseEntity> entities = browseService.queryByUserId(userId,page,pageSize);
            return success(entities);
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }

    @SafetyProcess
    @ApiOperation(value = "删除所有浏览记录",notes = "id:用户id")
    @GetMapping("/deleteAll")
    public Result deleteByUserId(@RequestParam String id){
        try {
            browseService.deleteByUserId(id);
            return success();
        }catch (Exception e){
            e.printStackTrace();
            return fail("操作失败");
        }
    }
}
