package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.UseEngergy;
import com.nantian.cloud.jljc.entity.ZstbInfo;
import com.nantian.cloud.jljc.entity.ZstbProduce;
import com.nantian.cloud.jljc.mapper.DictRegionMapper;
import com.nantian.cloud.jljc.service.DictRegionService;
import com.nantian.cloud.jljc.service.UseEngergyService;
import com.nantian.cloud.jljc.service.ZstbProduceService;
import com.nantian.cloud.jljc.tools.LpExcelUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/useEngergy")
@Api(value = "useEngergy", tags = "重点企业用能情况表")
public class TUseEngergyController {

    @Autowired
    private UseEngergyService useEngergyService;

    @Autowired
    private ZstbProduceService zstbProduceService;

    @Autowired
    private DictRegionService regionService;

    @SysLog("分页获取重点企业用能情况表")
    @ApiOperation(value = "分页获取重点企业用能情况表", notes = "分页获取重点企业用能情况表")
    @RequestMapping("/page")
    public R page(Page page, UseEngergy useEngergy) {
//        Page<UseEngergy> pg = new Page<>(page.getCurrent()current, size);
//        page.setDesc("add_time");
        List<UseEngergy> list = new ArrayList<>();
        ScUser u = SecurityUtils.getUser();
        if (u.getDeptId().toString().equals("530000")){
            useEngergy.setReportStatus("\"city\":\"1\"");
            list = useEngergyService.getPage(page, useEngergy);
        }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
            useEngergy.setReportStatus("\"country\":\"1\"");
            list = useEngergyService.getPage(page, useEngergy);
            Comparator<UseEngergy> reversed = Comparator.comparing(UseEngergy::getAdminisFlag).reversed();
            Comparator<UseEngergy> comparing = Comparator.comparing(UseEngergy::getAuditorFlag);
            if (list.size() > 0){
                list.sort(reversed.thenComparing(comparing));
            }
//            list.sort(Comparator.comparing(UseEngergy::getAdminisFlag).reversed()); //按照行政区划排序 ，州市在前，区县在后
        }else {
            list = useEngergyService.getPage(page, useEngergy);
            if (list.size() > 0){
                list.sort(Comparator.comparing(UseEngergy::getAuditorFlag));
            }
        }

