package com.aiup.api.controller;


import com.aiup.service.domain.R;
import com.aiup.service.domain.query.ConfigListQuery;
import com.aiup.service.domain.query.IdQuery;
import com.aiup.service.domain.query.TemplateListQuery;
import com.aiup.service.entity.TemplateInfo;
import com.aiup.service.entity.UserConfig;
import com.aiup.service.service.TemplateInfoService;
import com.aiup.service.service.UserConfigService;
import com.aiup.service.utils.LoginUserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Api(tags = "配置相关接口")
@RestController
@RequestMapping("/v1/config")
@RequiredArgsConstructor
public class UserConfigController {

    @Autowired
    private UserConfigService userConfigService;

    @ApiOperation(value = "根据模板类型获取模板列表")
    @PostMapping("/getListByType")
    public R<List<UserConfig>> getListByType(@RequestBody @Validated ConfigListQuery query) {
        query.setUserId(LoginUserUtils.getLoginUser().getUserId());
        List<UserConfig> list = userConfigService.getListByType(query);
        return R.ok(list);
    }
    @ApiOperation(value = "新建一个配置")
    @PostMapping("/create")
    public R<UserConfig> create(@RequestBody @Validated UserConfig query) {
        query.setIsDeleted(0);
        query.setCreateTime(new Date());
        query.setUserId(LoginUserUtils.getLoginUser().getUserId());
        query.setUpdateTime(null);
        return R.ok(userConfigService.insert(query));
    }



    @ApiOperation(value = "删除配置")
    @PostMapping("/remove")
    public R<Boolean> remove(@RequestBody IdQuery query) {
        query.setUserId(LoginUserUtils.getLoginUser().getUserId());
        PageRequest pageRequest = PageRequest.of(0,200);
        UserConfig templateInfo = new UserConfig();
        templateInfo.setIsDeleted(0);
        templateInfo.setUserId(query.getUserId());
        templateInfo.setConfigId(query.getRecordId());
        List<UserConfig> list = userConfigService.queryByPage(templateInfo, pageRequest).getContent();
        if(list == null || list.size()<=0){
            return R.error("配置不存在");
        }
        UserConfig temp = list.get(0);
        temp.setIsDeleted(1);
        temp.setUpdateTime(new Date());
        userConfigService.update(temp);
        return R.ok(true);
    }

}
