package com.yinlihupo.enlish.service.controller;

import com.yinlihupo.enlish.service.domain.dataobject.UnitDO;
import com.yinlihupo.enlish.service.model.vo.unit.AddUnitReqVO;
import com.yinlihupo.enlish.service.model.vo.unit.DeleteUnitReqVO;
import com.yinlihupo.enlish.service.model.vo.unit.FindUnitListReqVO;
import com.yinlihupo.enlish.service.model.vo.unit.FindUnitListRspVO;
import com.yinlihupo.enlish.service.service.UnitService;
import com.yinlihupo.framework.biz.operationlog.aspect.ApiOperationLog;
import com.yinlihupo.framework.common.response.PageResponse;
import com.yinlihupo.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
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.List;

@RequestMapping("/unit/")
@RestController
@Slf4j
public class UnitController {

    @Resource
    private UnitService unitService;

    @PostMapping("/list")
    @ApiOperationLog(description = "查询单元")
    public PageResponse<FindUnitListRspVO> list(@RequestBody FindUnitListReqVO findUnitListReqVO) {
        Integer page = findUnitListReqVO.getPage();
        Integer size = findUnitListReqVO.getSize();
        Integer unitDOListCount = unitService.findUnitDOListCount();

        List<UnitDO> unitDOList = unitService.findUnitDOList(page, size);
        List<FindUnitListRspVO> findUnitListRspVOS = unitDOList.stream().map(unitDO -> FindUnitListRspVO.builder()
                .id(unitDO.getId())
                .title(unitDO.getTitle())
                .version(unitDO.getVersion())
                .createAt(unitDO.getCreateAt())
                .build()
        ).toList();

        return PageResponse.success(findUnitListRspVOS, page, unitDOListCount, size);
    }

    @PostMapping("/add")
    @ApiOperationLog(description = "添加单元")
    public Response<Void> add(@RequestBody AddUnitReqVO addUnitReqVO) {
        try {
            unitService.add(addUnitReqVO);

            return Response.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @PostMapping("/delete")
    @ApiOperationLog(description = "删除单元")
    public Response<String> delete(@RequestBody DeleteUnitReqVO deleteUnitReqVO) {
        try {
            unitService.delete(deleteUnitReqVO.getId());

            return Response.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
}
