package com.xjrsoft.module.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.system.dto.AddDictionaryDetailDto;
import com.xjrsoft.module.system.dto.DictionaryDetailListDto;
import com.xjrsoft.module.system.dto.DictionaryDetailPageDto;
import com.xjrsoft.module.system.dto.UpdateDictionaryDetailDto;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.system.service.IDictionarydetailService;
import com.xjrsoft.module.system.vo.DictionaryDetailListVo;
import com.xjrsoft.module.system.vo.DictionaryDetailPageVo;
import com.xjrsoft.module.system.vo.DictionaryDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 数据字典详情 前端控制器
 * </p>
 *
 * @author tzx
 * @since 2022-03-17
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/dictionary-detail")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/dictionary-detail",tags = "数据字典详情")
@AllArgsConstructor
public class DictionarydetailController {

    private IDictionarydetailService dictionarydetailService;

    @GetMapping
    @ApiOperation(value = "获取当前数据字典详情（不分页）")
    public R list(DictionaryDetailListDto dto) {
        LambdaQueryWrapper<DictionaryDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getName()), DictionaryDetail::getName, dto.getName());
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getCode()), DictionaryDetail::getCode, dto.getCode());
        if (StrUtil.isNotEmpty(dto.getPCode())) {
            DictionaryDetail dictionaryDetail = dictionarydetailService.getOne(Wrappers.lambdaQuery(DictionaryDetail.class).eq(DictionaryDetail::getCode, dto.getPCode()));
            if (dictionaryDetail != null) {
                queryWrapper.eq(DictionaryDetail::getPId, dictionaryDetail.getId());
            }
        }

        queryWrapper.eq(ObjectUtil.isNotEmpty(dto.getItemId()) && dto.getItemId() != 0, DictionaryDetail::getItemId, dto.getItemId());
        queryWrapper.select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetailListVo.class).contains(x.getProperty()));
        queryWrapper.orderByAsc(DictionaryDetail::getSortCode);
        List<DictionaryDetail> list = dictionarydetailService.list(queryWrapper);
        return R.ok(BeanUtil.copyToList(list, DictionaryDetailListVo.class));
    }

    @GetMapping("/page")
    @ApiOperation(value = "获取当前数据字典详情（分页）")
    public R page(DictionaryDetailPageDto dto){
        LambdaQueryWrapper<DictionaryDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getName()),DictionaryDetail::getName,dto.getName())
                    .eq(StrUtil.isNotEmpty(dto.getCode()),DictionaryDetail::getCode,dto.getCode())
                    .and(StrUtil.isNotEmpty(dto.getKeyword()), wrapper -> wrapper.like(DictionaryDetail::getName, dto.getKeyword()).or().like(DictionaryDetail::getCode, dto.getKeyword()))
                    .eq(ObjectUtil.isNotEmpty(dto.getItemId()) && dto.getItemId() != 0,DictionaryDetail::getItemId,dto.getItemId())
                    .select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetailPageVo.class).contains(x.getProperty()))
                    .orderByAsc(DictionaryDetail::getSortCode);

        IPage<DictionaryDetail> page = dictionarydetailService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<DictionaryDetailPageVo> pageOutput = ConventPage.getPageOutput(page, DictionaryDetailPageVo.class);
        return R.ok(pageOutput);
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取当前数据字典详情的详情")
    public R info(@RequestParam Long id){
        DictionaryDetail dictionaryDetail = dictionarydetailService.getById(id);
        if (dictionaryDetail == null) {
            R.error("找不到此字典详情！");
        }
        return R.ok(BeanUtil.toBean(dictionaryDetail, DictionaryDetailVo.class));
    }

    @PostMapping
    @ApiOperation(value = "新增数据字典详情")
    public R add(@Valid @RequestBody AddDictionaryDetailDto dto){

        long count = dictionarydetailService.count(Wrappers.<DictionaryDetail>query().lambda().eq(DictionaryDetail::getItemId, dto.getItemId())
                .and(wrapper -> wrapper.eq(DictionaryDetail::getName, dto.getName())
                        .or().eq(DictionaryDetail::getValue, dto.getValue())
                        .or().eq(DictionaryDetail::getCode, dto.getCode())));
        if(count > 0){
            return R.error("字典名称或者编码已经存在！");
        }

        DictionaryDetail dictionaryDetail = BeanUtil.toBean(dto, DictionaryDetail.class);

        boolean isSuccess = dictionarydetailService.save(dictionaryDetail);
        if (isSuccess) dictionarydetailService.loadCaches();
        return R.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改数据字典详情")
    public R update(@Valid @RequestBody UpdateDictionaryDetailDto dto){
        long count = dictionarydetailService.count(Wrappers.<DictionaryDetail>query().lambda()
                .eq(DictionaryDetail::getItemId, dto.getItemId())
                .ne(DictionaryDetail::getId,dto.getId())
                .and(wrapper -> wrapper.eq(DictionaryDetail::getName, dto.getName())
                        .or().eq(DictionaryDetail::getValue, dto.getValue())
                        .or().eq(DictionaryDetail::getCode, dto.getCode())));
        if(count > 0){
            return R.error("字典名称、编码或值已经存在！");
        }
        DictionaryDetail dictionaryItem = BeanUtil.toBean(dto, DictionaryDetail.class);

        boolean isSuccess = dictionarydetailService.updateById(dictionaryItem);
        if (isSuccess) dictionarydetailService.loadCaches();
        return R.ok(isSuccess);
    }

    @DeleteMapping
    @ApiOperation(value = "删除数据字典详情")
    public R delete(@RequestBody List<Long> ids){
        return R.ok(dictionarydetailService.removeBatchByIds(ids));
    }
}
