package com.izouma.nineth.web;

import com.alibaba.fastjson.JSONObject;
import com.izouma.nineth.domain.*;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.dto.userfund.BalanceInfoDTO;
import com.izouma.nineth.enums.AccountType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.UserFundAccountRepo;
import com.izouma.nineth.service.UserFundAccountForLianlianpayService;
import com.izouma.nineth.service.UserFundAccountService;
import com.izouma.nineth.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/userFundAccount")
@AllArgsConstructor
@Slf4j
public class UserFundAccountController extends BaseController{

    private UserFundAccountService userFundAccountService;

    private UserFundAccountRepo userFundAccountRepo;

    private UserFundAccountForLianlianpayService userFundAccountForLianlianpayService;

    @PostMapping("/all")
    public Page<JSONObject> all(@RequestBody PageQuery pageQuery) {
        //所有资金账户
        Page<UserFundAccount> page =  userFundAccountService.all(pageQuery);
        List<JSONObject> newList = new ArrayList<>();
        page.forEach((item) -> {
            newList.add((JSONObject) JSONObject.toJSON(item));
        });

        Page<JSONObject> pageNew = new PageImpl<>(newList, page.getPageable(), page.getTotalElements());
        return pageNew;
    }

    /**
     * 获取账户余额
     * @param fundAccountId
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/getBalance")
    public BalanceInfoDTO getBalance(@RequestParam Long fundAccountId){
        BalanceInfoDTO balanceInfoDTO = null;
        UserFundAccount userFundAccount = userFundAccountRepo.findById(fundAccountId).orElseThrow(new BusinessException("未找到账户记录"));
        if(userFundAccount.getAccountType() == AccountType.LIANLIANPAY_USER){
            balanceInfoDTO = userFundAccountForLianlianpayService.getBalance(userFundAccount.getUserId());
        }else{
            throw new BusinessException("暂不支持当前类型的账户查询("+userFundAccount.getAccountType()+")");
        }

        return balanceInfoDTO;
    }


    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<UserFundAccount> data = userFundAccountService.all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }



}
