package com.ruoyi.hywz.controller.stamp.tax;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxComputeItemD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxContractD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxContractInvoiceD;
import com.ruoyi.hywz.entity.AdsMatHyxtStampTaxInvoiceD;
import com.ruoyi.hywz.entity.po.HomeStampTaxCountPO;
import com.ruoyi.hywz.entity.po.StampTaxBatchUpdateTaxItemPO;
import com.ruoyi.hywz.entity.po.IdsPO;
import com.ruoyi.hywz.entity.po.StampTaxComputeSavePO;
import com.ruoyi.hywz.entity.vo.stamp.tax.WarningDataVo;
import com.ruoyi.hywz.listener.ImportExcelHelper;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxContractDService;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxContractInvoiceDService;
import com.ruoyi.hywz.service.IAdsMatHyxtStampTaxInvoiceDService;
import com.ruoyi.hywz.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同信息表 前端控制器
 * </p>
 *
 * @author mybatisplus-generator
 * @date 2024-07-14 10:07:56
 */
@RestController
@AllArgsConstructor
@RequestMapping("adsMatHyxtStampTaxContractD")
@Api(value = "adsMatHyxtStampTaxContractD", tags = "印花税项目")
public class AdsMatHyxtStampTaxContractDController {

    private final IAdsMatHyxtStampTaxContractDService adsMatHyxtStampTaxContractDService;
    private final IAdsMatHyxtStampTaxInvoiceDService adsMatHyxtStampTaxInvoiceDService;

    @Resource
    private IAdsMatHyxtStampTaxContractInvoiceDService iAdsMatHyxtStampTaxContractInvoiceDService;

    @ApiOperation(value = "1【合同信息表】分页查询", notes = "分页查询")
    @PostMapping("/queryPage")
    public R queryPage(@RequestParam(defaultValue = "10") Long pageSize,
                       @RequestParam(defaultValue = "1") Long pageNo,
                       @RequestBody(required = false) AdsMatHyxtStampTaxContractD param) {
        return R.ok(adsMatHyxtStampTaxContractDService.queryPage(pageSize, pageNo, param));
    }

    @ApiOperation(value = "导出")
    @PostMapping("/dataExport")
    public void dataExport(@RequestBody(required = false) AdsMatHyxtStampTaxContractD param, HttpServletResponse response) throws IOException {
        InputStream fis = null;
        OutputStream ops = null;

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = java.util.UUID.randomUUID() + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        String templateFileName = "excelTemplate/stampTax/stampTaxContractExport.xlsx";
        fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateFileName);
        ops = response.getOutputStream();
        Page<AdsMatHyxtStampTaxContractD> pageResult = adsMatHyxtStampTaxContractDService.queryPage(100000L, 1L, param);
        List<AdsMatHyxtStampTaxContractD> itemList = pageResult.getRecords();
        int i = 0;
        for (AdsMatHyxtStampTaxContractD itemD : itemList) {
            i++;
            itemD.setNo(i);
        }

