package com.yonge.cooleshow.admin.controller;

import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.template.R;
import com.microsvc.toolkit.common.tools.DownloadManager;
import com.microsvc.toolkit.middleware.oss.OssPluginContext;
import com.microsvc.toolkit.middleware.oss.impl.TencentOssPlugin;
import com.yonge.cooleshow.biz.dal.entity.FileImportInfo;
import com.yonge.cooleshow.biz.dal.enums.AccountBizTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.InOrOutEnum;
import com.yonge.cooleshow.biz.dal.service.ExcelAnalyseCoreService;
import com.yonge.cooleshow.biz.dal.service.TenantAccountRecordService;
import com.yonge.cooleshow.biz.dal.wrapper.FileImportInfoWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAccountRecordWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantActivationCodeWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/tenantAccountRecord")
@Api(value = "机构账户流水表", tags = "机构账户流水表")
public class TenantAccountRecordController extends BaseController {

    @Autowired
    private TenantAccountRecordService tenantAccountRecordService;

    @Autowired
    private OssPluginContext ossPluginContext;

    @Autowired
    private ExcelAnalyseCoreService excelAnalyseCoreService;
    /**
     * 查询分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "机构流水", notes = "TenantAccountRecordQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantAccountRecord/page')")
    public HttpResponseResult<PageInfo<TenantAccountRecordWrapper.TenantAccountRecord>> page(@RequestBody TenantAccountRecordWrapper.TenantAccountRecordQuery query) {


        IPage<TenantAccountRecordWrapper.TenantAccountRecord> pages = tenantAccountRecordService.selectPage(PageUtil.getPage(query), query);

        // 统计数据
        TenantAccountRecordWrapper.TenantAccountRecordStat statistics = tenantAccountRecordService.getStatistics(query);
        if (statistics == null) {
            statistics = new TenantAccountRecordWrapper.TenantAccountRecordStat();
        }

        PageInfo<TenantAccountRecordWrapper.TenantAccountRecord> tenantAccountRecordPageInfo = PageUtil.pageInfo(pages);
        tenantAccountRecordPageInfo.setStatInfo(statistics);
        return succeed(tenantAccountRecordPageInfo);
    }



    /**
     * 导出
     */
    @PostMapping("/export")
    @ApiOperation(value = "机构流水", notes = "TenantAccountRecordQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantAccountRecord/export')")
    public HttpResponseResult<TenantActivationCodeWrapper.ExportFile> export(@RequestBody TenantAccountRecordWrapper.TenantAccountRecordQuery query) {
        query.setRows(-1);
        query.setInOrOut(InOrOutEnum.IN.getCode());

        IPage<TenantAccountRecordWrapper.TenantAccountRecord> pages = tenantAccountRecordService.selectPage(PageUtil.getPage(query), query);

        // 构建数据
        List<TenantAccountRecordWrapper.TenantAccountRecord> records = pages.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            records = new ArrayList<>();
        }

        List<TenantAccountRecordWrapper.TenantAccountRecordExport> list = JSON.parseArray(JSON.toJSONString(records), TenantAccountRecordWrapper.TenantAccountRecordExport.class);

        for (TenantAccountRecordWrapper.TenantAccountRecordExport tenantAccountRecord : list) {
            tenantAccountRecord.setBizType(AccountBizTypeEnum.valueOf(tenantAccountRecord.getBizType()).getMsg());
            tenantAccountRecord.setSettlement(PostStatusEnum.RECORDED.getCode().equals(tenantAccountRecord.getPostStatus())?"是":"否");
        }

        return succeed(generateExportExcelFile(list,TenantAccountRecordWrapper.TenantAccountRecordExport.class,"机构收入导出","机构收入导出"));
    }



    /**
     * 导出
     */
    @PostMapping("/import")
    @ApiOperation(value = "机构流水", notes = "TenantAccountRecordQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantAccountRecord/import')")
    public HttpResponseResult<FileImportInfo> importFile(@RequestBody FileImportInfoWrapper.FileImport wrapper) {

        wrapper.setImportUrl(URLEncodeUtil.encode(wrapper.getImportUrl()));

        // 读取数据
        return HttpResponseResult.succeed(excelAnalyseCoreService.analyseReadExcelData(
                JSON.parseObject(JSON.toJSONString(wrapper), FileImportInfoWrapper.FileImportInfo.class)));
    }

    private TenantActivationCodeWrapper.ExportFile generateExportExcelFile(List<?> orderExports, Class<?> clazz, String fileName, String sheetName) {

        // OSS上传文件目录
        String uploadOssPath = MessageFormat.format("excel-download/{0}", DateTime.now().toString("yyyy-MM"));

        // 文件上传下载地址
        String uploadPath = MessageFormat.format("{0}/{1}-{2}.xlsx", uploadOssPath, fileName, DateTime.now().toString("MMddHHmmss"));

        // 本地文件地址
        String localPath = DownloadManager.getInstance().path(uploadPath);

        // 模板文件保存在springboot项目的resources/static下
        // Resource resource = new ClassPathResource("static/预报名模板导出.xlsx");

        EasyExcel
                .write(localPath, clazz)
                //.withTemplate(resource.getStream()) // 利用模板的输出流
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet(0, sheetName)
                .doWrite(orderExports);

        // 上传本地文件到OSS服务器
        String downloadPath = ossPluginContext.getPluginService(TencentOssPlugin.PLUGIN_NAME)
                .uploadFile(uploadOssPath, new File(localPath));

        // 删除本地缓存文件
        DownloadManager.getInstance().deleteOnExit(localPath);

        // 学生统计下载
        return TenantActivationCodeWrapper.ExportFile
                .builder()
                .fileName(MessageFormat.format("{0}.xlsx", fileName))
                .downloadPath(downloadPath)
                .build();
    }

}