package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.DictRegion;
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.ZstbInfoService;
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("/zstbInfo")
@Api(value = "zstbInfo", tags = "节能评估审查实施情况表")
public class TZstbInfoController {

    @Autowired
    private ZstbInfoService zstbInfoService;

    @Autowired
    private UseEngergyService useEngergyService;

    @Autowired
    private DictRegionService regionService;



    @SysLog("分页获取节能评估审查实施情况表")
    @ApiOperation(value = "分页获取节能评估审查实施情况表", notes = "分页获取节能评估审查实施情况表")
    @RequestMapping("/page")
    public R page(Page page, ZstbInfo zstbInfo) {
        Page<ZstbInfo> list = new Page<>();
        ScUser u = SecurityUtils.getUser();
        String deptId = u.getDeptId().toString();
        if (("530000").equals(deptId)){
            zstbInfo.setReportStatus("\"city\":\"1\"");
            list = zstbInfoService.getPage(page, zstbInfo);
        }else if (deptId.substring(deptId.length() - 2).equals("00")){
            zstbInfo.setReportStatus("\"country\":\"1\"");
            list = zstbInfoService.getPage(page, zstbInfo);
            List<ZstbInfo> records = list.getRecords();
            Comparator<ZstbInfo> reversed = Comparator.comparing(ZstbInfo::getAdminisFlag).reversed();
            Comparator<ZstbInfo> comparing = Comparator.comparing(ZstbInfo::getAuditorFlag);
            if (records.size() > 0){
                records.sort(reversed.thenComparing(comparing));
            }
            list.setRecords(records);
        }else {
            list = zstbInfoService.getPage(page, zstbInfo);
            List<ZstbInfo> records = list.getRecords();
            if (records.size() > 0){
                records.sort(Comparator.comparing(ZstbInfo::getAuditorFlag));
            }
            list.setRecords(records);
        }
        return R.ok(list);
    }

