package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.bweb.excel.model.ExportTradeOrderModel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.IDGenerator;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.obs.HuaWeiYunObs;
import com.hfkj.openapi.v1.model.TradeDetailBillsModel;
import com.hfkj.service.BsTradeOrderRefundService;
import com.hfkj.service.BsTradeOrderService;
import com.hfkj.service.rebate.BsRebateRewardRosterService;
import com.hfkj.service.rebate.BsRebateRewardService;
import com.hfkj.service.rebate.model.ExportRewardRosterModel;
import com.hfkj.sysenum.RebateRewardRosterStatusEnum;
import com.hfkj.sysenum.TradeOrderRefundStatusEnum;
import com.hfkj.sysenum.TradeOrderStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Controller
@Api(value = "返利金")
@RequestMapping(value = "/rebateReward")
public class BsRebateRewardController {

    private static Logger log = LoggerFactory.getLogger(BsRebateRewardController.class);

    @Resource
    private BsRebateRewardService rebateRewardService;

    @Resource
    private BsRebateRewardRosterService rebateRewardRosterService;

    @RequestMapping(value="/grantReward",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "发放奖池金额")
    public ResponseData grantReward(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("batchIdentifier") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的奖池");
            }
            // 发放奖池
            rebateRewardService.grantReward(body.getLong("batchIdentifier"));

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryRewardList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取奖池列表")
    public ResponseData queryRewardList(@RequestParam(value = "batchIdentifier" , required = false) Long batchIdentifier,
                                        @RequestParam(value = "status" , required = false) Integer status,
                                        @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                        @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("batchIdentifier", batchIdentifier);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(rebateRewardService.getRebateRewardList(param)));

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/queryRewardDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取奖池详情")
    public ResponseData queryRewardDetail(@RequestParam(value = "batchIdentifier" , required = true) Long batchIdentifier) {
        try {
            // 查询奖池
            BsRebateReward rebateReward = rebateRewardService.getRebateReward(batchIdentifier);
            if (rebateReward == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的奖池");
            }
            Map<String,Object> param = new HashMap<>();
            param.put("rebateReward", rebateReward);
            param.put("rebateRewardRoster", rebateRewardRosterService.getRosterList(batchIdentifier));
            return ResponseMsgUtil.success(param);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/exportRewardRoster",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出奖池名单")
    public ResponseData exportRewardRoster(@RequestParam(value = "batchIdentifier" , required = true) Long batchIdentifier) {
        try {
            // 查询奖池
            BsRebateReward rebateReward = rebateRewardService.getRebateReward(batchIdentifier);
            if (rebateReward == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的奖池");
            }

            List<ExportRewardRosterModel> exportRosterModelList = new ArrayList<>();
            ExportRewardRosterModel exportRewardRosterModel;

            List<BsRebateRewardRoster> rosterList = rebateRewardRosterService.getRosterList(batchIdentifier);
            for (BsRebateRewardRoster roster : rosterList) {
                exportRewardRosterModel = new ExportRewardRosterModel();
                exportRewardRosterModel.setBatchIdentifier(roster.getBatchIdentifier());
                exportRewardRosterModel.setMerNo(roster.getMerNo());
                exportRewardRosterModel.setMerName(roster.getMerName());
                exportRewardRosterModel.setMerAbbreviate(roster.getMerAbbreviate());
                exportRewardRosterModel.setMerAccountNumber(roster.getMerAccountNumber());
                exportRewardRosterModel.setRewardRatio(roster.getRewardRatio());
                exportRewardRosterModel.setAmount(roster.getAmount());
                exportRewardRosterModel.setStatus(Objects.requireNonNull(RebateRewardRosterStatusEnum.getDataByNumber(roster.getStatus())).getName());
                exportRosterModelList.add(exportRewardRosterModel);
            }

            String childPath = "temporary/";
            String fileName = System.currentTimeMillis() + "" + Math.abs(new Random().nextInt() % 1000) + ".xlsx";
            EasyExcel.write(CommonSysConst.getSysConfig().getFilesystem() + "/" + childPath + fileName, TradeDetailBillsModel.class)
                    .sheet(batchIdentifier+"名单")
                    .doWrite(exportRosterModelList);

            // 上传华为云 OBS
            HuaWeiYunObs.obsUtilPutObject(CommonSysConst.getSysConfig().getFilesystem() + "/" + childPath + fileName, HuaWeiYunObs.bucketName,  childPath + fileName);
            // 延迟1秒  OBS服务器内网上传，有时间差
            Thread.sleep(1000);

            String fileUrl = CommonSysConst.getSysConfig().getObs_url() + "/"+ childPath + fileName;
            return ResponseMsgUtil.success(fileUrl);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
