package com.bonus.sgzb.material.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.bonus.sgzb.base.api.domain.SltAgreementApply;
import com.bonus.sgzb.base.api.domain.SltAgreementDetails;
import com.bonus.sgzb.base.api.domain.SltAgreementInfo;
import com.bonus.sgzb.base.api.domain.SltInfoVo;
import com.bonus.sgzb.common.core.utils.poi.ExcelUtil;
import com.bonus.sgzb.common.core.web.controller.BaseController;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.core.web.page.TableDataInfo;
import com.bonus.sgzb.common.log.annotation.Log;
import com.bonus.sgzb.common.log.enums.BusinessType;
import com.bonus.sgzb.common.security.annotation.RequiresPermissions;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.service.SltAgreementInfoService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author c liu
 * @date 2024/2/22
 */
@RestController
@RequestMapping("/sltAgreementInfo")
public class SltAgreementInfoController extends BaseController {
    @Resource
    private SltAgreementInfoService sltAgreementInfoService;

    /**
     * 根据条件获取协议结算列表
     */
    @RequiresPermissions("cost:settlement:list")
    @ApiOperation(value = "根据条件获取协议结算列表")
    @GetMapping("/getSltAgreementInfo")
    public TableDataInfo getSltAgreementInfo(AgreementInfo bean) {
        startPage();
        List<AgreementInfo> list = sltAgreementInfoService.getSltAgreementInfo(bean);
        return getDataTable(list);
    }

    /**
     * 根据协议获取结算清单
     */
    @ApiOperation(value = "根据协议获取结算清单")
    @PostMapping("/getSltInfo")
    @RequiresPermissions("finis:record:details")
    public AjaxResult getSltInfo(@RequestBody List<AgreementInfo> list) {
        SltInfoVo bean = sltAgreementInfoService.getSltInfo(list);
        return AjaxResult.success(bean);
    }

    /**
     * 根据协议获取月结算清单
     */
    @RequiresPermissions("month:record:query")
    @ApiOperation(value = "根据协议获取月结算清单")
    @PostMapping("/getSltInfoMonth")
    public AjaxResult getSltInfoMonth(@RequestBody List<AgreementInfo> list) {
        return AjaxResult.success(sltAgreementInfoService.getSltInfoMonth(list));
    }

    @RequiresPermissions("cost:settlement:export")
    @ApiOperation(value = "月结明细导出")
    @PostMapping("/exportSltInfoMonth")
    public void exportSltInfoMonth(HttpServletResponse response, @RequestBody List<AgreementInfo> list) throws IOException {
        List<SltAgreementInfo> sltInfoMonth = sltAgreementInfoService.getSltInfoMonth(list);
        List<List<MonthRepairInfo>> allLists = new ArrayList<>();
        for (AgreementInfo agreementInfo : list) {
            List<MonthRepairInfo> list1 = new ArrayList<>();
            for (SltAgreementInfo sltAgreementInfo : sltInfoMonth) {
                // 单个协议导出
                if (StringUtils.isNotBlank(agreementInfo.getCodeNum())) {
                    String[] split = agreementInfo.getCodeNum().split(",");
                    for (String s : split) {
                        if (s.equals(sltAgreementInfo.getCodeNum().toString())) {
                            List<SltAgreementInfo> node = sltAgreementInfo.getNode();
                            List<MonthRepairInfo> leaseInfoList = Convert.toList(MonthRepairInfo.class, node);
                            list1.addAll(leaseInfoList);
                        }
                    }
                } else {
                    if (String.valueOf(agreementInfo.getAgreementId()).equals(sltAgreementInfo.getAgreementId())){
                        // 多个协议导出
                        List<SltAgreementInfo> node = sltAgreementInfo.getNode();
                        List<MonthRepairInfo> leaseInfoList = Convert.toList(MonthRepairInfo.class, node);
                        list1.addAll(leaseInfoList);
                    }
                }
            }
            allLists.add(list1);
        }
        exportMultipleLists(allLists, response);
    }