    /**
     * 数据审核接口, 逐级审核
     * @param zstbInfo
     * @return
     */
    @SysLog("审核节能评估审查实施情况表")
    @PutMapping("/auditData")
    public R auditData(@RequestBody String zstbInfo){
        JSONObject jsonObject = JSONObject.parseObject(zstbInfo);
        String data = jsonObject.getString("auditorFlag");
        ZstbInfo s =  JSONArray.parseObject(data, ZstbInfo.class);
        ZstbInfo info = zstbInfoService.getOne(new QueryWrapper<ZstbInfo>().eq("id", s.getId()));
        String auditUser = info.getAuditUser();
        JSONObject object = JSONObject.parseObject(auditUser);
        ScUser u = SecurityUtils.getUser();
        String deptId = u.getDeptId().toString();
        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());
        zstbInfoService.updateById(s);
        return R.ok();
    }

    /**
     * 数据上报
     * @param zstbInfo
     * @return
     */
    @PutMapping("/reportData")
    @SysLog("上报节能评估审查实施情况表")
    public R reportDataList(@RequestBody String zstbInfo){
        JSONObject jsonObject = JSONObject.parseObject(zstbInfo);
        String data = jsonObject.getString("zstbInfo");
        List<ZstbInfo> s = (List<ZstbInfo>) JSONArray.parseArray(data, ZstbInfo.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")){ //州市数据上报
            s.forEach(zstbInfo1 -> {
                ZstbInfo info = zstbInfoService.getOne(new QueryWrapper<ZstbInfo>().eq("id", zstbInfo1.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");
                zstbInfo1.setReportUser(JSONObject.toJSONString(reportUserJson));
                zstbInfo1.setReportStatus(JSONObject.toJSONString(reportStatusJson));
            });
            zstbInfoService.updateBatchById(s);
            return R.ok();
        }else { //区县数据上报
            s.forEach(zstbInfo1 -> {
                ZstbInfo info = zstbInfoService.getOne(new QueryWrapper<ZstbInfo>().eq("id", zstbInfo1.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");
                zstbInfo1.setReportUser(JSONObject.toJSONString(reportUserJson));
                zstbInfo1.setReportStatus(JSONObject.toJSONString(reportStatusJson));
            });
            zstbInfoService.updateBatchById(s);
            return R.ok();
        }
    }

    @SysLog("节能评估审查实施情况表汇总数据")
    @ApiOperation(value = "获取汇总数据", notes = "获取汇总数据")
    @RequestMapping("/total")
    public R total( ZstbInfo zstbInfo) {
        List<ZstbInfo> list = zstbInfoService.getTotal(zstbInfo);
        return R.ok(list);
    }

    @SysLog("编辑节能评估审查实施情况表")
    @ApiOperation(value = "编辑节能评估审查实施情况表", notes = "编辑节能评估审查实施情况表")
    @RequestMapping("/edit")
    public R edit(@RequestBody ZstbInfo zstbInfo) {
        ScUser u = SecurityUtils.getUser();
        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 (zstbInfo.getId() == null) {
            zstbInfo.setDeptId(u.getDeptId().toString());
            zstbInfo.setDelFlag("1");
            zstbInfo.setAddTime(new Date());
            if (u.getDeptId().toString().equals("530000")){
                zstbInfo.setAdminisFlag("");
                zstbInfo.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "1");
                json.replace("city", "1");
                zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "1");
                jsonObject.replace("province", "1");
                zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
                zstbInfo.setAdminisFlag("2");
                zstbInfo.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "1");
                json.replace("city", "0");
                zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "1");
                jsonObject.replace("province", "0");
                zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }else {
                zstbInfo.setAdminisFlag("1");
                zstbInfo.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "0");
                json.replace("city", "0");
                zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "0");
                jsonObject.replace("province", "0");
                zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }
            zstbInfoService.save(zstbInfo);
        } else {
            String deptId = u.getDeptId().toString();
            String auditorFlag = zstbInfo.getAuditorFlag();
            if (auditorFlag.contains("2")){
                Map<String, String> map = new HashMap<>();
                map.put("city", "0");
                map.put("province", "0");
                zstbInfo.setAuditorFlag(JSONObject.toJSONString(map));
                map.replace("city", "");
                map.replace("province", "");
                zstbInfo.setCause(JSONObject.toJSONString(map));
            }
            if (("530000").equals(deptId)){
                //修改人
                String updateUser = zstbInfo.getUpdateUser();
                JSONObject jsonUpdateUser = JSONObject.parseObject(updateUser);
                jsonUpdateUser.replace("province", u.getUserRealName());
                zstbInfo.setUpdateUser(jsonUpdateUser.toJSONString());
            }else if (deptId.substring(deptId.length() - 2).equals("00")){
                //修改人
                if (deptId.equals(zstbInfo.getDeptId())){
                    String updateUser = zstbInfo.getUpdateUser();
                    JSONObject jsonUpdateUser = JSONObject.parseObject(updateUser);
                    jsonUpdateUser.replace("city", u.getUserRealName());
                    zstbInfo.setUpdateUser(jsonUpdateUser.toJSONString());
                    zstbInfo.setAdminisFlag("2");
                    zstbInfo.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "0");
                    zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                    zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else{
                    JSONObject object = JSONObject.parseObject(zstbInfo.getUpdateUser());
                    object.replace("city", u.getUserRealName());
                    zstbInfo.setUpdateUser(JSONObject.toJSONString(object));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }
            }else {
                zstbInfo.setAdminisFlag("1");
                zstbInfo.setReportUser(JSONObject.toJSONString(json));
                json.replace("country", "0");
                json.replace("city", "0");
                zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                jsonObject.replace("city", "0");
                jsonObject.replace("province", "0");
                zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
            }
            zstbInfo.setUpdateTime(new Date());
            zstbInfoService.updateById(zstbInfo);
        }
        return R.ok();
    }

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

    @SysLog("根据id查询节能评估审查实施情况表")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @RequestMapping("/getById")
    public R getById(String bId) {
        ZstbInfo byId = zstbInfoService.getById(bId);
        byId.setAreaTmp(regionService.getAreaTmp(byId.getArea()));
        return R.ok(byId);
    }

    @SysLog("删除节能评估审查实施情况表")
    @ApiOperation(value = "删除节能评估审查实施情况表", notes = "删除节能评估审查实施情况表")
    @RequestMapping("/remove")
    public R remove(@RequestBody ZstbInfo zstbInfo) {
        try {
            zstbInfo.setDelFlag("4");
            zstbInfoService.updateById(zstbInfo);
            return R.ok("删除成功");
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }

    @SysLog("下载节能评估审查实施情况表模板")
    @ApiOperation(value = "下载模板", notes = "下载模板")
    @RequestMapping(value = {"/template"}, produces = {"application/json;charset=UTF-8"})
    public void template(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<String> strList =  useEngergyService.getArea();
            String[] capacityAvi = strList.toArray(new String[strList.size()]);
            Integer deptId = SecurityUtils.getUser().getDeptId();
            String region = regionService.getById(deptId).getMeaning2();
            LpExcelUtil.infoExcel(false, null, "模板-新增固定资产投资项目节能审查实施情况报送信息表", request, response, capacityAvi,null,null, region);
        } 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 {
//            QueryWrapper<ZstbInfo> query = new QueryWrapper<>();
//            query.eq("sc_year",scYear);
//            query.eq("sc_month",scMonth);
//            query.eq("del_flag",'1');
//            query.like("area",area=="undefined"?"":area);
////            query.orderByDesc("add_time");
//            List<ZstbInfo> list = zstbInfoService.list(query);
//            List<String> strList =  useEngergyService.getArea();
//            String[] capacityAvi = strList.toArray(new String[strList.size()]);
//            Integer deptId = SecurityUtils.getUser().getDeptId();
//            String region = regionService.getById(deptId).getMeaning2();
//            LpExcelUtil.infoExcel(true, list, "固定资产投资项目节能审查实施情况报送信息表", request, response, capacityAvi, scYear, scMonth, region);
            ScUser u = SecurityUtils.getUser();
            QueryWrapper<ZstbInfo> 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<ZstbInfo> list = zstbInfoService.list(query);
            if (deptId.equals("530000")){
            }else if (deptId.substring(deptId.length() - 2).equals("00")){
                Comparator<ZstbInfo> reversed = Comparator.comparing(ZstbInfo::getAdminisFlag).reversed();
                Comparator<ZstbInfo> comparing = Comparator.comparing(ZstbInfo::getAuditorFlag);
                if (list.size() > 0){
                    list.sort(reversed.thenComparing(comparing));
                }
            }else {
                if (list.size() > 0){
                    list.sort(Comparator.comparing(ZstbInfo::getAuditorFlag));
                }
            }
            List<String> strList =  useEngergyService.getArea();
            String[] capacityAvi = strList.toArray(new String[strList.size()]);
            Integer deptId1 = SecurityUtils.getUser().getDeptId();
            String region = regionService.getById(deptId1).getMeaning2();
            LpExcelUtil.infoExcel(true, list, "固定资产投资项目节能审查实施情况报送信息表", request, response, capacityAvi, 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 date) {
        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<ZstbInfo> list = zstbInfoService.excelImport(file,date);
            if (list.size()==1&&list.get(0).getName().indexOf("导入失败")!=-1){
                return R.failed(list.get(0).getName());
            }
            ScUser u = SecurityUtils.getUser();
            list.forEach(zstbInfo -> {
                zstbInfo.setDeptId(u.getDeptId().toString());
                zstbInfo.setDelFlag("1");
                zstbInfo.setAddTime(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 (u.getDeptId().toString().equals("530000")){
                    zstbInfo.setAdminisFlag("");
                    zstbInfo.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "1");
                    zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                    zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "1");
                    zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else if (u.getDeptId().toString().substring(u.getDeptId().toString().length() - 2).equals("00")){
                    zstbInfo.setAdminisFlag("2");
                    zstbInfo.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "1");
                    json.replace("city", "0");
                    zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                    zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "1");
                    jsonObject.replace("province", "0");
                    zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }else {
                    zstbInfo.setAdminisFlag("1");
                    zstbInfo.setReportUser(JSONObject.toJSONString(json));
                    json.replace("country", "0");
                    json.replace("city", "0");
                    zstbInfo.setReportStatus(JSONObject.toJSONString(json));
                    zstbInfo.setUpdateUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setAuditUser(JSONObject.toJSONString(jsonObject));
                    zstbInfo.setCause(JSONObject.toJSONString(jsonObject));
                    jsonObject.replace("city", "0");
                    jsonObject.replace("province", "0");
                    zstbInfo.setAuditorFlag(JSONObject.toJSONString(jsonObject));
                }
            });
            zstbInfoService.saveBatch(list);
            return R.ok("导入成功");
        } catch (Exception e) {
            return R.failed("程序出错 "+e.getMessage(), "导入失败");
        }
    }

}