        //填充导出信息
        ExcelWriter excelWriter = EasyExcel.write(ops, AdsMatHyxtStampTaxContractD.class).withTemplate(fis).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(itemList, fillConfig, writeSheet);
        excelWriter.finish();
    }

    @ApiOperation(value = "1【合同信息表】列表查询", notes = "列表查询")
    @PostMapping("/queryList")
    public R queryList(@RequestBody(required = false) AdsMatHyxtStampTaxContractD param) {
        return adsMatHyxtStampTaxContractDService.queryList(param);
    }

    @ApiOperation(value = "1【合同信息表】下载导入模板")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        adsMatHyxtStampTaxContractDService.downloadTemplate(response);
    }

    @ApiOperation(value = "合同数据导入前检查", notes = "合同数据导入前检查")
    @PostMapping("/contractImportCheck")
    public R contractImportCheck(@RequestParam("file") MultipartFile file, HomeStampTaxCountPO param) throws IOException {
        Map<String, Object> result = new HashMap<>(4);

        ImportExcelHelper<AdsMatHyxtStampTaxContractD> helper = new ImportExcelHelper<>();
        List<AdsMatHyxtStampTaxContractD> list = helper.getList(file.getInputStream(), AdsMatHyxtStampTaxContractD.class, 0, 1);
        if (list.size() == 0) {
            result.put("isOk", 1);
            result.put("tips", "未解析到正确数据!");
            return R.ok(result);
        }

        String[] startAndEnd = DateUtil.getMonthStartAndEnd(param.getHomeDate());
        LocalDate startDate = LocalDate.parse(startAndEnd[0], DateUtil.f2_2);
        LocalDate endDate = LocalDate.parse(startAndEnd[1], DateUtil.f2_2);
        int size = 0;
        int totalSize = 0;
        for (AdsMatHyxtStampTaxContractD contractD : list) {
            totalSize++;
            String effectiveDate = DateUtil.getDate(contractD.getEffectiveDate());
            if (null != effectiveDate) {
                // 判断 effectiveDate 日期是否在 startDate - endDate日期之间，如果不在size+1
                LocalDate effective = LocalDate.parse(effectiveDate, DateUtil.f2_2);
                if (effective.isBefore(startDate) || effective.isAfter(endDate)) {
                    size++;
                }
            } else {
                size++;
            }
        }

        if (size > 0) {
            result.put("isOk", 0);
            result.put("tips", "共解析出"+totalSize+"条数据，存在"+size+"条数据，合同生效时间不在"+param.getHomeDate()+"月份中，是否确认导入？");
        } else {
            result.put("isOk", 0);
            result.put("tips", "共解析出"+totalSize+"条数据，本次导入将会把"+param.getHomeDate()+"月份数据清除，是否确认导入？");
        }
        return R.ok(result);
    }

    @ApiOperation(value = "1【合同信息表】合同数据导入", notes = "合同数据导入")
    @PostMapping("/contractImport")
    public R contractImport(@RequestParam("file") MultipartFile file, HomeStampTaxCountPO param) throws IOException {
        return adsMatHyxtStampTaxContractDService.contractImport(file, param);
    }

    @ApiOperation(value = "1【合同信息表】更新", notes = "更新")
    @PostMapping("/update")
    public R update(@RequestBody AdsMatHyxtStampTaxContractD contractD) {
        return adsMatHyxtStampTaxContractDService.updateTax(contractD);
    }

    @ApiOperation(value = "1【合同信息表】删除", notes = "删除")
    @PostMapping("/delete")
    public R delete(@RequestBody IdsPO param) {
        return adsMatHyxtStampTaxContractDService.deleteOne(param);
    }

    @ApiOperation(value = "1【合同信息表】批量删除", notes = "批量删除")
    @PostMapping("/batchDelete")
    public R batchDelete(@RequestBody IdsPO param) {
        return adsMatHyxtStampTaxContractDService.batchDelete(param);
    }

    @ApiOperation(value = "1【合同信息表】批量更新印花税税目", notes = "批量更新印花税税目")
    @PostMapping("/batchUpdateStampTaxItem")
    public R batchUpdateStampTaxItem(@RequestBody StampTaxBatchUpdateTaxItemPO param) {
        List<String> ids = param.getIds();
        if (ObjectUtils.isEmpty(ids) || ids.isEmpty()) {
            return R.fail("请选择要操作的数据！");
        }
        return adsMatHyxtStampTaxContractDService.batchUpdateTax(param);
    }

    @ApiOperation(value = "消除预警", notes = "消除预警")
    @PostMapping("/clearWarning")
    public R clearWarning(@RequestBody WarningDataVo param) {
//        adsMatHyxtStampTaxContractDService.updateIsWarning(param.getId(), 0, param.getRemark());
        LambdaUpdateWrapper<AdsMatHyxtStampTaxContractInvoiceD> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdsMatHyxtStampTaxContractInvoiceD::getId, param.getId());
        updateWrapper.set(AdsMatHyxtStampTaxContractInvoiceD::getWarningStatusDesc, "已处理");
        updateWrapper.set(AdsMatHyxtStampTaxContractInvoiceD::getWarningRemark, param.getRemark());
        Boolean updateFlag = iAdsMatHyxtStampTaxContractInvoiceDService.update(updateWrapper);
        if(!updateFlag){
            return R.fail("操作失败请刷新重试");
        }else {
            List<String> ids = iAdsMatHyxtStampTaxContractInvoiceDService.findContractIdByStatu();
            if(ids!=null && ids.size()>0){
                UpdateWrapper<AdsMatHyxtStampTaxContractD> uWrapper = new UpdateWrapper<>();
                uWrapper.notIn("id",ids);
                uWrapper.set("is_warning",0);
                uWrapper.set("warning_status_desc","已处理");
                adsMatHyxtStampTaxContractDService.update(uWrapper);

            }
        }
        return R.ok();
    }

}