    /**
     * 调整天数
     */
    @ApiOperation(value = "调整天数和日期")
    @PostMapping("/updateTrimDay")
    @RequiresPermissions("cost:settlement:edit")
    public AjaxResult updateTrimDay(@RequestBody List<SltAgreementInfo> sltAgreementInfo) {
        int bean = sltAgreementInfoService.updateTrimDay(sltAgreementInfo);
        if (bean == 0) {
            return AjaxResult.error("修改失败");
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 租赁明细导出
     */
    @Log(title = "租赁明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLeaseOne")
    @RequiresPermissions("ndertake:export_1")
    public void exportLeaseOne(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getLeaseListOne(list);
        List<LeaseInfo> leaseInfoList = Convert.toList(LeaseInfo.class, explist);
        ExcelUtil<LeaseInfo> util = new ExcelUtil<LeaseInfo>(LeaseInfo.class);
        util.exportExcel(response, leaseInfoList, "租赁明细导出");
    }

    /**
     * 租赁明细导出
     */
    @Log(title = "租赁明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLeaseThree")
    @RequiresPermissions("ndertake:export_2")
    public void exportLeaseThree(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getLeaseListThree(list);
        List<LeaseInfo> leaseInfoList = Convert.toList(LeaseInfo.class, explist);
        ExcelUtil<LeaseInfo> util = new ExcelUtil<LeaseInfo>(LeaseInfo.class);
        util.exportExcel(response, leaseInfoList, "租赁明细导出");
    }

    /**
     * 丢失明细导出
     */
    @Log(title = "丢失明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportLose")
    @RequiresPermissions("device:wh:export")
    public void exportLose(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getLoseList(list);
        List<LoseInfo> leaseInfoList = Convert.toList(LoseInfo.class, explist);
        ExcelUtil<LoseInfo> util = new ExcelUtil<LoseInfo>(LoseInfo.class);
        util.exportExcel(response, leaseInfoList, "丢失明细导出");
    }

    /**
     * 维修明细导出
     */
    @Log(title = "维修明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRepair")
    @RequiresPermissions("device:repair:export")
    public void exportRepair(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getRepairList(list);
        List<RepairInfo> leaseInfoList = Convert.toList(RepairInfo.class, explist);
        ExcelUtil<RepairInfo> util = new ExcelUtil<RepairInfo>(RepairInfo.class);
        util.exportExcel(response, leaseInfoList, "维修明细导出");
    }

    /**
     * 报废明细导出
     */
    @Log(title = "报废明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportScrap")
    @RequiresPermissions("device:scrap:export")
    public void exportScrap(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getScrapList(list);
        List<ScrapInfo> leaseInfoList = Convert.toList(ScrapInfo.class, explist);
        ExcelUtil<ScrapInfo> util = new ExcelUtil<ScrapInfo>(ScrapInfo.class);
        util.exportExcel(response, leaseInfoList, "维修明细导出");
    }

    /**
     * 预报废明细导出
     */
    @Log(title = "预报废明细导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportPreScrap")
    @RequiresPermissions("device:dai:scrap:export")
    public void exportPreScrap(HttpServletResponse response, @RequestBody List<AgreementInfo> list) {
        List<SltAgreementInfo> explist = sltAgreementInfoService.getPreScrapList(list);
        List<preScrapInfo> leaseInfoList = Convert.toList(preScrapInfo.class, explist);
        ExcelUtil<preScrapInfo> util = new ExcelUtil<preScrapInfo>(preScrapInfo.class);
        util.exportExcel(response, leaseInfoList, "维修明细导出");
    }


    /**
     * 校验该类型是否有归还记录，有的话该类型都按最后一次提交时间规划，
     */
 /*   @ApiOperation(value = "费用结算提交")
    @PostMapping("/checkSltEndTime")
    public AjaxResult checkSltEndTime(@RequestBody SltAgreementApply apply) {
        return sltAgreementInfoService.submitFee(apply);
    }*/
    /**
     * 费用结算提交
     */
    @ApiOperation(value = "费用结算提交")
    @PostMapping("/submitFee")
    public AjaxResult submitFee(@RequestBody SltAgreementApply apply) {
        return sltAgreementInfoService.submitFee(apply);
    }

    /**
     * 费用结算提交
     */
    @ApiOperation(value = "委外费用修改")
    @PostMapping("/updateOutSourceCosts")
    public AjaxResult updateOutSourceCosts(@RequestBody List<SltAgreementInfo> apply) {
        if (CollUtil.isEmpty(apply)) {
            return AjaxResult.error("请选择设备维修单");
        }
        for (SltAgreementInfo sltAgreementInfo : apply) {
            int res = sltAgreementInfoService.updateOutSourceCosts(sltAgreementInfo);
            if (res == 0) {
                return AjaxResult.error("修改失败");
            }
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 费用结算提交
     */
    @ApiOperation(value = "费用结算提交-承担方")
    @PostMapping("/submitFeeBear")
    public AjaxResult submitFeeBear(@RequestBody SltAgreementInfo apply) {
        return sltAgreementInfoService.submitFeeOne(apply);
    }

    /**
     * 获取结算审核列表
     */
    @RequiresPermissions("cost:settlement:auditing")
    @ApiOperation(value = "获取结算审核列表")
    @GetMapping("/getSltExam")
    public TableDataInfo getSltExam(AgreementInfo bean) {
        startPage();
        List<SltAgreementApply> list = sltAgreementInfoService.getSltExam(bean);
        return getDataTable(list);
    }

    /**
     * 获取结算审核清单
     */
    @ApiOperation(value = "获取结算审核清单")
    @GetMapping("/getSltExamInfo")
    public AjaxResult getSltExamInfo(SltAgreementApply apply) {
        SltInfoVo bean = sltAgreementInfoService.getSltExamInfo(apply);
        return AjaxResult.success(bean);
    }

    /**
     * 结算审核
     */
    @ApiOperation(value = "结算审核")
    @GetMapping("/settlementReview")
    public AjaxResult settlementReview(SltAgreementApply apply) {
        return toAjax(sltAgreementInfoService.settlementReview(apply));
    }

    public void exportMultipleLists(List<List<MonthRepairInfo>> lists, HttpServletResponse response) throws IOException {
            String fileName = "月结明细导出数据.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 使用 EasyExcel 创建一个写入器
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), MonthRepairInfo.class).build();

            for (int i = 0; i < lists.size(); i++) {
                List<MonthRepairInfo> monthRepairInfoList = lists.get(i);
                if (!CollectionUtils.isEmpty(monthRepairInfoList)) {
                    WriteSheet writeSheet = EasyExcel.writerSheet(monthRepairInfoList.get(0).getProjectName()).build();
                    excelWriter.write(monthRepairInfoList, writeSheet);
                }
            }

            // 关闭写入器
            excelWriter.finish();
        }
}
