package com.sunda.spmsweb.ordercontroller;


import com.alibaba.fastjson.JSONObject;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialDeliveryBoards;
import com.sunda.spmsorder.entity.MaterialSap;
import com.sunda.spmsorder.entity.vo.MaterialDeliveryBoardsQueryVO;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsorder.service.IMailService;
import com.sunda.spmsorder.service.IMaterialSapService;
import com.sunda.spmsorder.service.IMaterialSpmsService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.util.ExportExcel;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmsweb.util.MD5Utils;
import com.sunda.spmswms.entity.SapDeliveryNote;
import com.sunda.spmswms.service.ISapDeliveryNoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

/**
 * <p>
 * 邮件发送
 * </p>
 *
 * @author 黄志聪
 * @since 2023-04-23
 */
@RestController
@RequestMapping("/mailSpms")
@Api(tags = "SPMS 邮件接口", description = "发送邮件")
public class MailController {
	
	@Autowired
	private IMailService mailService;

    @Autowired
    ISpmsUserService iSpmsUserService;

	@RequestMapping("/sendMailCode")
    @ApiOperation(value = "发送邮件", httpMethod = "POST")
    public ResponseResult sendMailCode(@RequestBody JSONObject doc) {
        try {
            String userKey = UUID.randomUUID().toString() +"-"+ (new Date()).getTime();
            String userId = doc.get("userId")==null?"":doc.get("userId").toString().trim();
            String email = doc.get("email")==null?"":doc.get("email").toString().trim();

            int secon = mailService.checkGenerateSecond(userId,email);
            if(secon>3){
                return ResponseResult.error("请求数据失败").add("error", "5分钟内获取验证码邮件不能超过三次！The verification code cannot be obtained more than three times within five minutes！");
            }
            SpmsUser user = iSpmsUserService.getByUserEmail(userId,email);
            if(user!=null){
                if("0".equals(user.getSpmsStatus())){//已冻结
                    return ResponseResult.error("请求数据失败").add("error", "用户账号已锁定不可用，如需解锁请联系管理员!The user account is locked and unavailable. If you need to unlock it, please contact the administrator!");
                }else{
                    String code = mailService.generateCodeToEmail(userKey,userId);
                    String content = "尊敬的SPMS系统用户：您好！\n" +
                            "Dear SPMS Users: Hello!\n" +
                            "  您正在进行找回密码？操作，请在验证码输入框中输入："+code+"，以完成操作。\n" +
                            "  Are you get back password? To complete the operation, enter "+code+"，in the verification code text box.\n" +
                            "  注意：您此次验证码有效期为3分钟，请确保是本人操作，不要把验证码泄露给其他人，否则后果自负。\n" +
                            "  Note: The validity period of your verification code is 3 minutes. Please make sure it is operated by yourself. Do not disclose the verification code to others, or you will be liable for the consequences.\n" +
                            "此为SPMS系统邮件，请勿回复！\n" +
                            "This SPMS email, Please do not reply!\n" +
                            "【SPMS系统】运维团队\n"+
                            "【SPMS System】Implement Maintain Team\n";
                    mailService.sendSimpleMail(email, "", "SPMS系统验证码", content);
                }
            }else{
                return ResponseResult.error("请求数据失败").add("error", "用户账号或者邮箱错误，请重新输入！User account or email is incorrect, please re-enter!");
            }

            Map result = new HashMap();
            result.put("userKey",userKey );
            return ResponseResult.success().add("userKey", userKey);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/getMailCode")
    @ApiOperation(value = "查询邮件验证码并修改密码", httpMethod = "POST")
    public ResponseResult getMailCode(@RequestBody JSONObject doc) {
        try {
            String valiteCode = doc.get("valiteCode")==null?"":doc.get("valiteCode").toString().trim();
            String userKey = doc.get("userKey")==null?"":doc.get("userKey").toString().trim();
            String password = doc.get("password")==null?"":doc.get("password").toString().trim();
            if(StringUtils.isBlank(valiteCode)){
                return ResponseResult.error("请求数据失败").add("error", "验证码不能为空！The verification code cannot be empty!");
            }
            String userId = mailService.checkCodeByUser(userKey,valiteCode);
            if(StringUtils.isNotBlank(userId)){//验证码正确，并拿到缓存的用户账号
                if(StringUtils.isBlank(password)){
                    return ResponseResult.error("请求数据失败").add("error", "请输入新密码！Please enter your new password!");
                }
                ResponseResult respon = iSpmsUserService.updatePassword(userId, MD5Utils.encrypt(userId, password));
                if(200==respon.getCode()){//密码修改成功
                    SpmsUser user = iSpmsUserService.getByUserId(userId);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String date = sdf.format(new Date());
                    String content = "尊敬的SPMS系统用户：您好！\n" +
                            "Dear SPMS Users: Hello!\n" +
                            "  您在"+date+"提交找回密码请求，您已经成功重置密码了，请使用修改后的密码重新登录SPMS系统！\n" +
                            "  Did you submit get back password? request on "+date+". You have successfully reset the password, please use the changed password to log in the SPMS system again!\n" +
                            "  注意：密码作为私密的信息请勿泄露给其他人，以免帐号被盗造成不必要的损失。\n" +
                            "  Note: As private information, do not disclose the password to others, so as to avoid unnecessary losses caused by account theft.\n" +
                            "此为SPMS系统邮件，请勿回复！\n" +
                            "This SPMS email, Please do not reply!\n" +
                            "【SPMS系统】运维团队\n"+
                            "【SPMS System】Implement Maintain Team\n";
                    mailService.sendSimpleMail(user.getEmail(), "", "SPMS系统消息", content);
                }else{
                    return ResponseResult.error("请求数据失败").add("error", "密码修改异常，请联系管理员！Password change exception, please contact administrator!");
                }

            }
            return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
	

}
