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.DHighValueInfoPreImp;
import com.ruoyi.dimp.domain.DMarketsubDataInfo;
import com.ruoyi.dimp.domain.DMarketsubDataInfoPreDetail;
import com.ruoyi.dimp.domain.DMarketsubDataInfoPreImp;
import com.ruoyi.dimp.service.IDMarketsubDataInfoPreDetailService;
import com.ruoyi.dimp.service.IDMarketsubDataInfoPreImpService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;

/**
 * 市场主体数据导入记录Controller
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@RestController
@RequestMapping("/dimp/dMarketsubDataInfoPreImp")
public class DMarketsubDataInfoPreImpController extends BaseController {
    private final IDMarketsubDataInfoPreImpService dMarketsubDataInfoPreImpService;
    @Autowired
    private IDMarketsubDataInfoPreDetailService dMarketsubDataInfoPreDetailService;
    @Autowired
    private IBladeRegionService bladeRegionService;

    public DMarketsubDataInfoPreImpController(IDMarketsubDataInfoPreImpService dMarketsubDataInfoPreImpService) {
        this.dMarketsubDataInfoPreImpService = dMarketsubDataInfoPreImpService;
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<DMarketsubDataInfo> util = new ExcelUtil<DMarketsubDataInfo>(DMarketsubDataInfo.class);
        List<DMarketsubDataInfo> list = new ArrayList<DMarketsubDataInfo>();
        
        List<BladeRegion> brList= bladeRegionService.selectAllCityList();
        for(BladeRegion br:brList) {
        	DMarketsubDataInfo m=new DMarketsubDataInfo();
        	m.setCityName(br.getName());
        	list.add(m);
        }
        
        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("先选择年份");
    	}
    	
    	
        DMarketsubDataInfoPreImp imp = dMarketsubDataInfoPreImpService.importData(file,year);
        // 正在解析
        DMarketsubDataInfoPreImp u1 = new DMarketsubDataInfoPreImp();
        u1.setId(imp.getId());
        u1.setImpState(PreImpStatus.IMP_ING);
        dMarketsubDataInfoPreImpService.updateById(u1);
        Thread pdImpThread = new Thread() {
            public void run() {
                try {
                    // 预处理
                    List<DMarketsubDataInfoPreDetail> list = dMarketsubDataInfoPreDetailService.doPreImp(imp);
                    if(list==null || list.isEmpty()) {
                    	DMarketsubDataInfoPreImp u1 = new DMarketsubDataInfoPreImp();
						u1.setId(imp.getId());
						u1.setImpState(PreImpStatus.PARSE_ERR);
						String errReason = "没有读到数据，可能模板错误或空文件";
						u1.setErrReason(errReason);
						dMarketsubDataInfoPreImpService.updateById(u1);
						return;
					}
                    
                    // 处理
                    dMarketsubDataInfoPreDetailService.doImp(list, imp);
                } catch (Exception e) {
                    logger.error("导入时发生成异常," + e.getMessage(), e);

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

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


    /**
     * 查询市场主体数据导入记录列表
     *
     * @param dMarketsubDataInfoPreImp 市场主体数据导入记录
     * @return 市场主体数据导入记录集合
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dMarketsubDataInfoPreImp:list')")
    @GetMapping("/list")
    public TableDataInfo list(DMarketsubDataInfoPreImp dMarketsubDataInfoPreImp) {
        startPage();
        List<DMarketsubDataInfoPreImp> list = dMarketsubDataInfoPreImpService.queryList(dMarketsubDataInfoPreImp);
        return getDataTable(list);
    }


    /**
     * 导出市场主体数据导入记录列表
     *
     * @param dMarketsubDataInfoPreImp 市场主体数据导入记录
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dMarketsubDataInfoPreImp:export')")
    @Log(title = "市场主体数据导入记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DMarketsubDataInfoPreImp dMarketsubDataInfoPreImp) {
        List<DMarketsubDataInfoPreImp> list = dMarketsubDataInfoPreImpService.list(new QueryWrapper<>());
        ExcelUtil<DMarketsubDataInfoPreImp> util = new ExcelUtil<>(DMarketsubDataInfoPreImp.class);
        util.exportExcel(response, list, "市场主体数据导入记录数据");
    }

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


    /**
     * 新增市场主体数据导入记录信息
     *
     * @param dMarketsubDataInfoPreImp 市场主体数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dMarketsubDataInfoPreImp:add')")
    @Log(title = "市场主体数据导入记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DMarketsubDataInfoPreImp dMarketsubDataInfoPreImp) {
        return toAjax(dMarketsubDataInfoPreImpService.save(dMarketsubDataInfoPreImp));
    }


    /**
     * 修改市场主体数据导入记录信息
     *
     * @param dMarketsubDataInfoPreImp 市场主体数据导入记录
     * @return 结果
     * @date 2023-03-19
     */
    @PreAuthorize("@ss.hasPermi('dimp:dMarketsubDataInfoPreImp:edit')")
    @Log(title = "市场主体数据导入记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DMarketsubDataInfoPreImp dMarketsubDataInfoPreImp) {
        return toAjax(dMarketsubDataInfoPreImpService.updateById(dMarketsubDataInfoPreImp));
    }


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


}
