package com.shanghaichengdi.ghjgitem.controller;

import com.shanghaichengdi.ghjgitem.domain.SysDataShareUser;
import com.shanghaichengdi.ghjgitem.service.SysDatashareUserService;
import com.shanghaichengdi.ghjgitem.util.AppUtils;
import com.shanghaichengdi.ghjgitem.vo.response.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/sysDataShareManage")
@Slf4j
public class SysDataShareManageController extends CommonController {

  @Resource
  SysDatashareUserService sysDatashareUserService;

  @PostMapping("/createUser")
  public ReturnMsg createUser(@RequestParam @Validated String clientName) {
    List<SysDataShareUser> datashareUserList = sysDatashareUserService.list();
    Integer maxId = 0;
    if(!datashareUserList.isEmpty()){
      List<SysDataShareUser> sortedList = datashareUserList.stream()
          .sorted((o1, o2) -> o2.getId().compareTo(o1.getId()))
          .collect(Collectors.toList());
      maxId = sortedList.get(0).getId();
    }
    for(SysDataShareUser item : datashareUserList){
      if(item.getClient().equals(clientName)){
        log.info("clientName:"+clientName+"已存在");
        return ReturnMsg.success("client为"+clientName+"的账号已存在!");
      }
    }

    String appId = AppUtils.getAppId();
    String appSecret = AppUtils.getAppSecret(appId);
    SysDataShareUser user = new SysDataShareUser();
    user.setId(maxId+1);
    user.setKey(appId);
    user.setSecret(appSecret);
    user.setClient(clientName);
    user.setIsvalid(1L);
    user.setCreatetime(new Date());
    boolean result = sysDatashareUserService.save(user);
    if(result){
      return ReturnMsg.success("创建成功!");
    }else{
      return ReturnMsg.error("创建失败!");
    }
  }

}
