package com.zfire.mall.manager.controller.wallet;

import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zfire.mall.manager.annotation.ZfireList;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.listV2.*;
import com.zfire.mall.manager.bean.listV2.dto.CustomerAmountDTO;
import com.zfire.mall.manager.bean.wallet.CustomerWalletBean;
import com.zfire.mall.manager.bean.wallet.RebateWalletSaleBean;
import com.zfire.mall.manager.bean.wallet.WalletListBean;
import com.zfire.mall.manager.bean.wallet.WalletRebateBean;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.KingDeeWallet;
import com.zfire.mall.manager.plus.entity.SaleType;
import com.zfire.mall.manager.plus.entity.WalletRebate;
import com.zfire.mall.manager.plus.entity.WalletRebateSaleType;
import com.zfire.mall.manager.utils.excel.ExcelUtils;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Slf4j
@RestController
@Api(value = "钱包API", tags ={"钱包API"} )
@RequestMapping(value = "/wallet", produces = "application/json; charset=utf-8")
public class WalletController {


    @Autowired
    WalletLogic walletLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;

    @ZfireList
    @PostMapping("/rebate/list/v2")
    @ApiOperation("返利钱包列表-V2")
    public ResponseHelper<IPage<WalletRebateVO>> customerListV2(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<WalletRebateVO> page = walletLogic.listV2(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WalletRebateVO>() {});
    }

    @PostMapping("/rebate/list/export")
    @ApiOperation("返利钱包列表-列表V2导出")
    public void listTollV2Export(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<WalletRebateVO> list = walletLogic.listV2(zfireParamBean);
        //3.导出
        FieldUtils.exportData(list.getRecords(),zfireParam.getExportFields(),request,response);
    }


    @ApiOperation(value = "返利钱包列表")
    @GetMapping("/rebate/list")
    public ResponseHelper<IPage<WalletRebateBean>> rebateList(
            @ApiParam(required = false, value = "钱包名称") @RequestParam(required = false) String name,
            @ApiParam(required = false, value = "状态1=已启用 0=已停用") @RequestParam(required = false) Boolean status,
            @ApiParam(value = "页号",required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "页大小",required = true)@RequestParam Integer pageSize
    ) throws Exception {
        IPage<WalletRebateBean> list = walletLogic.list(name, status, pageNum, pageSize);
        return ResponseHelper.success(list);
    }


    @ApiOperation(value = "返利钱包详情")
    @GetMapping("/rebate/detail")
    public ResponseHelper<WalletRebateBean> detail(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String id
    ) throws Exception {
        WalletRebateBean detail = walletLogic.detail(id);
        return ResponseHelper.success(detail);
    }

