package com.jeeplus.centrecareful.reportArchieve.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.jeeplus.aop.demo.annotation.DemoMode;
import com.jeeplus.centrecareful.approvalInfo.util.ZSEasyPoiUtil;
import com.jeeplus.centrecareful.reportArchieve.Utils.EasyPoiUtil;
import com.jeeplus.centrecareful.reportArchieve.domain.ZsReportArchieve;
import com.jeeplus.centrecareful.reportArchieve.service.ZsReportArchieveService;
import com.jeeplus.centrecareful.reportArchieve.service.dto.ZsReportArchieveExport;
import com.jeeplus.common.excel.ExcelOptions;
import com.jeeplus.common.excel.ExportMode;
import com.jeeplus.logging.annotation.ApiLog;
import com.jeeplus.logging.constant.enums.LogTypeEnum;
import com.jeeplus.sys.feign.IDictApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags ="中审-报告归档")
@RequestMapping(value = "/zsReportArchieve/info")
@Log4j2
public class ZsReportArchieveController {

    @Autowired
    private ZsReportArchieveService reportArchieveService;


    @ApiOperation(value = "列表查询")
    @GetMapping("/list")
    public ResponseEntity<IPage<ZsReportArchieve>> list(Page<ZsReportArchieve> page, ZsReportArchieve zsReportArchieve) throws Exception{
        IPage<ZsReportArchieve> iPage = reportArchieveService.list(page, zsReportArchieve);

        return ResponseEntity.ok(iPage);
    }

    /**
     * 获取部门列表
     */
    @ApiOperation(value = "获取部门列表")
    @GetMapping("/getOfficeNameList")
    public List<ZsReportArchieve> getOfficeNameList(){
       List<ZsReportArchieve> list = reportArchieveService.getOfficeNameList();
       return list;
    }

