package com.jwipc.finance.controller.rest;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.logic.PaymentPlanApproveLogic;
import com.jwipc.finance.logic.PaymentPlanDetailLogic;
import com.jwipc.finance.model.query.PaymentPlanQuery;
import com.jwipc.finance.model.query.PpApproveQuery;
import com.jwipc.finance.service.IAccountStatementService;
import com.jwipc.finance.service.IPaymentPlanDetailService;
import com.jwipc.finance.service.IPaymentPlanService;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.util.EasyExcelImportUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.jwipc.finance.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>
 *     对账模块-付款计划明细 前端控制器
 * </p>
 *
 * @author 邓京术
 * @since 2025-07-23
 */
@RestController
@RequestMapping(MODULE_ROOT + "/payment/plan/detail/rest")
@RequiredArgsConstructor
public class PaymentPlanDetailRestController {

    private final PaymentPlanDetailLogic paymentPlanDetailLogic;

    private final PaymentPlanApproveLogic paymentPlanApproveLogic;

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 查询付款计划明细数据
     *
     * @param paymentPlanQuery 查询条件
     * @return 结果
     */
    @PostMapping("/find/by/paymentPlan/id")
    public ResponseEntity findByStatementId(PaymentPlanQuery paymentPlanQuery) {
        //查询权限控制
        paymentPlanQuery.setUserId(LoginUtil.getUserId());
        return ResponseEntity.ok(paymentPlanDetailLogic.findByPaymentPlanIdPage(paymentPlanQuery));
    }

    /**
     * 获取付款计划单审批确认备注
     *
     * @param query 查询参数
     * @return 结果
     */
    @PostMapping("/find/as/approve/log")
    public PageView findStatementApproveLog(PpApproveQuery query){
        return paymentPlanApproveLogic.findByPage(query);
    }

    /**
     * 付款计划明细数据导出
     *
     * @return
     */
    @PostMapping("/exportPaymentPlanDetailData")
    public void exportPaymentPlanDetailData(HttpServletResponse response, String exportFiled, String queryStr)
    {
        PaymentPlanQuery basicPlanQuery = JSON.parseObject(queryStr, PaymentPlanQuery.class);
        if (!LoginUtil.isSupplier() && !LoginUtil.getName().equals("admin")){
            basicPlanQuery.setUserId(LoginUtil.getUserId());
        }
        paymentPlanDetailLogic.exportPaymentPlanDetailData(response,exportFiled,basicPlanQuery);
    }


    /**
     * 付款计划明细导入  付款计划明细编辑页面
     * @param file 计划文件
     * @return 导入是否成功
     */
    @PostMapping("/importPaymentPlanDetail")
    public ResponseEntity importForPublished(@RequestPart("file") MultipartFile file) {
        Long userId = LoginUtil.getUserId();
        try {
            String go_import_published = stringRedisTemplate.opsForValue().get("importPaymentPlanDetail" + userId);
            if (null != go_import_published && go_import_published.equals("Y")) {
                throw new DaoException("数据正在导入中，请勿重复操作！");
            }
            //如果大于最大限制条件，抛出异常提醒，邓京术 2025-05-26
//            List<DictDTO> dictDTOS = dictClient.getDicByType("excel_export_data_count");
//            List<PaymentPlanItemDTO> result = Lists.newArrayList();
            List<Map<String, String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
//            String exportCount = dictDTOS.get(0).getCode();
            //异步执行导出
            if (dataList.size() > Integer.parseInt("1000")) {
                throw new DaoException(StrUtil.format("导入数据超过{}条", 1000));
            }
            paymentPlanDetailLogic.importPaymentPlanDetailData(dataList);
            return ResponseEntity.ok("导入成功!");
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        } finally {
            stringRedisTemplate.opsForValue().set("importPaymentPlanDetail" + userId, "N", 30, TimeUnit.SECONDS);
        }
    }
}
