package com.ruoyi.dimp.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.PreImpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dimp.domain.DHighValueInfo;
import com.ruoyi.dimp.domain.DHighValueInfoExp2;
import com.ruoyi.dimp.domain.DHighValueInfoPreDetail;
import com.ruoyi.dimp.domain.DHighValueInfoPreImp;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreImp;
import com.ruoyi.dimp.service.IDHighValueInfoPreDetailService;
import com.ruoyi.dimp.service.IDHighValueInfoPreImpService;

/**
 * 高价值数据导入记录Controller
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@RestController
@RequestMapping("/dimp/dHighValueInfoPreImp")
public class DHighValueInfoPreImpController extends BaseController {
    private final IDHighValueInfoPreImpService dHighValueInfoPreImpService;
    
    @Autowired
    private IDHighValueInfoPreDetailService dHighValueInfoPreDetailService;

    public DHighValueInfoPreImpController(IDHighValueInfoPreImpService dHighValueInfoPreImpService) {
        this.dHighValueInfoPreImpService = dHighValueInfoPreImpService;
    }


    /**
     * 查询高价值数据导入记录列表
     *
     * @param dHighValueInfoPreImp 高价值数据导入记录
     * @return 高价值数据导入记录集合
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:list')")
    @GetMapping("/list")
    public TableDataInfo list(DHighValueInfoPreImp dHighValueInfoPreImp) {
        startPage();
        List<DHighValueInfoPreImp> list = dHighValueInfoPreImpService.queryList(dHighValueInfoPreImp);
        
        TableDataInfo tb=getDataTable(list);
        
        for(DHighValueInfoPreImp p:list) {
        	if(StringUtils.isNotBlank(p.getImpBatch()) && p.getImpBatch().trim().length()>4) {
        		p.setImpBatch(p.getImpBatch().trim().substring(0,4));
        	}
        }
        
        return tb;
        
    }
    
    @PostMapping("/importTemplate")
	public void importTemplate(HttpServletResponse response) {
		ExcelUtil<DHighValueInfoExp2> util = new ExcelUtil<DHighValueInfoExp2>(DHighValueInfoExp2.class);
		List<DHighValueInfoExp2>list=new ArrayList<DHighValueInfoExp2>();
		util.exportExcel(response, list, "高价值专利数据");
	}
    
    
    @PostMapping("/import")
	@Log(title = "高价值专利数据导入", businessType = BusinessType.IMPORT)
	@ResponseBody
    public AjaxResult importData(MultipartFile file,HttpServletRequest req) throws Exception {
    	
    	String impBatch = req.getParameter("impBatch");
    	
    	if(StringUtils.isBlank(impBatch)  || "null".equalsIgnoreCase(impBatch)) {
			throw new RuntimeException("导入年份不能为空");
		}
    	
    	if(impBatch!=null) {
    		impBatch=impBatch.replace("-", "").trim();
    	}
    	if(impBatch.length()==4) {
    		impBatch=impBatch+"12";
    	}
    	
//    	if(StringUtils.isBlank(impBatch)) {
//			throw new RuntimeException("导入批次不能为空");
//		}
    	
    	DHighValueInfoPreImp imp = dHighValueInfoPreImpService.importData(file,impBatch);
		// 正在解析
    	DHighValueInfoPreImp u1 = new DHighValueInfoPreImp();
		u1.setId(imp.getId());
		u1.setImpState(PreImpStatus.IMP_ING);
		dHighValueInfoPreImpService.updateById(u1);
		Thread pdImpThread = new Thread() {
			public void run() {
				try {
					// 预处理
					List<DHighValueInfoPreDetail> list = dHighValueInfoPreDetailService.doPreImp(imp);
					if(list==null || list.isEmpty()) {
						DHighValueInfoPreImp u1 = new DHighValueInfoPreImp();
						u1.setId(imp.getId());
						u1.setImpState(PreImpStatus.PARSE_ERR);
						String errReason = "没有读到数据，可能模板错误或空文件";
						u1.setErrReason(errReason);
						dHighValueInfoPreImpService.updateById(u1);
						return;
					}
					
					// 处理
					dHighValueInfoPreDetailService.doImp(list, imp);
				} catch (Exception e) {
					logger.error("导入时发生成异常," + e.getMessage(), e);

					DHighValueInfoPreImp u1 = new DHighValueInfoPreImp();
					u1.setId(imp.getId());
					u1.setImpState(PreImpStatus.PARSE_ERR);
					String errReason = e.getMessage();
					if (errReason.length() > 3000) {
						errReason = errReason.substring(0, 3000);
					}
					u1.setErrReason(errReason);
					dHighValueInfoPreImpService.updateById(u1);

				}
			}
		};
		pdImpThread.setName("pdImpThread");
		pdImpThread.setDaemon(true);
		pdImpThread.start();
		return AjaxResult.success("系统已接收，请稍后留意导入状态");
    }


    /**
     * 导出高价值数据导入记录列表
     *
     * @param dHighValueInfoPreImp 高价值数据导入记录
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, DHighValueInfoPreImp dHighValueInfoPreImp) {
        List<DHighValueInfoPreImp> list = dHighValueInfoPreImpService.list(new QueryWrapper<>());
        ExcelUtil<DHighValueInfoPreImp> util = new ExcelUtil<>(DHighValueInfoPreImp. class);
        util.exportExcel(response, list, "高价值数据导入记录数据");
    }

    /**
     * 获取高价值数据导入记录详细信息
     *
     * @param id 主键id
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(dHighValueInfoPreImpService.getById(id));
    }


    /**
     * 新增高价值数据导入记录信息
     *
     * @param dHighValueInfoPreImp 高价值数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:add')")
    @Log(title = "高价值数据导入记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DHighValueInfoPreImp dHighValueInfoPreImp) {
        return toAjax(dHighValueInfoPreImpService.save(dHighValueInfoPreImp));
    }


    /**
     * 修改高价值数据导入记录信息
     *
     * @param dHighValueInfoPreImp 高价值数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:edit')")
    @Log(title = "高价值数据导入记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DHighValueInfoPreImp dHighValueInfoPreImp) {
        return toAjax(dHighValueInfoPreImpService.updateById(dHighValueInfoPreImp));
    }


    /**
     * 删除高价值数据导入记录信息
     *
     * @param ids 主键ids
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dHighValueInfoPreImp:remove')")
    @Log(title = "高价值数据导入记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(dHighValueInfoPreImpService.removeByIds(Arrays.asList(ids)));
    }


}
