package com.mcwl.web.controller.email;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.R;
import com.mcwl.system.domain.SysEmail;
import com.mcwl.system.domain.dto.AddEmailRes;
import com.mcwl.system.domain.dto.EditEmailRes;
import com.mcwl.system.domain.vo.EmailVo;
import com.mcwl.system.service.ISysEmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/***
 * 邮箱
 */
@RestController
@RequestMapping("email")
@RequiredArgsConstructor
@Api(tags = "邮箱")
public class EmailController {

    private final ISysEmailService sysEmailService;

    /**
     * 查询邮箱
     */
    @GetMapping("listEmail")
    @ApiOperation(value = "查询邮箱列表")
    public R<List<EmailVo>> listEmail() {

        List<SysEmail> sysEmailList = sysEmailService.list(new LambdaQueryWrapper<SysEmail>().orderByDesc(SysEmail::getCreateTime));

        return R.ok(BeanUtil.copyToList(sysEmailList, EmailVo.class));
    }

    @GetMapping("getEmail")
    @ApiOperation(value = "查询邮箱")
    public R<EmailVo> getEmail(@Valid @NotNull(message = "邮箱id不能为空") Long emailId) {

        SysEmail sysEmail = sysEmailService.getById(emailId);

        return R.ok(BeanUtil.toBean(sysEmail, EmailVo.class));
    }

    /**
     * 新建邮箱
     */
    @PostMapping("createEmail")
    @ApiOperation(value = "新建邮箱")
    public R<Object> createEmail(@RequestBody AddEmailRes addEmailRes) {

        sysEmailService.save(BeanUtil.toBean(addEmailRes, SysEmail.class));

        return R.ok();
    }

    /**
     * 删除邮箱
     */
    @GetMapping("deleteEmail")
    @ApiOperation(value = "删除邮箱")
    public R<Object> deleteEmail(@Valid @NotNull(message = "邮箱id不能为空") Long emailId) {

        List<SysEmail> sysEmailList = sysEmailService.list();
        if (sysEmailList.size() == 1) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "至少需要一个邮箱");
        }

        SysEmail sysEmail = sysEmailService.getById(emailId);
        if (Objects.isNull(sysEmail)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "邮箱不存在");
        }

        sysEmailService.removeById(emailId);
        return R.ok();
    }

    @PostMapping("updateEmail")
    @ApiOperation(value = "修改邮箱")
    public R<Object> updateEmail(@RequestBody EditEmailRes editEmailRes) {

        SysEmail sysEmail = sysEmailService.getById(editEmailRes.getId());
        if (Objects.isNull(sysEmail)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG, "邮箱不存在");
        }

        sysEmailService.updateById(BeanUtil.toBean(editEmailRes, SysEmail.class));
        return R.ok();
    }


}
