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.apache.commons.lang3.StringUtils;
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.poi.ExcelUtil;
import com.ruoyi.dimp.domain.DPatentAuthInfoPreImp;
import com.ruoyi.dimp.domain.DPopulationDataInfo;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreDetail;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreImp;
import com.ruoyi.dimp.service.IDPopulationDataInfoPreDetailService;
import com.ruoyi.dimp.service.IDPopulationDataInfoPreImpService;

/**
 * 云南人口数据导入记录Controller
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@RestController
@RequestMapping("/dimp/dPopulationDataInfoPreImp")
public class DPopulationDataInfoPreImpController extends BaseController {
    private final IDPopulationDataInfoPreImpService dPopulationDataInfoPreImpService;
    @Autowired
    private IDPopulationDataInfoPreDetailService dPopulationDataInfoPreDetailService;

    public DPopulationDataInfoPreImpController(IDPopulationDataInfoPreImpService dPopulationDataInfoPreImpService) {
        this.dPopulationDataInfoPreImpService = dPopulationDataInfoPreImpService;
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<DPopulationDataInfo> util = new ExcelUtil<DPopulationDataInfo>(DPopulationDataInfo.class);
        List<DPopulationDataInfo> list = new ArrayList<DPopulationDataInfo>();
        util.exportExcel(response, list, "云南人口数据");
    }

    @PostMapping("/import")
    @Log(title = "云南人口数据导入", businessType = BusinessType.IMPORT)
    @ResponseBody
    public AjaxResult importData(MultipartFile file, HttpServletRequest req) throws Exception {
    	
    	String year = req.getParameter("year");
    	if(year!=null) {
    		year=year.replace("-", "").trim();
    	}
    	if(StringUtils.isBlank(year) || "null".equalsIgnoreCase(year)) {
    		throw new RuntimeException("先选择年份");
    	}
    	
    	
        DPopulationDataInfoPreImp imp = dPopulationDataInfoPreImpService.importData(file,year);
        // 正在解析
        DPopulationDataInfoPreImp u1 = new DPopulationDataInfoPreImp();
        u1.setId(imp.getId());
        u1.setImpState(PreImpStatus.IMP_ING);
        dPopulationDataInfoPreImpService.updateById(u1);
        Thread pdImpThread = new Thread() {
            public void run() {
                try {
                    // 预处理
                    List<DPopulationDataInfoPreDetail> list = dPopulationDataInfoPreDetailService.doPreImp(imp);
                    if(list==null || list.isEmpty()) {
                    	DPopulationDataInfoPreImp u1 = new DPopulationDataInfoPreImp();
						u1.setId(imp.getId());
						u1.setImpState(PreImpStatus.PARSE_ERR);
						String errReason = "没有读到数据，可能模板错误或空文件";
						u1.setErrReason(errReason);
						dPopulationDataInfoPreImpService.updateById(u1);
						return;
					}
                    
                    // 处理
                    dPopulationDataInfoPreDetailService.doImp(list, imp);
                } catch (Exception e) {
                    logger.error("导入时发生成异常," + e.getMessage(), e);

                    DPopulationDataInfoPreImp u1 = new DPopulationDataInfoPreImp();
                    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);
                    dPopulationDataInfoPreImpService.updateById(u1);

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


    /**
     * 查询云南人口数据导入记录列表
     *
     * @param dPopulationDataInfoPreImp 云南人口数据导入记录
     * @return 云南人口数据导入记录集合
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dPopulationDataInfoPreImp:list')")
    @GetMapping("/list")
    public TableDataInfo list(DPopulationDataInfoPreImp dPopulationDataInfoPreImp) {
        startPage();
        List<DPopulationDataInfoPreImp> list = dPopulationDataInfoPreImpService.queryList(dPopulationDataInfoPreImp);
        return getDataTable(list);
    }


    /**
     * 导出云南人口数据导入记录列表
     *
     * @param dPopulationDataInfoPreImp 云南人口数据导入记录
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dPopulationDataInfoPreImp:export')")
    @Log(title = "云南人口数据导入记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DPopulationDataInfoPreImp dPopulationDataInfoPreImp) {
        List<DPopulationDataInfoPreImp> list = dPopulationDataInfoPreImpService.list(new QueryWrapper<>());
        ExcelUtil<DPopulationDataInfoPreImp> util = new ExcelUtil<>(DPopulationDataInfoPreImp.class);
        util.exportExcel(response, list, "云南人口数据导入记录数据");
    }

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


    /**
     * 新增云南人口数据导入记录信息
     *
     * @param dPopulationDataInfoPreImp 云南人口数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dPopulationDataInfoPreImp:add')")
    @Log(title = "云南人口数据导入记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DPopulationDataInfoPreImp dPopulationDataInfoPreImp) {
        return toAjax(dPopulationDataInfoPreImpService.save(dPopulationDataInfoPreImp));
    }


    /**
     * 修改云南人口数据导入记录信息
     *
     * @param dPopulationDataInfoPreImp 云南人口数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dPopulationDataInfoPreImp:edit')")
    @Log(title = "云南人口数据导入记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DPopulationDataInfoPreImp dPopulationDataInfoPreImp) {
        return toAjax(dPopulationDataInfoPreImpService.updateById(dPopulationDataInfoPreImp));
    }


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


}