        // 子表
        if (list.size() != 0) {
            list.forEach(item -> {
                QueryWrapper<ZstbProduce> query = new QueryWrapper<>();
                query.eq("use_engergy_id", item.getId());
                query.eq("del_flag", "1");
                List<ZstbProduce> produces = zstbProduceService.list(query);
                item.setProduceList(produces);
            });
        }
        page.setRecords(list);
        return R.ok(page);
    }

    /**
     * 数据审核接口, 审核通过后数据自动上报至省级部门
     * @param useEngergy
     * @return
     */
    @SysLog("审核重点企业用能情况表")
    @PutMapping("/auditData")
    public R auditData(@RequestBody String useEngergy){
        JSONObject jsonObject = JSONObject.parseObject(useEngergy);
        String data = jsonObject.getString("auditorFlag");
        UseEngergy s =  JSONArray.parseObject(data, UseEngergy.class);
        ScUser u = SecurityUtils.getUser();
        String deptId = u.getDeptId().toString();
        UseEngergy info = useEngergyService.getById(s.getId());
        String auditUser = info.getAuditUser();
        JSONObject object = JSONObject.parseObject(auditUser);
        if (("530000").equals(deptId)){ //省级审核
            object.replace("province", u.getUserRealName());
            s.setAuditUser(JSONObject.toJSONString(object));
        }else if (deptId.substring(deptId.length() - 2).equals("00")){ //州市审核
            object.replace("city", u.getUserRealName());
            s.setAuditUser(JSONObject.toJSONString(object));
        }else {
            return R.failed("区县用户不能审核数据！");
        }
        s.setDelFlag("1");
        s.setUpdateTime(new Date());
        useEngergyService.updateById(s);
        return R.ok();
    }

    /**
     * 上报数据
     * @param useEngergies
     * @return
     */
    @PutMapping("/reportData")
    @SysLog("上报重点企业用能情况表")
    public R reportDataList(@RequestBody String useEngergies){
        JSONObject jsonObject = JSONObject.parseObject(useEngergies);
        String data = jsonObject.getString("useEngergys");
        List<UseEngergy> s = (List<UseEngergy>) JSONArray.parseArray(data, UseEngergy.class);
        ScUser u = SecurityUtils.getUser();
        String deptId = u.getDeptId().toString();
        if (deptId.equals("530000")){
            return R.failed("省级用户不需要进行数据上报操作！");
        }else if (deptId.substring(deptId.length() - 2).equals("00")){ //州市数据上报
            if (s.size() > 0){
                s.forEach(useEngergy -> {
                    UseEngergy info = useEngergyService.getById(useEngergy.getId());
                    String reportUser = info.getReportUser();
                    String reportStatus = info.getReportStatus();
                    JSONObject reportUserJson = JSONObject.parseObject(reportUser);
                    JSONObject reportStatusJson = JSONObject.parseObject(reportStatus);
                    reportUserJson.replace("city", u.getUserRealName());
                    reportStatusJson.replace("city", "1");
                    useEngergy.setReportUser(JSONObject.toJSONString(reportUserJson));
                    useEngergy.setReportStatus(JSONObject.toJSONString(reportStatusJson));
                });
            }
            useEngergyService.updateBatchById(s);
            return R.ok();
        }else { //区县数据上报
            s.forEach(useEngergy -> {
                UseEngergy info = useEngergyService.getById(useEngergy.getId());
                String reportUser = info.getReportUser();
                String reportStatus = info.getReportStatus();
                JSONObject reportUserJson = JSONObject.parseObject(reportUser);
                JSONObject reportStatusJson = JSONObject.parseObject(reportStatus);
                reportUserJson.replace("country", u.getUserRealName());
                reportStatusJson.replace("country", "1");
                useEngergy.setReportUser(JSONObject.toJSONString(reportUserJson));
                useEngergy.setReportStatus(JSONObject.toJSONString(reportStatusJson));
            });
            useEngergyService.updateBatchById(s);
            return R.ok();
        }
    }

    @SysLog("重点企业用能情况表汇总数据查询")
    @ApiOperation(value = "获取汇总数据", notes = "获取汇总数据")
    @RequestMapping("/total")
    public R total( UseEngergy useEngergy) {
        List<UseEngergy> list = useEngergyService.getTotal(useEngergy);
        return R.ok(list);
    }

    @SysLog("根据id查询重点企业用能情况表")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @RequestMapping("/getById")
    public R getById(String bId) {
        UseEngergy byId = useEngergyService.getById(bId);
        QueryWrapper<ZstbProduce> query = new QueryWrapper<>();
        query.eq("use_engergy_id", byId.getId());
        query.eq("del_flag", "1");
        List<ZstbProduce> produces = zstbProduceService.list(query);
        byId.setProduceList(produces);
        byId.setAreaTmp(regionService.getAreaTmp(byId.getArea()));
        return R.ok(byId);
    }

    @SysLog("修改重点企业用能情况表")
    @ApiOperation(value = "编辑重点企业用能情况表", notes = "编辑重点企业用能情况表")
    @RequestMapping("/edit")
    public R edit(@RequestBody UseEngergy useEngergy) {
        Date date = new Date();
        Map<String, String> json = new HashMap<>();
        json.put("country", "");
        json.put("city", "");
        Map<String, String> jsonObject = new HashMap<>();
        jsonObject.put("city", "");
        jsonObject.put("province", "");
        if (useEngergy.getId() == null) {
//            List<UseEngergy> list = useEngergyService.list(new QueryWrapper<UseEngergy>()
//                    .eq("enterprise_name", useEngergy.getEnterpriseName()).eq("del_flag", "1"));
//            if (list.size() > 0){ //处理以前存在的数据，全部设置为删除状态
//                list.forEach(u -> {
//                    u.setDelFlag("4");
//                    List<ZstbProduce> produceList = zstbProduceService.list(new QueryWrapper<ZstbProduce>()
//                            .eq("use_engergy_id", u.getId()).eq("del_flag", "1"));
//                    if (produceList.size() > 0){
//                        produceList.forEach(p -> {
//                            p.setDelFlag("4");
//                        });
//                        zstbProduceService.updateBatchById(produceList);
//                    }
//                });
//                useEngergyService.updateBatchById(list);
//            }
            ScUser u = SecurityUtils.getUser();
            useEngergy.setDeptId(u.getDeptId().toString());
            useEngergy.setDelFlag("1");
            useEngergy.setAddTime(date);

            if (u.getDeptId().toString().equals("530000")){
                useEngergy.setAdminisFlag("");
                useEngergy.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "1");
                json.replace("city", "1");
                useEngergy.setReportStatus(JSONObject.toJSONString(json));
                useEngergy.setUpdateUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setAuditUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "1");
                jsonObject.replace("province", "1");
                useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
                useEngergy.setAdminisFlag("2");
                useEngergy.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "1");
                json.replace("city", "0");
                useEngergy.setReportStatus(JSONObject.toJSONString(json));
                useEngergy.setUpdateUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setAuditUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "1");
                jsonObject.replace("province", "0");
                useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }else {
                useEngergy.setAdminisFlag("1");
                useEngergy.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "0");
                json.replace("city", "0");
                useEngergy.setReportStatus(JSONObject.toJSONString(json));
                useEngergy.setUpdateUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setAuditUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "0");
                jsonObject.replace("province", "0");
                useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }
//            useEngergy.setUpdateUser(u.getUserRealName());
            useEngergyService.save(useEngergy);

            if (useEngergy.getProduceList().size() != 0) {
                List<ZstbProduce> ps = useEngergy.getProduceList();
                ps.forEach(item -> {
                    item.setUseEngergyId(useEngergy.getId());
                    item.setAddTime(date);
                    zstbProduceService.save(item);
                });
            }
        } else {

            /*List<UseEngergy> list = useEngergyService.list(new QueryWrapper<UseEngergy>()
                    .eq("enterprise_name", useEngergy.getEnterpriseName()).eq("del_flag", "1"));
            if (list.size() > 0){ //处理以前存在的数据，全部设置为删除状态
                list.forEach(u -> {
                    u.setDelFlag("4");
                    List<ZstbProduce> produceList = zstbProduceService.list(new QueryWrapper<ZstbProduce>()
                            .eq("use_engergy_id", u.getId()).eq("del_flag", "1"));
                    if (produceList.size() > 0){
                        produceList.forEach(p -> {
                            p.setDelFlag("4");
                        });
                        zstbProduceService.updateBatchById(produceList);
                    }
                });
                useEngergyService.updateBatchById(list);
            }*/

            ScUser u = SecurityUtils.getUser();
            String auditorFlag = useEngergy.getAuditorFlag();
            if (auditorFlag.contains("2")){
                Map<String, String> map = new HashMap<>();
                map.put("city", "0");
                map.put("province", "0");
                useEngergy.setAuditorFlag(JSONObject.toJSONString(map));
                map.replace("city", "");
                map.replace("province", "");
                useEngergy.setCause(JSONObject.toJSONString(map));
            }
            useEngergy.setUpdateTime(date);
            String deptId = u.getDeptId().toString();
            if (("530000").equals(deptId)){
                //修改人
                String updateUser = useEngergy.getUpdateUser();
                JSONObject jsonUpdateUser = JSONObject.parseObject(updateUser);
                jsonUpdateUser.replace("province", u.getUserRealName());
                useEngergy.setUpdateUser(jsonUpdateUser.toJSONString());
            }else if (deptId.substring(deptId.length() - 2).equals("00")){
                if (deptId.equals(useEngergy.getDeptId())){
                    String updateUser = useEngergy.getUpdateUser();
                    JSONObject jsonUpdateUser = JSONObject.parseObject(updateUser);
                    jsonUpdateUser.replace("city", u.getUserRealName());
                    useEngergy.setUpdateUser(jsonUpdateUser.toJSONString());
                    useEngergy.setAdminisFlag("2");
                    useEngergy.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "0");
                    useEngergy.setReportStatus(JSONObject.toJSONString(json));
                    useEngergy.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    useEngergy.setAuditUser(JSONObject.toJSONString(jsonObject));
                    useEngergy.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else {
                    JSONObject object = JSONObject.parseObject(useEngergy.getUpdateUser());
                    object.replace("city", u.getUserRealName());
                    useEngergy.setUpdateUser(JSONObject.toJSONString(object));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }
            }else {
                useEngergy.setAdminisFlag("1");
                useEngergy.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "0");
                json.replace("city", "0");
                useEngergy.setReportStatus(JSONObject.toJSONString(json));
                useEngergy.setUpdateUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setAuditUser(JSONObject.toJSONString(jsonObject));
                useEngergy.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "0");
                jsonObject.replace("province", "0");
                useEngergy.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }
            useEngergyService.updateById(useEngergy);
            if (useEngergy.getProduceList().size() != 0) {
                List<ZstbProduce> ps = useEngergy.getProduceList();
                ps.forEach(item -> {
                    item.setUpdateTime(new Date());
                    item.setUseEngergyId(useEngergy.getId());
                    item.setUpdateTime(date);
                });
                zstbProduceService.saveOrUpdateBatch(ps);
            }
        }
        return R.ok();
    }

    @SysLog("批量新增重点企业用能情况(提取历史数据新增)")
    @ApiOperation(value = "批量新增重点企业用能情况(提取历史数据新增)", notes = "批量新增重点企业用能情况(提取历史数据新增)")
    @PostMapping("/renewBatch")
    public R saveOrUpdateBatch(@RequestBody String str) {
        JSONObject json = JSONObject.parseObject(str);
        List<UseEngergy> dataList = (List<UseEngergy>) JSONArray.parseArray(json.getString("data"), UseEngergy.class);
        String scYear = json.getString("scYear");
        String scMonth = json.getString("scMonth");
        for (UseEngergy info : dataList) {
            info.setId(null);
            info.setScYear(scYear);
            info.setScMonth(scMonth);
            edit(info);
        }
        return R.ok();
    }

    @SysLog("删除重点企业用能情况表")
    @ApiOperation(value = "删除重点企业用能情况表", notes = "删除重点企业用能情况表")
    @RequestMapping("/remove")
    public R remove(@RequestBody UseEngergy useEngergy) {
        try {
            ScUser u = SecurityUtils.getUser();
            useEngergy.setDeptId(u.getDeptId().toString());
            useEngergy.setDelFlag("4");
            useEngergy.setUpdateUser(u.getUserRealName());
            useEngergyService.updateById(useEngergy);
            //查询产品，逻辑删除产品
            QueryWrapper<ZstbProduce> query = new QueryWrapper<>();
            query.eq("use_engergy_id", useEngergy.getId());
            query.eq("del_flag", "1");
            List<ZstbProduce> produces = zstbProduceService.list(query);
            produces.forEach(r -> {
                r.setDelFlag("4");
            });
            zstbProduceService.updateBatchById(produces);
//            useEngergyService.removeById(useEngergy.getId());
            return R.ok("删除成功");
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }

    @ApiOperation(value = "获取单位", notes = "获取单位")
    @RequestMapping("/getUnit")
    public R getUnit() {
        List<String> unit = useEngergyService.getUnit();
        return R.failed(unit);
    }

    @SysLog("下载重点企业用能情况表模板")
    @ApiOperation(value = "下载模板", notes = "下载模板")
    @RequestMapping(value = {"/template"}, produces = {"application/json;charset=UTF-8"})
    public void template(HttpServletRequest request, HttpServletResponse response, String date) {
        try {
            List<String> strList = useEngergyService.getArea();
            List<String> unit = useEngergyService.getUnit();
            String[] capacityAvi = strList.toArray(new String[strList.size()]);
            String[] unitAvi = unit.toArray(new String[strList.size()]);
            LpExcelUtil.useEngergyTemplate("模板-重点企业用能情况表", request, response, capacityAvi, date, unitAvi);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SysLog("导出重点企业用能情况表")
    @ApiOperation(value = "数据导出", notes = "数据导出")
    @RequestMapping(value = {"/export"}, produces = {"application/json;charset=UTF-8"})
    public void export(HttpServletRequest request, HttpServletResponse response, String scYear, String scMonth, String area) {
        try {
            ScUser u = SecurityUtils.getUser();
            QueryWrapper<UseEngergy> query = new QueryWrapper<>();
//            query.orderByDesc("add_time");
            query.eq("sc_year", scYear);
            query.eq("sc_month", scMonth);
            query.eq("del_flag", '1');
            //query.like("area", area == "undefined" ? "" : area);
            String deptId = u.getDeptId().toString();
            if (deptId.equals("530000")){
                query.like("report_status", "\"city\":\"1\"");
            }else if (deptId.contains("00")){
                query.like("report_status", "\"country\":\"1\"");
                query.like("dept_id", deptId.substring(0,4));
            }else {
                query.like("dept_id", deptId);
            }
            List<UseEngergy> list = useEngergyService.list(query);
            if (deptId.equals("530000")){
            }else if (deptId.substring(deptId.length() - 2).equals("00")){
                Comparator<UseEngergy> reversed = Comparator.comparing(UseEngergy::getAdminisFlag).reversed();
                Comparator<UseEngergy> comparing = Comparator.comparing(UseEngergy::getAuditorFlag);
                if (list.size() > 0){
                    list.sort(reversed.thenComparing(comparing));
                }
//                Comparator<UseEngergy> reversed = Comparator.comparing(UseEngergy::getAdminisFlag).reversed();
//                Comparator<UseEngergy> comparing = Comparator.comparing(UseEngergy::getAuditorFlag);
//                if (list.size() > 0){
//                    list.sort(reversed.thenComparing(comparing));
//                }
            }else {
                if (list.size() > 0){
                    list.sort(Comparator.comparing(UseEngergy::getAuditorFlag));
                }
            }
            // 子表
            if (list.size() != 0) {
                list.forEach(item -> {
                    QueryWrapper<ZstbProduce> query2 = new QueryWrapper<>();
                    query2.eq("use_engergy_id", item.getId());
                    query2.eq("del_flag", "1");
                    List<ZstbProduce> produces = zstbProduceService.list(query2);
                    item.setProduceList(produces);
                });
            }
            Integer deptId1 = SecurityUtils.getUser().getDeptId();
            String region = regionService.getById(deptId1).getMeaning2();
            LpExcelUtil.useEngergyExcel(true, "重点企业用能情况表", list, request, response, scYear, scMonth, region);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Excel数据导入
     *
     * @param file
     * @return
     * @throws FileFormatException
     */
    @RequestMapping("/excelImport")
    @SysLog("导入重点企业用能情况表")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file, String datel) {
        try {
            /*if (file.getOriginalFilename().indexOf("xlsx")!=-1){
                return R.failed("上传文件格式错误！需要为xls");
            }*/
            if (!(file.getOriginalFilename().endsWith("xlsx") || file.getOriginalFilename().endsWith("xls"))) {
                return R.failed("传入文件不是excel格式!");
            }
            List<UseEngergy> list = useEngergyService.excelImport(file, datel);
            if (list.size() == 1 && list.get(0).getEnterpriseName().indexOf("导入失败") != -1) {
                return R.failed(list.get(0).getEnterpriseName());
            }
            Date date = new Date();
            list.forEach(item -> {
                ScUser u = SecurityUtils.getUser();
                item.setDeptId(u.getDeptId().toString());
                item.setDelFlag("1");
                item.setAddTime(date);
                Map<String, String> json = new HashMap<>();
                json.put("country", "");
                json.put("city", "");
                Map<String, String> jsonObject = new HashMap<>();
                jsonObject.put("city", "");
                jsonObject.put("province", "");
                if (u.getDeptId().toString().equals("530000")){
                    item.setAdminisFlag("");
                    item.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "1");
                    item.setReportStatus(JSONObject.toJSONString(json));
                    item.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    item.setAuditUser(JSONObject.toJSONString(jsonObject));
                    item.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "1");
                    item.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
                    item.setAdminisFlag("2");
                    item.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "0");
                    item.setReportStatus(JSONObject.toJSONString(json));
                    item.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    item.setAuditUser(JSONObject.toJSONString(jsonObject));
                    item.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    item.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else {
                    item.setAdminisFlag("1");
                    item.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "0");
                    json.replace("city", "0");
                    item.setReportStatus(JSONObject.toJSONString(json));
                    item.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    item.setAuditUser(JSONObject.toJSONString(jsonObject));
                    item.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "0");
                    jsonObject.replace("province", "0");
                    item.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }
//                item.setUpdateUser(u.getUserRealName());
//                ScUser u = SecurityUtils.getUser();
//                item.setDeptId(u.getDeptId().toString());
//                item.setDelFlag("1");
//                item.setUpdateUser(u.getUserRealName());
//                if (u.getDeptId().toString().equals("530000")){
//                    item.setAdminisFlag("");
//                }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
//                    item.setAdminisFlag("2");
//                }else {
//                    item.setAdminisFlag("1");
//                }
//                item.setAuditorFlag("0");
                item.setScYear(datel.split("-")[0]);
                item.setScMonth(Integer.parseInt(datel.split("-")[1])+"");
                item.setIndustryCode(item.getIndustryCode().replace(".0",""));  //行业编码去除最后的 .0
                useEngergyService.save(item);
                List<ZstbProduce> ps = item.getProduceList();
                ps.forEach(p -> {
                    p.setUseEngergyId(item.getId());
                    p.setAddTime(date);
                    p.setDelFlag("1");
                });
                zstbProduceService.saveBatch(item.getProduceList());
            });
            return R.ok("导入成功");
        } catch (Exception e) {
            return R.failed("程序出错 "+e.getMessage(), "导入失败");
        }
    }


    /**
     * 根据企业名称查询历史填报数据
     */
    @SysLog("根据企业名称查询历史填报重点企业用能情况表")
    @GetMapping("/getElvInfo")
    public R returnEnterpriseInfo(String companyName){
        List<UseEngergy> list = useEngergyService.list(new QueryWrapper<UseEngergy>().eq("enterprise_name", companyName).eq("del_flag", "1"));
        if (list.size() > 0){
            return R.ok(list.get(0));
        }
        return R.ok();
    }

    /**
     * 根据企业名称查询历史填报产品
     */
    @SysLog("根据企业名称查询历史填报产品")
    @GetMapping("/getProduce")
    public R getProduce(String companyName){
        List<UseEngergy> list = useEngergyService.list(new QueryWrapper<UseEngergy>().eq("enterprise_name", companyName).eq("del_flag", "1"));
        if (list.size() > 0){
            UseEngergy useEngergy = list.get(0);
            List<ZstbProduce> produceList = zstbProduceService.list(new QueryWrapper<ZstbProduce>().eq("use_engergy_id", useEngergy.getId()).eq("del_flag", "1"));
            return R.ok(produceList);
        }else {
            return R.failed("查询产品结果为空");
        }
    }
}
