package com.xiaoniu.subsystem.system.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 com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoniu.common.core.result.R;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.subsystem.system.domain.SysDictData;
import com.xiaoniu.subsystem.system.domain.dto.SysDictDataDTO;
import com.xiaoniu.subsystem.system.domain.dto.SysDictDataPageDTO;
import com.xiaoniu.subsystem.system.domain.vo.SysDictDataVO;
import com.xiaoniu.subsystem.system.service.ISysDictDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUsername;

/**
 * 数据字典信息
 *
 * @author xiaoniu
 */
@RestController
@RequestMapping("/dict/data")
@Tag(name = "数据字典信息", description = "数据字典信息接口")
public class SysDictDataController {
    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "详情", description = "传入unit")
    public R<SysDictDataVO> detail(@Parameter(description = "主键", required = true) @RequestParam Long dictCode) {
        SysDictData detail = dictDataService.getById(dictCode);
        return R.data(BeanUtil.copy(detail, SysDictDataVO.class));
    }

    /**
     * 分页 数据字典信息
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入unit")
    public R<IPage<SysDictDataVO>> list(@Validated SysDictDataPageDTO dto) {
        IPage<SysDictData> pages = dictDataService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                new LambdaQueryWrapper<SysDictData>()
                        .orderByDesc(SysDictData::getCreateTime,SysDictData::getDictType,SysDictData::getDictSort)
                        .eq(null != dto.getDictCode(),SysDictData::getDictCode, dto.getDictCode())
                        .eq(StringUtils.isNotBlank(dto.getDictType()),SysDictData::getDictType, dto.getDictType())
                        .like(StringUtils.isNotBlank(dto.getDictValue()),SysDictData::getDictValue, dto.getDictValue())
                        .eq(StringUtils.isNotBlank(dto.getDictLabel()),SysDictData::getDictLabel, dto.getDictLabel())
                        .eq(StringUtils.isNotBlank(dto.getStatus()),SysDictData::getStatus, dto.getStatus()));
        return R.data(BeanUtil.copy(pages, SysDictDataVO.class));
    }


    /**
     * 新增 数据字典信息
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "新增", description = "传入unit")
    public R save(@Valid @RequestBody SysDictDataDTO dto) {
        long count = dictDataService.count(new LambdaQueryWrapper<SysDictData>()
                .eq(SysDictData::getDictType, dto.getDictType())
                .eq(StringUtils.isNotBlank(dto.getDictValue()), SysDictData::getDictValue, dto.getDictValue()));
        if (count > 0) {
            return R.fail("类型名称已存在");
        }
        List<SysDictData> list = dictDataService.list(new LambdaQueryWrapper<SysDictData>()
                .orderByDesc(SysDictData::getCreateTime,SysDictData::getDictSort,SysDictData::getDictLabel)
                .eq(SysDictData::getDictType, dto.getDictType()));
        if (CollectionUtils.isNotEmpty(list)){
            dto.setDictSort(Long.parseLong(list.get(0).getDictLabel()) + 1);
            dto.setDictLabel(String.valueOf(Integer.parseInt(list.get(0).getDictLabel()) + 1));
        }else{
            dto.setDictSort(1L);
            dto.setDictLabel("1");
        }
        return R.status(dictDataService.save(Objects.requireNonNull(BeanUtil.copy(dto, SysDictData.class))
                .setCreateBy(getUsername()).setCreateTime(new Date())));
    }

    /**
     * 修改 数据字典信息
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改", description = "传入unit")
    public R update(@Valid @RequestBody SysDictDataDTO dto) {
        long count = dictDataService.count(new LambdaQueryWrapper<SysDictData>()
                .eq(SysDictData::getDictType, dto.getDictType())
                .eq(StringUtils.isNotBlank(dto.getDictValue()), SysDictData::getDictValue, dto.getDictValue())
                .ne(SysDictData::getDictCode, dto.getDictCode()));
        if (count > 0) {
            return R.fail("类型名称已存在");
        }
        return R.status(dictDataService.updateById(Objects.requireNonNull(BeanUtil.copy(dto, SysDictData.class))
                .setUpdateBy(getUsername()).setUpdateTime(new Date())));
    }


    /**
     * 删除 数据字典信息
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除", description = "传入ids")
    public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String dictCodes) {
        return R.status(dictDataService.removeByIds(Arrays.stream(dictCodes.split(",")).toList()));
    }

}