    @ApiOperation(value = "返利钱包新增")
    @PostMapping("/add")
    public ResponseHelper add(
            @RequestBody(required = true) WalletRebate walletRebate
    ) throws Exception {
        Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.LOCK_WALLET + walletRebate.getName());
        try {
            if(!obtain.tryLock(10,TimeUnit.SECONDS)){
                return ResponseHelper.error("系统繁忙请稍后再试");
            }
            walletLogic.add(walletRebate);
        }finally {
            obtain.unlock();
        }
        return ResponseHelper.success();
    }

    @ApiOperation(value = "返利钱包修改")
    @PostMapping("/update")
    public ResponseHelper update(
            @RequestBody(required = true)  WalletRebate walletRebate
    ) throws Exception {
        walletLogic.update(walletRebate);
        return ResponseHelper.success();
    }


    @ZfireList
    @PostMapping("/rebate_saletype/list/v2")
    @ApiOperation("返利钱包销售类型V2")
    public ResponseHelper<IPage<WalletSaleTypeRelaVO>> rebateTypeListV2(
            @RequestBody ZfireParamBean zfireParamBean
    ) throws RemoteServiceException {
        IPage<WalletSaleTypeRelaVO> page = walletLogic.listRebateSaleTypeV2(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<WalletSaleTypeRelaVO>() {});
    }

    @PostMapping("/rebate_saletype/list/v2/export")
    @ApiOperation("返利钱包销售类型V2-导出")
    public void rebateTypeListExport(
            @RequestBody ZfireParamBean zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<WalletSaleTypeRelaVO> list = walletLogic.listRebateSaleTypeV2(zfireParamBean);
        //3.导出
        FieldUtils.exportData(list.getRecords(),zfireParam.getExportFields(),request,response);
    }


    @ApiOperation(value = "返利钱包销售类型-列表")
    @GetMapping("/rebate_saletype/list")
    public ResponseHelper<IPage<RebateWalletSaleBean>> rebateTypeList(
            @ApiParam(required = false, value = "钱包名称") @RequestParam(required = false) String name,
            @ApiParam(required = false, value = "销售类型编码") @RequestParam(required = false) String saleTypeCode,
            @ApiParam(required = false, value = "销售类型名称") @RequestParam(required = false) String saleTypeName,
            @ApiParam(required = false, value = "状态1=已启用 0=已停用") @RequestParam(required = false) Boolean status,
            @ApiParam(value = "页号",required = true)@RequestParam Integer pageNum,
            @ApiParam(value = "页大小",required = true)@RequestParam Integer pageSize
    ) throws Exception {
        IPage<RebateWalletSaleBean> rebateWalletSaleBeanIPage = walletLogic.listRebateSaleType(name, saleTypeCode, saleTypeName, status, pageNum, pageSize);
        return ResponseHelper.success(rebateWalletSaleBeanIPage);
    }


    @ApiOperation(value = "返利钱包销售类型-导出")
    @GetMapping("/rebate_saletype/export")
    public void rebateTypeExport(
            @ApiParam(required = false, value = "钱包名称") @RequestParam(required = false) String name,
            @ApiParam(required = false, value = "销售类型编码") @RequestParam(required = false) String saleTypeCode,
            @ApiParam(required = false, value = "销售类型名称") @RequestParam(required = false) String saleTypeName,
            @ApiParam(required = false, value = "状态1=已启用 0=已停用") @RequestParam(required = false) Boolean status,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        IPage<RebateWalletSaleBean> rebateWalletSaleBeanIPage = walletLogic.listRebateSaleType(name, saleTypeCode, saleTypeName, status, 1, -1);
        ExcelData excelData = walletLogic.listRebateSaleTypeExport(rebateWalletSaleBeanIPage.getRecords());
        ExcelUtils.exportExcel(request,response,"返利钱包销售类型.xlsx",excelData);
    }


    @ApiOperation(value = "返利钱包销售类型-详情")
    @GetMapping("/rebate_saletype/detail")
    public ResponseHelper<WalletRebateSaleType> rebateTypeDetail(
            @ApiParam(required = true, value = "id") @RequestParam(required = true) String walletRebateSaleTypeId
    ) throws Exception {
        WalletRebateSaleType walletRebateSaleType = walletLogic.detailRebateSaleType(walletRebateSaleTypeId);
        return ResponseHelper.success(walletRebateSaleType);
    }

    @ApiOperation(value = "返利钱包销售类型-新增")
    @PostMapping("/rebate_saletype/add")
    public ResponseHelper rebateTypeAdd(
            @RequestBody(required = true) WalletRebateSaleType walletRebateSaleType
    ) throws Exception {
        walletLogic.addRebateSaleType(walletRebateSaleType);
        return ResponseHelper.success();
    }

    @ApiOperation(value = "返利钱包销售类型-修改")
    @PostMapping("/rebate_saletype/update")
    public ResponseHelper rebateTypeUpdate(
            @RequestBody(required = true) WalletRebateSaleType walletRebateSaleType
    ) throws Exception {
        walletLogic.updateRebateSaleType(walletRebateSaleType);
        return ResponseHelper.success();
    }

    @ApiOperation(value = "返利钱包销售类型-删除")
    @PostMapping("/rebate_saletype/delete")
    public ResponseHelper rebateTypeUpdate(
            @RequestParam(required = true) List<String> walletRebateSaleTypeIds
    ) throws Exception {
        walletLogic.deleteRebateSaleType(walletRebateSaleTypeIds);
        return ResponseHelper.success();
    }




    @PostMapping("/bindMain")
    @ApiOperation("绑定品类")
    public ResponseHelper bindMain(
            @ApiParam(value = "钱包id",required = true) @RequestParam(required = true) String id,
            @ApiParam(value = "是否为折让钱包 true=是 false=否",required = true) @RequestParam(required = true) Boolean isZr,
            @ApiParam(value = "是否可使用返利 true=是 false=否",required = true) @RequestParam(required = true) Boolean isRebate
    ){
        walletLogic.bindMain(id,isZr,isRebate);
        return ResponseHelper.success();
    }

    @PostMapping("/init")
    @ApiOperation(value = "经销商生成钱包")
    public ResponseHelper init(
            @ApiParam(value = "经销商id",required = true) @RequestParam(required = true) String customerId
    ) throws Exception {
        walletLogic.initByK3Customer(customerId);
        return ResponseHelper.success();
    }

    @GetMapping("/customer/list")
    @ApiOperation(value = "经销商钱包列表")
    public ResponseHelper<List<CustomerWalletBean>> customerWalletList(
            @ApiParam(value = "经销商id",required = false) @RequestParam(required = false) String customerId,
            @ApiParam(value = "钱包类型：COMMONLY=普通钱包 REBATE=返利钱包",required = false) @RequestParam(required = false) String type,
            @ApiParam(value = "是否有流水",required = false) @RequestParam(required = false) Boolean hasRecord
    ) throws Exception {
        List<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, type,hasRecord);
        return ResponseHelper.success(customerWalletBeans);
    }

    @GetMapping("/customer/list/page")
    @ApiOperation(value = "经销商钱包列表-分页版")
    public ResponseHelper<IPage<CustomerWalletBean>> customerWalletPage(
            @ApiParam(value = "经销商id",required = false) @RequestParam(required = false) String customerId,
            @ApiParam(value = "钱包类型：COMMONLY=普通钱包 REBATE=返利钱包",required = false) @RequestParam(required = false) String type,
            @ApiParam(value = "是否有流水",required = false) @RequestParam(required = false) Boolean hasRecord,
            @ApiParam(value = "最小可用信用额度",required = false) @RequestParam(required = false) BigDecimal minFreeAmount,
            @ApiParam(value = "最大可用信用额度",required = false) @RequestParam(required = false) BigDecimal maxFreeAmount,
            @ApiParam(value = "pageNum",required = true) @RequestParam(required = true) Integer pageNum,
            @ApiParam(value = "pageSize",required = true) @RequestParam(required = true) Integer pageSize
    ) throws Exception {
        IPage<CustomerWalletBean> customerWalletBeans = walletLogic.queryWalletByCustomerId(customerId, type,hasRecord,minFreeAmount,maxFreeAmount,pageNum,pageSize);
        return ResponseHelper.success(customerWalletBeans);
    }


    @GetMapping("/list")
    @ApiOperation(value = "钱包列表(非返利钱包)")
    public ResponseHelper<List<KingDeeWallet>> list(
            @ApiParam(value = "钱包名称",required = false) @RequestParam(required = false) String walletName
    ) throws Exception {
        List<KingDeeWallet> list = walletLogic.list(walletName);
        return ResponseHelper.success(list);
    }

    @PostMapping("/detail")
    @ApiOperation(value = "现金钱包详情")
    public ResponseHelper<KingDeeWallet> KingDeeDetail(
            @ApiParam(value = "现金钱包id",required = true) @RequestParam(required = true) String id
    ) throws Exception {
        KingDeeWallet wallet = walletLogic.kingDeedetail(id);
        return ResponseHelper.success(wallet);
    }

    @PostMapping("/rebate_rate/update")
    @ApiOperation(value = "设置特定的经销商返利钱包的返利额度")
    public ResponseHelper updateRate(
            @ApiParam(value = "返利钱包id",required = true) @RequestParam(required = true) String customerWalletId,
            @ApiParam(value = "返利比例(1折=0.1，不能大于1)",required = true) @RequestParam(required = true)BigDecimal rebateRate
            ) throws Exception {
        walletLogic.updateRate(customerWalletId,rebateRate);
        return ResponseHelper.success();
    }

    @GetMapping("/customer/list/export")
    @ApiOperation(value = "经销商信用额度数据导出")
    public void customerWalletPageExport(
            @ApiParam(value = "经销商id",required = false) @RequestParam(required = false) String customerId,
            @ApiParam(value = "钱包类型：COMMONLY=普通钱包 REBATE=返利钱包",required = false) @RequestParam(required = false) String type,
            @ApiParam(value = "是否有流水",required = false) @RequestParam(required = false) Boolean hasRecord,
            @ApiParam(value = "最小可用信用额度",required = false) @RequestParam(required = false) BigDecimal minFreeAmount,
            @ApiParam(value = "最大可用信用额度",required = false) @RequestParam(required = false) BigDecimal maxFreeAmount,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {

        IPage<CustomerWalletBean> list = walletLogic.queryWalletByCustomerId(customerId, type,hasRecord,minFreeAmount,maxFreeAmount,1,-1);
        ExcelData excelData = walletLogic.customerWalletExportData(list.getRecords());
        ExcelUtils.exportExcel(request,response,"信用额度管理.xlsx",excelData);
    }


    @GetMapping("/count/export")
    @ApiOperation(value = "经销商钱包统计-导出")
    public void export(
            @ApiParam(value = "经销商编码",required = false) @RequestParam(required = false) String customerNumber,
            @ApiParam(value = "经销商编码开始",required = false) @RequestParam(required = false) String startCustomerId,
            @ApiParam(value = "经销商编码结束",required = false) @RequestParam(required = false) String endCustomerId,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //log.info("countExport startCustomerId:"+ startCustomerId +",endCustomerId:"+endCustomerId);
        ExcelData excelData = walletLogic.exportWalletCount(customerNumber,startCustomerId,endCustomerId);
        ExcelUtils.exportExcel(request,response,"经销商钱包额度记录.xlsx",excelData);
    }


    @GetMapping("/all")
    @ApiOperation("所有钱包")
    public ResponseHelper<List<WalletListBean>> allWallet(){
        List<WalletListBean> walletListBeans = walletLogic.allWalletList();
        return ResponseHelper.success(walletListBeans);
    }


    @ZfireList
    @PostMapping("/history/list")
    @ApiOperation("经销商历史钱包余额-列表")
    public ResponseHelper<IPage<CustomerWalletAmountVO>> customerHistoryAmount(
            @RequestBody CustomerAmountDTO zfireParamBean
    ) throws RemoteServiceException {
        IPage<CustomerWalletAmountVO> page = walletLogic.historyAmountList(zfireParamBean);
        return ResponseHelper.success(page, new TypeReference<CustomerWalletAmountVO>() {});
    }

    @PostMapping("/history/list/export")
    @ApiOperation("经销商历史钱包余额-导出")
    public void historyListExport(
            @RequestBody CustomerAmountDTO zfireParamBean,
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);
        //2.查询要导出的内容
        IPage<CustomerWalletAmountVO> page = walletLogic.historyAmountList(zfireParamBean);
        //3.导出
        FieldUtils.exportData(page.getRecords(),zfireParam.getExportFields(),request,response);
    }

}
