package cn.iocoder.yudao.module.system.controller.admin.biz;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.system.api.kingdee.KingdeeApi;
import cn.iocoder.yudao.module.system.service.biz.KingdeeRecordService;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Map;
import cn.iocoder.yudao.module.system.controller.admin.biz.vo.excel.KingdeeCustomerExcelVO;
import cn.iocoder.yudao.module.system.service.biz.ElderlyInfoService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: jinyd
 * @CreateTime: 2024/12/25  14:46
 * @Description:
 * @Version: 4.0
 */

@Tag(name = "管理后台 - 同步金蝶记录")
@RestController
@RequestMapping("/sync/kingdee-record")
@Validated
public class KingdeeRecordController {

    @Resource
    private KingdeeRecordService kingdeeRecordService;

    @Resource
    private KingdeeApi kingdeeApi;

    @Resource
    private ElderlyInfoService elderlyInfoService;

    @GetMapping("/get")
    @Operation(summary = "获得同步金蝶记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('sync:kingdee-record:query')")
    public CommonResult<Integer> getKingdeeRecord(@RequestParam("param") String param) {
        Integer result = 0;

        return CommonResult.success((result));
    }

    @PostMapping("/syncBDCustomer")
    @Operation(summary = "同步客户编码")
    @Parameter(name = "tenantId", description = "租户id", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<Integer> syncBDCustomer(@RequestParam("tenantId") Long tenantId) {
        return CommonResult.success((kingdeeApi.syncBDCustomer(tenantId)));
    }

    @PostMapping("/syncArReceivable")
    @Operation(summary = "应收单")
    @Parameter(name = "tenantId", description = "租户id", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<Integer> syncArReceivable(@RequestParam("tenantId") Long tenantId, @RequestParam("billingMonth") String billingMonth,
                                                  @RequestParam("elderId") Long elderId) {
        return CommonResult.success((kingdeeApi.syncArReceivable(tenantId, billingMonth,elderId)));
    }

    @PostMapping("/syncArReceivebillNew")
    @Operation(summary = "收款单")
    @Parameter(name = "tenantId", description = "租户id", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<String> syncArReceivebillNew(@RequestParam("expenseOrderId") Long expenseOrderId) {
        return CommonResult.success((kingdeeApi.syncArReceivebillNew(expenseOrderId)));
    }

    @PostMapping("/syncArReceivebillNewBatch")
    @Operation(summary = "批量推送收款单")
    @Parameter(name = "tenantId", description = "租户id", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<String> syncArReceivebillNewBatch(@RequestParam("expenseOrderIdList") List<Long> expenseOrderIdList) {
        return CommonResult.success((kingdeeApi.syncArReceivebillNewBatch(expenseOrderIdList)));
    }

    @PostMapping("/syncBDOrg")
    @Operation(summary = "同步机构编码")
    @Parameter(name = "tenantId", description = "租户id", required = true, example = "1024")
    @TenantIgnore
    public CommonResult<Integer> syncBDOrg(@RequestParam("tenantId") Long tenantId) {
        return CommonResult.success((kingdeeApi.syncBDOrg(tenantId)));
    }

    @PostMapping("/importKingdeeCustomerExcel")
    @Operation(summary = "导入金蝶客户信息（更新长者金蝶客户编码）")
    @Parameter(name = "tenantId", description = "机构id/租户id", required = true, example = "1024")
    @Parameter(name = "file", description = "Excel文件", required = true)
    @TenantIgnore
    public CommonResult<Map<String, Object>> importKingdeeCustomerExcel(@RequestParam("tenantId") Long tenantId,
                                                                       @RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("filename=" + file.getOriginalFilename());
        System.out.println("size=" + file.getSize());
        // 1. 读取Excel数据（诊断模式：先读取原始 cell 值，确认 EasyExcel/POI 是否真的读到单元格内容）
        List<Map<Integer, String>> rawRows = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), new AnalysisEventListener<Map<Integer, String>>() {
                    @Override
                    public void invoke(Map<Integer, String> data, AnalysisContext context) {
                        rawRows.add(data);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext context) {
                    }
                })
                .autoCloseStream(true)
                .sheet()
                .headRowNumber(1) // 表头在第一行，数据从第二行开始
                .doRead();

        System.out.println("rawRows=" + rawRows.size());
        if (!rawRows.isEmpty()) {
            System.out.println("rawFirstRow=" + JSON.toJSONString(rawRows.get(0)));
        }

        // 2. 将原始数据转换为 VO（只取前两列：客户编码、客户名称；其它列按需补充）
        List<KingdeeCustomerExcelVO> list = new ArrayList<>();
        for (Map<Integer, String> row : rawRows) {
            KingdeeCustomerExcelVO vo = new KingdeeCustomerExcelVO();
            vo.setCustomerNumber(row.get(0));
            vo.setCustomerName(row.get(1));
            vo.setShortName(row.get(2));
            vo.setDocumentStatus(row.get(3));
            vo.setForbiddenStatus(row.get(4));
            vo.setUseOrganization(row.get(5));
            vo.setAuditor(row.get(6));
            vo.setAuditDate(row.get(7));
            vo.setCustomerGroup(row.get(8));
            list.add(vo);
        }

        System.out.println("rows=" + list.size());
        if (!list.isEmpty()) {
            System.out.println(JSON.toJSONString(list.get(0)));
        }

        // 2. 调用服务处理数据（仅更新指定机构）
        Map<String, Object> result = elderlyInfoService.importKingdeeCustomerExcel(tenantId, list);

        // 3. 返回处理结果
        return CommonResult.success(result);
    }

}
