package com.bonus.canteen.core.account.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.account.domain.bo.AccOperationHistory;
import com.bonus.canteen.core.account.domain.param.AccOperationQueryParam;
import com.bonus.canteen.core.account.mapper.AccOperationHistoryMapper;
import com.bonus.canteen.core.account.service.AccOperationHistoryService;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.houqin.utils.SM4EncryptUtils;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser;
import com.github.pagehelper.page.PageMethod;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AccOperationHistoryServiceImpl extends ServiceImpl<AccOperationHistoryMapper, AccOperationHistory> implements AccOperationHistoryService {
   @Resource
   private RemoteUserService remoteUserService;
   public List<AccOperationHistory> selectAccOperationHistory(AccOperationQueryParam param) {
      String encryptedSearchValue = SM4EncryptUtils.sm4Encrypt(param.getSearchValue());
      List<AccOperationHistory> operationRecordList = this.baseMapper.queryPageAccOperationRecord(param, encryptedSearchValue);
      if(CollUtil.isNotEmpty(operationRecordList)) {
         for(AccOperationHistory history : operationRecordList) {
            history.setPhone(SM4EncryptUtils.sm4Decrypt(history.getPhone()));
         }
      }
      return operationRecordList;
   }

   public void addAccOperationHistory(Long userId, Integer type) {
      AjaxResult userResult = remoteUserService.getInfo(userId , SecurityConstants.INNER);
      if(Objects.nonNull(userResult)) {
         SysUser sysUser = JSONObject.parseObject(JSON.toJSONString(userResult.get(AjaxResult.DATA_TAG)), SysUser.class);
         AccOperationHistory accOperationRecord = new AccOperationHistory();
         accOperationRecord.setType(type);
         accOperationRecord.setUserId(userId);
         accOperationRecord.setUserName(sysUser.getUserName());
         accOperationRecord.setPhone(sysUser.getPhonenumber());
         accOperationRecord.setCreateBy(SecurityUtils.getUsername());
         accOperationRecord.setCreateTime(LocalDateTime.now());
         this.baseMapper.insert(accOperationRecord);
      }
   }
}
