package com.aircraft.modules.article.controller;

import com.aircraft.modules.article.domain.CpMaterial;
import com.aircraft.modules.article.domain.dto.CpMaterialDTO;
import com.aircraft.modules.article.mapper.CpMaterialMapper;
import com.aircraft.modules.system.mapper.UserMapper;
import com.aircraft.modules.article.service.CpMaterialService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.aircraft.utils.SecurityUtils.getCurrentUserId;

/**
 * <p>
 * 素材表 前端控制器（仅操作cp_material表）
 * </p>
 *
 * @author cli
 * @since 2025-07-11
 */
@Api(tags = "系统：素材管理")
@RestController
@RequestMapping("/cpMaterial")
public class CpMaterialController {
    private static final Logger LOG = LoggerFactory.getLogger(CpMaterialController.class);

    @Autowired
    private CpMaterialService materialService;

    @Autowired
    private CpMaterialMapper materialMapper;
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "分页查询素材（支持模糊查询）", notes = "分页查询素材，仅根据素材名称进行模糊查询")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "搜索关键词，用于模糊查询素材名称", paramType = "query")
    })
    public ResponseEntity<IPage<CpMaterial>> findByPage(
            final Page<CpMaterial> page,
            @RequestParam(required = false) String keyword) {
        try {
            QueryWrapper<CpMaterial> wrapper = new QueryWrapper<>();
            // 仅对素材名称进行模糊查询
            if (keyword != null && !keyword.isEmpty()) {
                wrapper.like("name", keyword);
            }
            wrapper.eq("del_flag", 0);  // 只查询未删除的素材
            wrapper.orderByDesc("create_time");//按时间倒序排序
            IPage<CpMaterial> records = materialService.page(page, wrapper);
            return new ResponseEntity<>(records, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("分页查询素材时出错", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @ApiOperation(value = "查询单个素材", notes = "根据ID查询cp_material表中的素材，已删除数据返回不存在")
    @ApiImplicitParam(name = "id", value = "素材ID", required = true, paramType = "path", dataType = "int")
    @GetMapping("/{id}")
    public ResponseEntity<CpMaterial> getById(@PathVariable Integer id) {
        try {
            // 查询素材（包含逻辑删除判断）
            CpMaterial material = materialMapper.selectById(id);
            if (material == null || material.getDelFlag() == 1) {
                return ResponseEntity.notFound().build(); // 不存在或已删除
            }
            return ResponseEntity.ok(material);
        } catch (Exception e) {
            LOG.error("查询素材失败（ID：{}）", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "添加素材", notes = "向cp_material表插入新素材，自动填充创建时间和创建人")
    @PostMapping
    public ResponseEntity<CpMaterial> add(@Valid @RequestBody CpMaterialDTO material) {
        try {
            CpMaterial cpMaterial = new CpMaterial();
            BeanUtils.copyProperties(material, cpMaterial);
            // 填充默认值
            cpMaterial.setCreateTime(LocalDateTime.now());
            cpMaterial.setUpdateTime(LocalDateTime.now());
            cpMaterial.setDelFlag(0); // 默认未删除
//            // 设置创建人ID
//            Long creatorId = getCurrentUserId();
//            String name = userMapper.getNameById(creatorId);
//            cpMaterial.setCreateBy(name); // 假设表中有creator_id字段

            // 保存素材
            materialService.save(cpMaterial);
            // 返回创建的素材（包含自增ID）
            return ResponseEntity
                    .created(URI.create("/cpMaterial/" + cpMaterial.getId()))
                    .body(cpMaterial);
        } catch (DataIntegrityViolationException e) {
            LOG.error("添加素材失败：数据完整性冲突", e);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            LOG.error("添加素材失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "修改素材", notes = "根据ID更新cp_material表中的素材，仅更新未删除的数据")
    @PutMapping
    public ResponseEntity<CpMaterial> update(@Valid @RequestBody CpMaterial material) {
        try {
            // 校验ID
            if (material.getId() == null) {
                return ResponseEntity.badRequest().body(null);
            }

            // 检查素材是否存在且未删除
            CpMaterial existing = materialService.getById(material.getId());
            if (existing == null || existing.getDelFlag() == 1) {
                return ResponseEntity.notFound().build();
            }
            // 更新素材（不修改创建时间和删除标记）
            material.setCreateTime(existing.getCreateTime()); // 保留原创建时间
            material.setUpdateTime(LocalDateTime.now());
            material.setDelFlag(existing.getDelFlag()); // 保留删除状态
            materialService.updateById(material);
            return ResponseEntity.ok(material);
        } catch (Exception e) {
            LOG.error("修改素材失败（ID：{}）", material.getId(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @ApiOperation(value = "删除素材", notes = "逻辑删除：将cp_material表中的del_flag设为1")
    @ApiImplicitParam(name = "id", value = "素材ID", required = true, paramType = "path", dataType = "int")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Integer id) {
        try {
            // 检查素材是否存在
            CpMaterial material = materialService.getById(id);
            if (material == null || material.getDelFlag() == 1) {
                return ResponseEntity.notFound().build();
            }

            // 逻辑删除：更新del_flag=1
            material.setDelFlag(1);
            materialService.updateDelFlagById(material.getId(), material.getDelFlag());
            // 3. 删除成功，返回成功信息
            Map<String, Object> success = new HashMap<>();
            success.put("code", 200);
            success.put("msg", "删除成功");
            return ResponseEntity.ok(success);
        } catch (Exception e) {
            LOG.error("删除素材失败（ID：{}）", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}