/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.controller;

import java.util.Date;

import javax.validation.Valid;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.constant.AppConstant;
import org.springblade.core.constant.RoleConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.message.model.MsgResponse;
import org.springblade.message.model.SmsInfo;
import org.springblade.message.sms.AliyunSmsTemplate;
import org.springblade.message.sms.QiniuSmsTemplate;
import org.springblade.message.sms.TencentSmsTemplate;
import org.springblade.modules.system.entity.Sms;
import org.springblade.modules.system.enums.SmsCategory;
import org.springblade.modules.system.service.normal.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;

import cn.hutool.extra.spring.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 短信配置表 控制器
 *
 * @author BladeX
 */
@RestController
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/sms")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
@Api(value = "短信配置表", tags = "短信配置表接口")
public class SmsController extends BladeController {

	@Autowired
	private SmsService smsService;

	/**
	 * 详情
	 */
	@GetMapping("/{id}")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "详情")
	public R<Sms> detail(@PathVariable Integer id) {
		return R.data(smsService.getById(id));
	}

	/**
	 * 自定义分页 短信配置表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入sms")
	public R<IPage<Sms>> page(Sms sms, Query query) {
		IPage<Sms> pages = smsService.page(Condition.getPage(query), Condition.getQueryWrapper(sms).lambda().orderByDesc(Sms::getId));
		return R.data(pages);
	}

	/**
	 * 新增或修改 短信配置表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增或修改", notes = "传入sms")
	public R<Integer> submit(@Valid @RequestBody Sms sms) {
		if(sms.getId() == null) {
			sms.setCreateTime(new Date());
			sms.setCreateUserId(getUser().getUserId());
		}
		sms.setTemplateParams(sms.getCategory().getFunction().apply(sms.getTemplateContent()));
		boolean ret = smsService.saveOrUpdate(sms);
		return ret ? R.data(sms.getId()) : R.fail("操作失败");
	}

	/**
	 * 删除 短信配置表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "删除", notes = "传入ids")
	public R<String> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(smsService.removeByIds(Func.toLongList(ids)));
	}
	
	/**
	 * 获取短信模版内容
	 */
	@PostMapping("/getTemplateContent")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "获取短信模版内容", notes = "传入sms")
	public R<String> templateContent(@RequestBody Sms sms) {
		SmsInfo smsInfo = SmsInfo.builder().accessKey(sms.getAccessKey()).secretKey(sms.getSecretKey()).signName(sms.getSignName())
				.regionId(sms.getRegionId()).appId(sms.getAppId()).templateId(sms.getTemplateId()).build();
		MsgResponse msgResponse = null;
		if(sms.getCategory() == SmsCategory.aliyun) { //阿里云
			msgResponse = SpringUtil.getBean(AliyunSmsTemplate.class).queryTemplateContent(smsInfo);
		}else if(sms.getCategory() == SmsCategory.qiniu) { //七牛云
			msgResponse = SpringUtil.getBean(QiniuSmsTemplate.class).queryTemplateContent(smsInfo);
		}else {
			msgResponse = SpringUtil.getBean(TencentSmsTemplate.class).queryTemplateContent(smsInfo);
		}
		return msgResponse.isSuccess() ? R.data(msgResponse.getMsg()) : R.fail(msgResponse.getMsg());
	}

	@PostMapping("/enable-sms")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "启用短息验证码模板", notes = "传入id")
	public R<Boolean> enableMsgTemplate(@ApiParam(value = "主键", required = true) @RequestParam Integer id){
		Sms sms = new Sms();
		sms.setStatus(1);
		sms.setId(id);
		boolean enable = smsService.updateById(sms);
		sms = new Sms();
		sms.setStatus(0);
		boolean update = smsService.update(sms,Wrappers.<Sms>lambdaUpdate()
				.eq(Sms::getBusinessClassify, 1)
				.ne(Sms::getId, id));
		return R.data(enable == update);
	}
}
