package com.jiayue.ssi.controller;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiayue.ssi.annotation.OperateLog;
import com.jiayue.ssi.annotation.PreventReplay;
import com.jiayue.ssi.backenum.ApproveOperaterEnum;
import com.jiayue.ssi.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.constant.ApproveConstants;
import com.jiayue.ssi.constant.CustomException;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.entity.SysApprove;
import com.jiayue.ssi.entity.SysParameter;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.service.SysApproveService;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.util.List;

/**
 * 审核接口
 *
 * @author xsl
 * @since 2023/03/13
 */
@RestController
@RequestMapping("/sysApproveController")
@Slf4j
public class SysApproveController {
    @Autowired
    SysApproveService sysApproveService;
    @Autowired
    SysUserService sysUserService;

    /**
     * 获取用户分页信息
     *
     * @return 用户信息
     */
    @GetMapping(value = "/getAll")
    @PreAuthorize("@ss.hasPermi('approveManager:approve:list')")
    @OperateLog(title = "审核管理", businessType = BusinessType.QUERY, auditType = AuditType.SYS,operdesc = "查询审核列表")
    @PreventReplay
    public ResponseVO getAll(String currentPage, String pageSize, String approveStatus, String approveResult) throws CustomException {
        try {
            Integer cp;
            if (StringUtils.isNotEmpty(currentPage)) {
                if (NumberUtil.isInteger(currentPage)){
                    cp = Integer.parseInt(currentPage);
                }
                else{
                    return ResponseVO.fail("currentPage不是整数！");
                }
            }
            else{
                return ResponseVO.fail("currentPage不能是空！");
            }

            Integer ps;
            if (StringUtils.isNotEmpty(pageSize)) {
                if (NumberUtil.isInteger(pageSize)){
                    ps = Integer.parseInt(pageSize);
                }
                else{
                    return ResponseVO.fail("pageSize不是整数！");
                }
            }
            else{
                return ResponseVO.fail("pageSize不能是空！");
            }

            QueryWrapper<SysApprove> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(approveStatus)) {
                wrapper.eq("approve_status", approveStatus);
            }
            if (StringUtils.isNotEmpty(approveResult)) {
                wrapper.eq("approve_result", approveResult);
            }
            Page<SysApprove> result = sysApproveService.page(new Page<>(cp, ps), wrapper);
            List<SysApprove> records = result.getRecords();
            //遍历对象数组的方法
            records.forEach(
                    record -> {
                        if (record.getModuleName().equals(ApproveConstants.MODULE_NAME_USER)){
                            if (record.getOperation().equals(String.valueOf(ApproveOperaterEnum.INSERT.getCode()))){
                                // 敏感数据先解密
                                String idcard = SM2CryptUtils.decrypt(record.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String nickname = SM2CryptUtils.decrypt(record.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String mailbox = SM2CryptUtils.decrypt(record.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String phonenumber = SM2CryptUtils.decrypt(record.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                // 脱密处理
                                idcard = DesensitizedUtil.idCardNum(idcard,5,2);
                                nickname = DesensitizedUtil.chineseName(nickname);
                                mailbox = DesensitizedUtil.email(mailbox);
                                phonenumber = DesensitizedUtil.mobilePhone(phonenumber);
                                // 封装新增操作
                                StringBuffer parameterContent = new StringBuffer("");
                                parameterContent.append("账号："+record.getUsername());
                                parameterContent.append(",身份证号码："+idcard);
                                if ("0".equals(record.getUsertype())){
                                    parameterContent.append(",用户类型：管理员");
                                }
                                else {
                                    parameterContent.append(",用户类型：业务用户");
                                }

                                parameterContent.append(",姓名："+nickname);
                                parameterContent.append(",邮箱："+mailbox);
                                parameterContent.append(",手机号码："+phonenumber);
                                if (record.getExpDate()==null){

                                }
                                else {
                                    parameterContent.append(",账号有效期："+DateFormatUtils.format(record.getExpDate(),"yyyy-MM-dd"));
                                }
                                record.setParameterContent(parameterContent.toString());
                            }
                            else if (record.getOperation().equals(String.valueOf(ApproveOperaterEnum.UPDATE.getCode()))){
                                // 根据用户主键ID获取用户表里原有数据
                                StringBuffer parameterContent = new StringBuffer("");
                                String oldInfo = record.getParameterContent();
                                SysUser oldSysUser = JSONUtil.toBean(oldInfo,SysUser.class);
                                parameterContent.append("修改前内容：\n");
                                String oldidcard = SM2CryptUtils.decrypt(oldSysUser.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String oldnickname = SM2CryptUtils.decrypt(oldSysUser.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String oldmailbox = SM2CryptUtils.decrypt(oldSysUser.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String oldphonenumber = SM2CryptUtils.decrypt(oldSysUser.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                // 脱密处理
                                String tmidcard = DesensitizedUtil.idCardNum(oldidcard,5,2);
                                String tmnickname = DesensitizedUtil.chineseName(oldnickname);
                                String tmailbox = DesensitizedUtil.email(oldmailbox);
                                String tmphonenumber = DesensitizedUtil.mobilePhone(oldphonenumber);
                                parameterContent.append("账号："+oldSysUser.getUsername());
                                parameterContent.append(",身份证号码："+tmidcard);
                                if ("0".equals(oldSysUser.getUsertype())){
                                    parameterContent.append(",用户类型：管理员");
                                }
                                else {
                                    parameterContent.append(",用户类型：业务用户");
                                }
                                parameterContent.append(",姓名："+tmnickname);
                                parameterContent.append(",邮箱："+tmailbox);
                                parameterContent.append(",手机号码："+tmphonenumber);
                                if (oldSysUser.getExpDate()==null){
                                }
                                else {
                                    parameterContent.append(",账号有效期："+DateFormatUtils.format(oldSysUser.getExpDate(),"yyyy-MM-dd"));
                                }
                                parameterContent.append("\n");

                                // 审批表里的记录敏感数据先解密
                                String idcard = SM2CryptUtils.decrypt(record.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String nickname = SM2CryptUtils.decrypt(record.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String mailbox = SM2CryptUtils.decrypt(record.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String phonenumber = SM2CryptUtils.decrypt(record.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                // 脱密处理
                                idcard = DesensitizedUtil.idCardNum(idcard,5,2);
                                nickname = DesensitizedUtil.chineseName(nickname);
                                mailbox = DesensitizedUtil.email(mailbox);
                                phonenumber = DesensitizedUtil.mobilePhone(phonenumber);
                                parameterContent.append("修改后内容：\n");
                                parameterContent.append("账号："+record.getUsername());
                                parameterContent.append(",身份证号码："+idcard);
                                if ("0".equals(record.getUsertype())){
                                    parameterContent.append(",用户类型：管理员");
                                }
                                else {
                                    parameterContent.append(",用户类型：业务用户");
                                }

                                parameterContent.append(",姓名："+nickname);
                                parameterContent.append(",邮箱："+mailbox);
                                parameterContent.append(",手机号码："+phonenumber);
                                if (record.getExpDate()==null){

                                }
                                else {
                                    parameterContent.append(",账号有效期："+DateFormatUtils.format(record.getExpDate(),"yyyy-MM-dd"));
                                }
                                record.setParameterContent(parameterContent.toString());
                            }
                            else if (record.getOperation().equals(String.valueOf(ApproveOperaterEnum.DELETE.getCode()))){
                                // 敏感数据先解密
                                String idcard = SM2CryptUtils.decrypt(record.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String nickname = SM2CryptUtils.decrypt(record.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String mailbox = SM2CryptUtils.decrypt(record.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                String phonenumber = SM2CryptUtils.decrypt(record.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY);
                                // 脱密处理
                                idcard = DesensitizedUtil.idCardNum(idcard,5,2);
                                nickname = DesensitizedUtil.chineseName(nickname);
                                mailbox = DesensitizedUtil.email(mailbox);
                                phonenumber = DesensitizedUtil.mobilePhone(phonenumber);
                                // 封装新增操作
                                StringBuffer parameterContent = new StringBuffer("");
                                parameterContent.append("账号："+record.getUsername());
                                parameterContent.append(",身份证号码："+idcard);
                                if ("0".equals(record.getUsertype())){
                                    parameterContent.append(",用户类型：管理员");
                                }
                                else {
                                    parameterContent.append(",用户类型：业务用户");
                                }

                                parameterContent.append(",姓名："+nickname);
                                parameterContent.append(",邮箱："+mailbox);
                                parameterContent.append(",手机号码："+phonenumber);
                                if (record.getExpDate()==null){

                                }
                                else {
                                    parameterContent.append(",账号有效期："+DateFormatUtils.format(record.getExpDate(),"yyyy-MM-dd"));
                                }
                                record.setParameterContent(parameterContent.toString());
                            }
//                            else if (record.getOperation().equals(String.valueOf(ApproveOperaterEnum.RELOCK.getCode()))){
//                                // 敏感数据先解密
//                                String idcard = SM2CryptUtils.decrypt(record.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY);
//                                String nickname = SM2CryptUtils.decrypt(record.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY);
//                                String mailbox = SM2CryptUtils.decrypt(record.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY);
//                                String phonenumber = SM2CryptUtils.decrypt(record.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY);
//                                // 脱密处理
//                                idcard = DesensitizedUtil.idCardNum(idcard,5,2);
//                                nickname = DesensitizedUtil.chineseName(nickname);
//                                mailbox = DesensitizedUtil.email(mailbox);
//                                phonenumber = DesensitizedUtil.mobilePhone(phonenumber);
//                                // 封装新增操作
//                                StringBuffer parameterContent = new StringBuffer("");
//                                parameterContent.append("账号："+record.getUsername());
//                                parameterContent.append(",身份证号码："+idcard);
//                                if ("0".equals(record.getUsertype())){
//                                    parameterContent.append(",用户类型：管理员");
//                                }
//                                else {
//                                    parameterContent.append(",用户类型：业务用户");
//                                }
//
//                                parameterContent.append(",姓名："+nickname);
//                                parameterContent.append(",邮箱："+mailbox);
//                                parameterContent.append(",手机号码："+phonenumber);
//                                if (record.getExpDate()==null){
//
//                                }
//                                else {
//                                    parameterContent.append(",账号有效期："+DateFormatUtils.format(record.getExpDate(),"yyyy-MM-dd"));
//                                }
//                                record.setParameterContent(parameterContent.toString());
//                            }
                        }
                    }
            );
            return ResponseVO.success(result);
        } catch (Exception e) {
            throw new CustomException("获取所有审核异常", e);
        }
    }

    /**
     * 审批结果提交
     */
    @PostMapping(value = "/submitApprove")
    @OperateLog(title = "审核管理", businessType = BusinessType.UPDATE, auditType = AuditType.SYS,operdesc = "审核结果提交")
    @PreAuthorize("@ss.hasPermi('approveManager:approve:submitApprove')")
    @PreventReplay
    public ResponseVO submitApprove(@RequestBody SysApprove sysApprove) throws CustomException {
        try {
            SysApprove oldSysApprove = sysApproveService.getById(sysApprove.getId());
            if (sysApprove.getVersion().intValue() != oldSysApprove.getVersion().intValue()){
                return ResponseVO.fail("此数据被操作过，自动刷新列表后请重试操作！");
            }
            sysApproveService.submitApprove(sysApprove);
            return ResponseVO.success("审核提交成功");
        } catch (Exception e) {
            throw new CustomException("审核提交异常", e);
        }
    }
}
