
package com.tmerclub.cloud.biz.controller.platform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.biz.constant.NotifyType;
import com.tmerclub.cloud.biz.dto.NotifyTemplateDTO;
import com.tmerclub.cloud.biz.model.NotifyTemplate;
import com.tmerclub.cloud.biz.service.NotifyTemplateService;
import com.tmerclub.cloud.biz.vo.NotifyTemplateVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.util.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author lhd
 * @date 2021-05-14 09:35:32
 */
@RestController("platformNotifyTemplateController")
@RequestMapping("/p/notifyTemplate")
@Tag(name = "platform-消息通知配置")
public class NotifyTemplateController {

    @Autowired
    private NotifyTemplateService notifyTemplateService;


    @GetMapping("/page")
    @Operation(summary = "获取列表", description = "分页获取列表")
    public ServerResponseEntity<PageVO<NotifyTemplateVO>> page(@Valid PageDTO pageDTO, NotifyTemplateDTO notifyTemplateDTO) {

        PageVO<NotifyTemplateVO> templatePage = notifyTemplateService.page(pageDTO, notifyTemplateDTO);
        if (CollectionUtils.isEmpty(templatePage.getList())) {
            return ServerResponseEntity.success();
        }
        for (NotifyTemplateVO template : templatePage.getList()) {
            List<Integer> templateList = getTemplateList(template.getNotifyTypes());
            template.setSms(false);
            template.setApp(false);
            template.setSub(false);
            for (Integer type : templateList) {
                template.setSms(Objects.equals(type, NotifyType.SMS.value()) || template.getSms());
                template.setApp(Objects.equals(type, NotifyType.APP.value()) || template.getApp());
                template.setSub(Objects.equals(type, NotifyType.MP.value()) || template.getSub());
            }
            template.setTemplateTypeList(templateList);
        }
        return ServerResponseEntity.success(templatePage);
    }

    @GetMapping
    @Operation(summary = "获取", description = "根据templateId获取")
    public ServerResponseEntity<NotifyTemplateVO> getByTemplateId(@RequestParam Long templateId) {
        NotifyTemplateVO templateVO = notifyTemplateService.getByTemplateId(templateId);
        templateVO.setTemplateTypeList(getTemplateList(templateVO.getNotifyTypes()));
        return ServerResponseEntity.success(templateVO);
    }

    @PutMapping
    @Operation(summary = "更新", description = "更新")
    public ServerResponseEntity<Void> update(@Valid @RequestBody NotifyTemplateDTO notifyTemplateDTO) {
        int count = notifyTemplateService.countBySendType(notifyTemplateDTO.getSendType(), notifyTemplateDTO.getTemplateId());
        if (count > 0) {
            // 已经存在当前消息类型的短信，请去进行修改操作
            throw new LuckException("已经存在当前消息类型的短信，请去进行修改操作");
        }
        if (CollUtil.isNotEmpty(notifyTemplateDTO.getTemplateTypeList())) {
            notifyTemplateDTO.setNotifyTypes(arrayChangeList(notifyTemplateDTO.getTemplateTypeList()));
        }
        NotifyTemplate notifyTemplate = BeanUtil.map(notifyTemplateDTO, NotifyTemplate.class);
        NotifyTemplateVO byTemplateId = notifyTemplateService.getByTemplateId(notifyTemplate.getTemplateId());
        notifyTemplate.setMsgType(byTemplateId.getMsgType());
        notifyTemplate.setSendType(byTemplateId.getSendType());
        notifyTemplateService.update(notifyTemplate);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除", description = "根据id删除")
    public ServerResponseEntity<Void> delete(@RequestParam Long templateId) {
        notifyTemplateService.deleteById(templateId);
        return ServerResponseEntity.success();
    }

    /**
     * 通过id状态变更
     *
     * @param templateId id
     * @return 是否修改成功
     */
    @DeleteMapping("/{templateId}")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long templateId) {
        NotifyTemplateVO templateVO = notifyTemplateService.getByTemplateId(templateId);
        templateVO.setStatus(templateVO.getStatus() == 1 ? 0 : 1);
        NotifyTemplate notifyTemplate = BeanUtil.map(templateVO, NotifyTemplate.class);
        notifyTemplateService.update(notifyTemplate);
        return ServerResponseEntity.success();
    }

    private List<Integer> getTemplateList(String templateTypes) {
        String[] templateTypeList = templateTypes.split(StrUtil.COMMA);
        List<Integer> templates = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (String templateStr : templateTypeList) {
            if (StrUtil.isBlank(templateStr)) {
                continue;
            }
            templates.add(Integer.valueOf(templateStr));
        }
        return templates;
    }

    private String arrayChangeList(List<Integer> templateTypeList) {
        StringBuilder templateTypes = new StringBuilder(Constant.INITIAL_CAPACITY);
        for (Integer templateType : templateTypeList) {
            templateTypes.append(templateType);
            templateTypes.append(StrUtil.COMMA);
        }
        templateTypes.deleteCharAt(templateTypes.length() - 1);
        return templateTypes.toString();
    }
}
