package com.fzm.mall.server.admin.finance_center.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fzm.mall.server.admin.constant.MALLGlobalConfig;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.finance_center.entity.dto.*;
import com.fzm.mall.server.admin.finance_center.entity.vo.BaseIntegralDetailVO;
import com.fzm.mall.server.admin.finance_center.entity.vo.IntegralDetailVO;
import com.fzm.mall.server.admin.finance_center.entity.vo.IntegralListVO;
import com.fzm.mall.server.admin.finance_center.service.IMerchantIntegralService;
import com.fzm.mall.server.admin.finance_center.service.IPlatformIntegralService;
import com.fzm.mall.server.admin.home_page.enums.type.AdminTypeEnum;
import com.fzm.mall.server.admin.home_page.model.Admin;
import com.fzm.mall.server.admin.home_page.service.IAdminService;
import com.fzm.mall.server.admin.repo.ResponseFactory;
import com.fzm.mall.server.admin.repo.ResponseVO;
import com.fzm.mall.server.admin.util.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author wangp
 * @date 2021/4/27 10:44
 * @description 积分管理
 * @since JDK 1.8
 */
@Api(tags = "财务中心-积分管理")
@RestController
@RequestMapping("/integralManage")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class IntegralManageController {
    private final IMerchantIntegralService merchantIntegralService;
    private final ResponseFactory resFac;
    private final IAdminService adminService;
    private final IPlatformIntegralService platformIntegralService;

    //TODO   积分充值 -- 待定 | 批量转账 -- 3个接口
    @ApiOperation(value = "发行商户积分")
//    @AdminLog(description = "财务中心-发行商户积分", module = OperateModuleEnum.FINANCE_CENTER)
    @PostMapping("/issueMerchantIntegral")
    public ResponseVO issueMerchantIntegral(@RequestBody MerchantIntegralDTO dto, @RequestHeader String adminId) {
        System.err.println("dto:" + dto);
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        merchantIntegralService.issueMerchantIntegral(dto, admin.getMerchantId());
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "商户积分详情")
    @GetMapping("/merchantIntegralDetail")
    public ResponseVO merchantIntegralDetail(@RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        IntegralDetailVO vo = merchantIntegralService.queryByMerchantId(admin.getMerchantId());
        return resFac.getSuccessResponseWithData(vo);
    }

    @ApiOperation(value = "分页查询-系统积分列表")
    @GetMapping("/page")
    public ResponseVO page(
            @ApiParam(name = "label", value = "积分标识")
            @RequestParam(required = false) String label,
            @ApiParam(name = "merchantName", value = "商户名称")
            @RequestParam(required = false) String merchantName,
            @ApiParam(name = "status", value = "积分状态")
            @RequestParam(required = false) Integer status,
            @ApiParam(name = "pageNum", value = "当前页数")
            @RequestParam Integer pageNum,
            @ApiParam(name = "pageSize", value = "每页个数")
            @RequestParam Integer pageSize,
            @ApiParam(name = "adminId", value = "管理员id")
            @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        IPage<IntegralListVO> page = merchantIntegralService.page(admin.getMerchantId(), label, merchantName, status, pageNum, pageSize);
        return resFac.getSuccessResponseWithData(page);
    }

    @ApiOperation(value = "设置积分兑换比例")
    @PutMapping("/setRatio")
    public ResponseVO setRatio(@RequestBody @Valid IntegralExchangeRatioDTO ratioDTO, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        merchantIntegralService.setRatio(ratioDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "积分审核")
    @PutMapping("/check")
    public ResponseVO check(@RequestBody @Valid IntegralCheckDTO checkDTO, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        merchantIntegralService.check(checkDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "积分禁用、启用")
    @PutMapping("/disable")
    public ResponseVO disable(@RequestBody @Valid IntegralDisableDTO disableDTO, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        merchantIntegralService.disable(disableDTO);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "商户积分转账-单个")
    @PostMapping("/merchantTransSingle")
    public ResponseVO merchantTransSingle(@RequestBody @Valid TransferAccountsDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        merchantIntegralService.merchantTransSingle(dto, admin.getMerchantId(), false);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "商户积分转账-批量")
    @GetMapping("/merchantTransBatch")
    public ResponseVO merchantTransBatch(@RequestParam String path, @RequestHeader String adminId) {
        System.err.println("path:" + path);
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        String merchantId = adminService.getByAdminId(adminId).getMerchantId();
        merchantIntegralService.merchantTransBatch(path, merchantId, false);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "商户平台基础积分转账-单个")
    @PostMapping("/merchantBaseTransSingle")
    public ResponseVO merchantBaseTransSingle(@RequestBody @Valid TransferAccountsDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        merchantIntegralService.merchantTransSingle(dto, admin.getMerchantId(), true);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "商户平台基础积分转账-批量")
    @GetMapping("/merchantBaseTransBatch")
    public ResponseVO merchantBaseTransBatch(@RequestParam String path, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getMerchantTypeArr());
        Admin admin = adminService.getByAdminId(adminId);
        merchantIntegralService.merchantTransBatch(path, admin.getMerchantId(), true);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "平台基础积分转账-单个")
    @PostMapping("/platFormTransSingle")
    public ResponseVO platFormTransSingle(@RequestBody @Valid TransferAccountsDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        platformIntegralService.platFormTransSingle(dto);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "平台基础积分转账-批量")
    @PostMapping("/platFormTransBatch")
    public ResponseVO platFormTransBatch(@RequestBody PlatformTransBatchDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        platformIntegralService.platFormTransBatch(dto);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "设置平台积分价格")
    @PostMapping("/setPlatFormIntegralPrice")
    public ResponseVO setPlatFormIntegralPrice(@RequestBody @Valid SetIntegralPriceDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        platformIntegralService.setPlatFormIntegralPrice(dto);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "增发平台基础积分")
    @PostMapping("/addPlatFormIntegral")
    public ResponseVO addPlatFormIntegral(@RequestBody @Valid AddIssueDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        platformIntegralService.addPlatFormIntegral(dto);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "回收平台基础积分")
    @PostMapping("/recoverPlatFormIntegral")
    public ResponseVO recoverPlatFormIntegral(@RequestBody @Valid RecoverDTO dto, @RequestHeader String adminId) {
        adminService.adminAuthChecks(adminId, AdminTypeEnum.getPlatFormTypeArr());
        platformIntegralService.recoverPlatFormIntegral(dto);
        return resFac.getSimpleSuccessResponse();
    }

    @ApiOperation(value = "平台基础积分详情")
    @GetMapping("/platformBaseIntegralDetail")
    public ResponseVO platformBaseIntegralDetail(@RequestHeader String adminId) {
        BaseIntegralDetailVO detailVO = platformIntegralService.platformBaseIntegralDetail();
        Admin admin = adminService.getByAdminId(adminId);
        Integer type = admin.getType();
        BaseIntegralDetailVO vo = null;
        if (type.equals(AdminTypeEnum.PLATFORM_ADMINISTRATOR.getType()) || type.equals(AdminTypeEnum.PLATFORM.getType())) {
            vo = detailVO;
        }
        if (type.equals(AdminTypeEnum.MERCHANT.getType()) || type.equals(AdminTypeEnum.PLATFORM_MERCHANT.getType())) {
            vo = merchantIntegralService.platformBaseIntegralDetail(MALLGlobalConfig.PLATFORM_BASE_INTEGRAL,
                    admin.getMerchantId(), detailVO.getPrice());
        }
        return resFac.getSuccessResponseWithData(vo);
    }

    @ApiOperation(value = "下载excel模板")
    @GetMapping("/downloadexcel")
    public void downloadPermMatrix(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Workbook wb;
        try {
            ClassPathResource resource = new ClassPathResource("template/transBatch.xlsx");
            InputStream inputStream = resource.getInputStream();
            // 根据不同excel创建不同对象,Excel2003版本-->HSSFWorkbook,Excel2007版本-->XSSFWorkbook
            wb = WorkbookFactory.create(inputStream);
            response.reset();
            response.setContentType("multipart/form-data");
            if (wb.getClass().getSimpleName() == "HSSFWorkbook") {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("批量转账模板".getBytes(), "iso8859-1") + ".xls");
            } else {
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String("批量转账模板".getBytes(), "iso8859-1") + ".xlsx");
            }
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "上传excel模板")
    @PostMapping("/uploadexcel")
    @Transactional(rollbackFor = Exception.class)
    public ResponseVO importWatchExcel(@RequestParam String path, @RequestHeader String adminId) {
        Admin admin = adminService.getByAdminId(adminId);
        if (admin == null) {
            return resFac.getResponse(MallResponseError.NO_AUTH_ERROR);
        }
        List<Map<String, String>> maps = ExcelUtil.analysisExcel(path);
        System.err.println(maps);
        return resFac.getSimpleSuccessResponse();
    }

}