    /**
     * 下载导入模板
     * @param response
     * @param request
     * @throws IOException
     */
    @GetMapping("import/template")
    @ApiOperation(value = "下载模板")
    public void importFileTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("/dot/报告归档导入模板.xls");
            //强制下载不打开
            response.setContentType("application/force-download");
            OutputStream out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("zs_report_archieve.xls", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 导入发票明细数据
     *
     * @return
     */
    @DemoMode
    @PostMapping("/importDetail")
    @ApiLog(value = "导入发票明细数据excel")
    public ResponseEntity importDetail(MultipartFile file, HttpServletRequest request) throws Exception {

        ArrayList<ZsReportArchieveExport> arrayList = new ArrayList<>();

        List<ZsReportArchieveExport> listA = new ArrayList<>();
        //获取sheet
        listA = EasyPoiUtil.importExcel(file, 1, 1, ZsReportArchieveExport.class);
        //去除excel中的空行
        listA = getExcelList(listA);
        //将示例行去除掉
        listA.removeIf(item -> {
            String number = (item).getNumber();
            return number != null && number.contains("例");
        });
        if(listA.isEmpty()){
            return ResponseEntity.badRequest().body("导入数据为空，导入失败！如导入表格中存在示例行，请将示例行进行删除");
        }
        //导入前检测数据
        String resultA = reportArchieveService.importDecide(listA, arrayList);
        if(StringUtils.isNotBlank(resultA)){
            //有返回值，说明导入的数据不正确。向用户抛提示
            return ResponseEntity.badRequest().body  (resultA);
        }

        return ResponseEntity.ok("导入成功");
    }

    /**
     * 去除excel中的空行
     * @param list
     * @return
     */
    public ArrayList<ZsReportArchieveExport> getExcelList(List<ZsReportArchieveExport> list){

        ArrayList<ZsReportArchieveExport> financeInvoiceDetailDTOS = new ArrayList<>();

        list.stream().forEach(item->{
            if(objectCheckIsNull(item)){
                financeInvoiceDetailDTOS.add(item);
            }
        });

        return financeInvoiceDetailDTOS;
    }

    public static boolean objectCheckIsNull(Object object) {
        boolean flag = false; //定义返回结果，默认为true

        if (Objects.isNull(object)) {
            flag = false;
        } else {
            Class clazz = (Class) object.getClass(); // 得到类对象
            Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
            for (Field field : fields) {
                if("serialVersionUID".equals(field.getName()) || "BIZ_CODE".equalsIgnoreCase(field.getName())){
                    continue;
                }
                field.setAccessible(true);
                Object fieldValue = null;
                try {
                    fieldValue = field.get(object); //得到属性值
                    Type fieldType = field.getGenericType();//得到属性类型
                    String fieldName = field.getName(); // 得到属性名
                    log.info("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
                } catch (IllegalArgumentException e) {
                    log.error(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    log.error(e.getMessage(), e);
                }
                if (fieldValue != null && fieldValue != "") {  //只要有一个属性值不为null 就返回false 表示对象不为null
                    flag = true;
                    break;
                }
            }
        }

        return flag;
    }



    /**
     * 查询
     * @param id
     * @return
     */
    @ApiOperation(value = "查询")
    @GetMapping("/queryById")
    public ResponseEntity<ZsReportArchieve> queryById(@RequestParam String id) throws Exception{
        ZsReportArchieve dto = reportArchieveService.findById(id);
        return ResponseEntity.ok(dto);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @GetMapping("/remove")
    public ResponseEntity<String> remove(@RequestParam String id){
        String s = reportArchieveService.remove(id);
        return ResponseEntity.ok(s);
    }


    /**
     * 根据报告文号类型查询最新的报告文号
     * @param reportNoType
     * @return
     */
    @ApiOperation(value = "根据报告文号类型查询最新的报告文号")
    @GetMapping("/getReportNo")
    public ResponseEntity<ZsReportArchieve> getReportNo(@RequestParam String reportNoType) throws Exception{
        ZsReportArchieve dto = reportArchieveService.findByReportNoType(reportNoType);
        return ResponseEntity.ok(dto);
    }
    /**
     * 根据报告文号查询最新的盒号
     * @return
     */
    @ApiOperation(value = "根据报告文号查询最新的盒号")
    @GetMapping("/getFileBoxNumber")
    public ResponseEntity<ZsReportArchieve> getFileBoxNumber(@RequestParam String reportNo) throws Exception{
        ZsReportArchieve dto = reportArchieveService.findByReportNo(reportNo);
        return ResponseEntity.ok(dto);
    }

    /**
     * 根据盒号查询修改人
     * @param fileBoxNumber
     * @return
     */
    @ApiOperation(value = "根据盒号查询修改人")
    @GetMapping("/checkFileBoxNumber")
    public boolean checkFileBoxNumber(@RequestParam String fileBoxNumber,@RequestParam String reportNoType) throws Exception{
        boolean dto = reportArchieveService.findByFileBoxNumber(fileBoxNumber,reportNoType);
        return dto;
    }

    /**
     * 校验报告文号类型与报告文号是否一致
     * @return
     */
    @ApiOperation(value = "校验报告文号类型与报告文号是否一致")
    @GetMapping("/checkReportTypeAndReportNo")
    public boolean checkReportTypeAndReportNo(@RequestParam String reportNoType,@RequestParam String reportNo) throws Exception{
        boolean dto = reportArchieveService.checkReportTypeAndReportNo(reportNoType,reportNo);
        return dto;
    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改")
    @PostMapping("/saveForm")
    public ResponseEntity<String> saveForm(@RequestBody ZsReportArchieve reportArchieve){
        String s = reportArchieveService.saveForm(reportArchieve);
        return ResponseEntity.ok(s);

    }

    @ApiLog(value = "报告归档数据", type = LogTypeEnum.EXPORT)
    @GetMapping("exportFile")
    @ApiOperation(value = "报告归档数据")
    public void exportFile(ZsReportArchieveExport zsReportArchieveExport, Page <ZsReportArchieveExport> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename();
        String sheetName = options.getSheetName();
        List<ZsReportArchieveExport> result = new ArrayList<>();
        if ( ExportMode.current.equals ( options.getMode() ) ) {
            result = reportArchieveService.exportList (page,zsReportArchieveExport).getRecords();
        } else if (ExportMode.selected.equals ( options.getMode() )) {
            result = reportArchieveService.exportList (page,zsReportArchieveExport).getRecords().stream ( ).filter ( item ->
                    options.getSelectIds ( ).contains ( item.getId ( ) )
            ).collect ( Collectors.toList ( ) );
        } else {
            page.setSize (-1);
            page.setCurrent (0);
            result = reportArchieveService.exportList (page,zsReportArchieveExport).getRecords();
        }
        Integer count = 0;
        if(result.size()>0){
            //获取字典数据
            String businessTypeDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("business_type");
            Map<String,Object> businessTypeValueDTOs = JSON.parseObject(businessTypeDatas, new TypeReference<Map<String,Object>>() {});

//            String storagePlaceDatas = SpringUtil.getBean ( IDictApi.class ).getDictListMapByDict ("storage_place");
//            Map<String,Object> storagePlaceValueDTOs = JSON.parseObject(storagePlaceDatas, new TypeReference<Map<String,Object>>() {});

            for (ZsReportArchieveExport info : result) {

                if(com.jeeplus.utils.StringUtils.isNotBlank(info.getBusinessType())){
                    for (String key : businessTypeValueDTOs.keySet()) {
                        if(info.getBusinessType().equals(key)){
                            info.setBusinessType(String.valueOf(businessTypeValueDTOs.get(key)));
                            break;
                        }
                    }
                }
                if(com.jeeplus.utils.StringUtils.isNotBlank(info.getStoragePlace())){
                    String replace = info.getStoragePlace().replace(",", "区");
                    String place = "江苏分所 "+replace+"区";
                    info.setStoragePlace(place);
                }
                if (StringUtils.isNotBlank(info.getSpecialPlace())){
                    info.setStoragePlace(info.getSpecialPlace());
                }
                count+=1;
                info.setNumber(count+"");

            }
        }
        ZSEasyPoiUtil.exportExcel ( result, sheetName,  sheetName, ZsReportArchieveExport.class, fileName, response );

    }


    /**
     * 根据报告年份修改文档存放位置
     * @param reportArchieve
     * @return
     */
    @ApiOperation(value = "根据报告年份修改文档存放位置")
    @PostMapping(value = "/updatePlaceByYear")
    public ResponseEntity< Map<String, Object>> updatePlaceByYear(@RequestBody  ZsReportArchieve reportArchieve) {
        int rows = reportArchieveService.updatePlaceByYear(reportArchieve);
        Map<String, Object> result = new HashMap<>();
        if (rows > 0) {
            result.put("code", 0); // 0 表示成功
            result.put("message", "操作成功，共转移 " + rows + " 条份报告");
        } else {
            result.put("code", 1); // 1 表示失败
            result.put("message", "未找到对应年份的数据");
        }
        return ResponseEntity.ok(result);
    }

}
