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.common.constants.StampWarningCheckRule;
import com.ruoyi.hywz.common.enums.StampBusinessTypeEnum;
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.IdsPO;
import com.ruoyi.hywz.entity.po.StampTaxBatchUpdateBusinessTypePO;
import com.ruoyi.hywz.entity.vo.stamp.tax.WarningDataVo;
import com.ruoyi.hywz.listener.ImportExcelHelper;
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.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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("adsMatHyxtStampTaxInvoiceD")
@Api(value = "adsMatHyxtStampTaxInvoiceD", tags = "印花税项目")
public class AdsMatHyxtStampTaxInvoiceDController {

    private final IAdsMatHyxtStampTaxInvoiceDService adsMatHyxtStampTaxInvoiceDService;
    private final IAdsMatHyxtStampTaxContractInvoiceDService iAdsMatHyxtStampTaxContractInvoiceDService;

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

    @ApiOperation(value = "导出")
    @PostMapping("/dataExport")
    public void dataExport(@RequestBody(required = false) AdsMatHyxtStampTaxInvoiceD 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/stampTaxInvoiceExport.xlsx";
        fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateFileName);
        ops = response.getOutputStream();
        Page<AdsMatHyxtStampTaxInvoiceD> pageResult = adsMatHyxtStampTaxInvoiceDService.queryPage(100000L, 1L, param);
        List<AdsMatHyxtStampTaxInvoiceD> itemList = pageResult.getRecords();
        int i = 0;
        for (AdsMatHyxtStampTaxInvoiceD itemD : itemList) {
            i++;
            itemD.setNo(i);
            if(StringUtils.isNotEmpty(itemD.getBusinessType())){
                itemD.setYhssm(StampWarningCheckRule.getFpMapType().get(itemD.getBusinessType()));
            }
        }

        //填充导出信息
        ExcelWriter excelWriter = EasyExcel.write(ops, AdsMatHyxtStampTaxInvoiceD.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 = "2【发票信息表】分页查询", notes = "分页查询")
    @PostMapping("/queryList")
    public R queryList(@RequestBody(required = false) AdsMatHyxtStampTaxInvoiceD param) {
        return adsMatHyxtStampTaxInvoiceDService.queryList(param);
    }

    @ApiOperation(value = "2【发票信息表】下载导入模板")
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        adsMatHyxtStampTaxInvoiceDService.downloadTemplate(response);
    }

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

        ImportExcelHelper<AdsMatHyxtStampTaxInvoiceD> helper = new ImportExcelHelper<>();
        List<AdsMatHyxtStampTaxInvoiceD> list = helper.getList(file.getInputStream(), AdsMatHyxtStampTaxInvoiceD.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 (AdsMatHyxtStampTaxInvoiceD contractD : list) {
            totalSize++;
            String makeDate = DateUtil.getFormat(contractD.getMakeDate(), DateUtil.f2);
            if (null != makeDate) {
                // 判断 mkDate 日期是否在 startDate - endDate日期之间，如果不在size+1
                LocalDate mkDate = LocalDate.parse(makeDate, DateUtil.f2_2);
                if (mkDate.isBefore(startDate) || mkDate.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 = "2【发票信息表】发票数据导入", notes = "发票数据导入")
    @PostMapping("/invoiceImport")
    public R contractImport(@RequestParam("file") MultipartFile file, HomeStampTaxCountPO param) throws IOException {
        return adsMatHyxtStampTaxInvoiceDService.invoiceImport(file, param);
    }

    @ApiOperation(value = "2【发票信息表】更新", notes = "更新")
    @PostMapping("/update")
    public R update(@RequestBody AdsMatHyxtStampTaxInvoiceD contractD) {
        contractD.setUpdateTime(new Date());
        adsMatHyxtStampTaxInvoiceDService.updateById(contractD);
        return R.ok();
    }

    @ApiOperation(value = "2【发票信息表】删除", notes = "删除")
    @PostMapping("/delete")
    public R delete(@RequestBody IdsPO param) {
        return adsMatHyxtStampTaxInvoiceDService.deleteOne(param);
    }

    @ApiOperation(value = "2【发票信息表】批量删除", notes = "批量删除")
    @PostMapping("/batchDelete")
    public R batchDelete(@RequestBody IdsPO param) {
        return adsMatHyxtStampTaxInvoiceDService.batchDelete(param);
    }

    @ApiOperation(value = "2【发票信息表】业务类型列表", notes = "业务类型列表")
    @PostMapping("/businessTypeList")
    public R businessTypeList() {
        return R.ok(StampBusinessTypeEnum.getList());
    }

    @ApiOperation(value = "1【发票信息表】更新", notes = "更新")
    @PostMapping("/updateBusinessType")
    public R updateBusinessType(@RequestBody AdsMatHyxtStampTaxInvoiceD invoiceD) {
        return adsMatHyxtStampTaxInvoiceDService.updateBusinessType(invoiceD);
    }

    @ApiOperation(value = "2【发票信息表】批量更新业务类型", notes = "批量更新业务类型")
    @PostMapping("/batchUpdateBusinessType")
    public R batchUpdateBusinessType(@RequestBody StampTaxBatchUpdateBusinessTypePO param) {
        List<String> ids = param.getIds();
        if (ObjectUtils.isEmpty(ids) || ids.isEmpty()) {
            return R.fail("请选择要操作的数据！");
        }
        return adsMatHyxtStampTaxInvoiceDService.batchUpdateBusinessType(param);
    }

    @ApiOperation(value = "消除预警", notes = "消除预警")
    @PostMapping("/clearWarning")
    public R clearWarning(@RequestBody WarningDataVo param) {
//        adsMatHyxtStampTaxInvoiceDService.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> ids2 = iAdsMatHyxtStampTaxContractInvoiceDService.findInvoiceIdByStatu();
            if(ids2!=null && ids2.size()>0){
                UpdateWrapper<AdsMatHyxtStampTaxInvoiceD> uWrapper2 = new UpdateWrapper<>();
                uWrapper2.notIn("id",ids2);
                uWrapper2.set("is_warning",0);
                uWrapper2.set("warning_status_desc","已处理");
                adsMatHyxtStampTaxInvoiceDService.update(uWrapper2);
            }
        }
        return R.ok();
    }

}
