package com.dtok.api;


import cn.dev33.satoken.stp.StpUtil;
import com.dtok.entity.Account;
import com.dtok.entity.CommonItem;
import com.dtok.entity.Devices;
import com.dtok.entity.Script;
import com.dtok.framework.exception.AuthenticateException;
import com.dtok.framework.exception.BizExceptionEnum;
import com.dtok.framework.exception.BusinessException;
import com.dtok.framework.response.ResponseData;
import com.dtok.repository.AccountRepository;
import com.dtok.repository.CommonItemRepository;
import com.dtok.repository.DevicesRepository;
import com.dtok.repository.ScriptRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class AppApi {

    @Autowired
    DevicesRepository devicesRepository;

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    CommonItemRepository commonItemRepository;


    @Autowired
    ScriptRepository scriptRepository;

    @GetMapping("/checkRegister/{token}/{androidId}")
    public ResponseData checkRegister(@PathVariable String token, @PathVariable String androidId) {
        String username = (String) StpUtil.getLoginIdByToken(token);

        if (!StpUtil.getTokenValue().equals(token)) {
            throw new AuthenticateException(401, "非法注册");
        }
        if (!StringUtils.hasLength(username)) {
            throw new AuthenticateException(401, "登录信息失效");
        }

        Account account = accountRepository.findUserByUsername(username);

        Devices devices = devicesRepository.findFirstByAccountAndAndroidId(account.getId(), androidId);

        if (Objects.isNull(devices)) {
            throw new BusinessException(BizExceptionEnum.DEVICE_NOT_REGISTER);
        } else {
            return ResponseData.success(devices);
        }
    }


    @GetMapping("/getCommonItem")
    public ResponseData getCommonItem(@RequestParam(defaultValue = "com.ss.android.ugc.aweme", required = false,
            value = "app") String app) {
        Account account = ((Account) StpUtil.getSession().get("loginUser"));

        List<CommonItem> commonItemList = commonItemRepository.findAllByAppAndIsDefaultOrCreatedAt(app, true, account.getId());
        Map<String, List<CommonItem>> resultMap = commonItemList.stream().collect(
                Collectors.groupingBy(CommonItem::getType));
        return ResponseData.success(resultMap);
    }


    @GetMapping("/checkLogin")
    public ResponseData checkLogin() {
//        Account account = ((Account) StpUtil.getSession().get("loginUser"));
        Account account = accountRepository.findUserByUsername((String) StpUtil.getLoginId());

        Timestamp timestamp = new Timestamp((new Date()).getTime());
        if (!Objects.isNull(account.getExpireAt()) && account.getExpireAt().before(timestamp)) {
            StpUtil.logoutByTokenValue(StpUtil.getTokenValue());
            throw new AuthenticateException(BizExceptionEnum.ACCOUNT_EXPIRE);
        }

        return ResponseData.success(accountRepository.getFirstByUsername((String) StpUtil.getLoginId()));
    }

    @PostMapping("/addCommonItem")
    public ResponseData addCommonItem(@RequestParam(defaultValue = "com.ss.android.ugc.aweme", required = false,
            value = "app") String app, @RequestParam("type") String type, @RequestParam("content") String content) {
        CommonItem commonItem = new CommonItem();
        commonItem.setApp(app);
        commonItem.setCreatedTime(new Date());
        commonItem.setContent(content);
        commonItem.setType(type);
        commonItem.setCreatedAt(((Account) StpUtil.getSession().get("loginUser")).getId());
        commonItem.setIsDefault(false);
        commonItemRepository.save(commonItem);

        return ResponseData.success("添加成功");
    }


    @PostMapping("/getExecScript/{uuid}")
    public ResponseData getExecScript(@RequestParam(defaultValue = "com.ss.android.ugc.aweme", required = false,
            value = "app") String app, @RequestParam("module") String module, @PathVariable String uuid) {
        Account account = accountRepository.getUserLoginEntity((String) StpUtil.getLoginId());

        if (!StringUtils.hasLength(uuid)) {
            throw new NullPointerException("没有找到设备");
        }

        if (!StringUtils.hasLength(module)) {
            throw new NullPointerException("没有此功能");
        }

        Devices devices = devicesRepository.findFirstByUuid(uuid);

        Timestamp timestamp = new Timestamp((new Date()).getTime());
        if (!Objects.isNull(account.getExpireAt()) && account.getExpireAt().before(timestamp)) {
            StpUtil.logoutByTokenValue(StpUtil.getTokenValue());
            throw new AuthenticateException(BizExceptionEnum.ACCOUNT_EXPIRE);
        }

        if (!account.getId().equals(devices.getAccount())) {
            throw new NullPointerException("权限错误");
        }

        Script script = scriptRepository.findFirstByModuleAndApp(module, app);

        if (Objects.isNull(script)) {
            throw new NullPointerException("没有此功能");
        }
        script.setCallCount(script.getCallCount() + 1);
        scriptRepository.save(script);

        return ResponseData.success(script);
    }


}
