package com.testor.module.environment.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.dict.data.controller.SysDictDataController;
import com.testor.biz.sys.dict.data.model.dto.SysDictDataResponse;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.util.excel.LocalDateTimeConverter;
import com.testor.module.accident.model.resp.ReportUnitResp;
import com.testor.module.environment.dao.TBasicEnvironmentManageDao;
import com.testor.module.environment.model.domain.TBasicEnvironmentManage;
import com.testor.module.environment.model.dto.TBasicEnvironmentManageParam;
import com.testor.module.environment.service.TBasicEnvironmentManageService;
import com.testor.module.sys.dao.NewSysOrgDao;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 环保基本面管理Service业务层处理
 *
 * @author testor-framework
 * @date 2022-09-16 13:37:50
 */
@Service
public class TBasicEnvironmentManageServiceImpl extends SuperServiceImpl<TBasicEnvironmentManageDao, TBasicEnvironmentManage> implements TBasicEnvironmentManageService {
    @Autowired(required = false)
    private TBasicEnvironmentManageDao tBasicEnvironmentManageDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private NewSysOrgService newSysOrgService;
    @Autowired
    private NewSysOrgDao newSysOrgDao;

    @Override
    public BaseResponse<TBasicEnvironmentManage> edit(TBasicEnvironmentManage addRequest) {
        BaseResponse<TBasicEnvironmentManage> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            TBasicEnvironmentManage data = BeanHelper.beanToBean(addRequest, TBasicEnvironmentManage.class);
            if ("0".equals(addRequest.getLocation())) {
                data.setTroubleshoot("");
            }
            if ("0".equals(addRequest.getRanmei())) {
                data.setBoilerStage("");
                data.setBoilerTon("");
                data.setThenStatus("");
            }
            if ("0".equals(addRequest.getShenwu())) {
                data.setBiologyStage("");
                data.setBiologyTon("");
            }
            if ("0".equals(addRequest.getRanqi())) {
                data.setFuelStage("");
                data.setFuelTon("");
            }
            if (!"1".equals(addRequest.getLicence())) {
                data.setDust("");
                data.setSo2("");
                data.setNox("");
                data.setVocs("");
                data.setCodcr("");
                data.setNh3N("");
            }
            data.setId(addRequest.getOrgId());
            boolean result = this.saveOrUpdate(data);
            if (result) {
                TBasicEnvironmentManage newEntity = new TBasicEnvironmentManage();
                newEntity.setId(addRequest.getOrgId());
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TBasicEnvironmentManage> getByIds(String orgId) {
        BaseResponse<TBasicEnvironmentManage> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(orgId)) {
            TBasicEnvironmentManage data = this.getById(orgId);
            if (ObjectHelper.isNotEmpty(data)) {
                SysUser user = sysUserService.getById(data.getUpdateBy());
                data.setUpdateName(user.getUserName());
            }
            baseResponse.setData(data);
        }
        return baseResponse;
    }

    @Override
    public IPage<TBasicEnvironmentManage> getList(TBasicEnvironmentManageParam param, String parentIds, String orgId, List<String> companyIds) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TBasicEnvironmentManage> resultPage = new Page<>(page, limit);
        return tBasicEnvironmentManageDao.getList(resultPage, param, parentIds, orgId, companyIds);
    }

    @SneakyThrows
    @Override
    public void export(HttpServletResponse response, TBasicEnvironmentManageParam param) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        String parentIds = sysOrg.getParentIds();
        String orgId = sysOrg.getOrgId();
        List<String> companyIds = param.getCompanyIds();
        IPage<TBasicEnvironmentManage> resultList = getList(param, parentIds, orgId, companyIds);
        List<TBasicEnvironmentManage> tBasicEnvironmentManages = converDict(resultList.getRecords());
        final Integer[] number = {1};
        tBasicEnvironmentManages.forEach(
                item -> {
                    item.setSerialNumber(number[0]);
                    item.setLocation(StringUtils.isNotBlank(item.getLocation()) ? item.getLocation() : "-");
                    item.setTroubleshoot(StringUtils.isNotBlank(item.getTroubleshoot()) ? item.getTroubleshoot() : "-");
                    item.setSensitiveAreas(StringUtils.isNotBlank(item.getSensitiveAreas()) ? item.getSensitiveAreas() : "-");
                    item.setCheckCase(StringUtils.isNotBlank(item.getCheckCase()) ? item.getCheckCase() : "-");
                    item.setLicence(StringUtils.isNotBlank(item.getLicence()) ? item.getLicence() : "-");
                    item.setPollution(StringUtils.isNotBlank(item.getPollution()) ? item.getPollution() : "-");
                    item.setRiskPoint(StringUtils.isNotBlank(item.getRiskPoint()) ? item.getRiskPoint() : "-");
                    item.setIntake(StringUtils.isNotBlank(item.getIntake()) ? item.getIntake() : "-");
                    item.setDrain(StringUtils.isNotBlank(item.getDrain()) ? item.getDrain() : "-");
                    item.setDust(StringUtils.isNotBlank(item.getDust()) ? item.getDust() : "-");
                    item.setSo2(StringUtils.isNotBlank(item.getSo2()) ? item.getSo2() : "-");
                    item.setNox(StringUtils.isNotBlank(item.getNox()) ? item.getNox() : "-");
                    item.setVocs(StringUtils.isNotBlank(item.getVocs()) ? item.getVocs() : "-");
                    item.setFlueCount(StringUtils.isNotBlank(item.getFlueCount()) ? item.getFlueCount() : "-");
                    item.setFlueDeal(StringUtils.isNotBlank(item.getFlueDeal()) ? item.getFlueDeal() : "-");
                    item.setFlueDeal(StringUtils.isNotBlank(item.getFlueDeal()) ? item.getFlueDeal() : "-");
                    item.setCodcr(StringUtils.isNotBlank(item.getCodcr()) ? item.getCodcr() : "-");
                    item.setNh3N(StringUtils.isNotBlank(item.getNh3N()) ? item.getNh3N() : "-");
                    item.setWasteCount(StringUtils.isNotBlank(item.getWasteCount()) ? item.getWasteCount() : "-");
                    item.setWasteDeal(StringUtils.isNotBlank(item.getWasteDeal()) ? item.getWasteDeal() : "-");
                    item.setBoilerStage(StringUtils.isNotBlank(item.getBoilerStage()) ? item.getBoilerStage() : "-");
                    item.setBoilerTon(StringUtils.isNotBlank(item.getBoilerTon()) ? item.getBoilerTon() : "-");
                    item.setThenStatus(StringUtils.isNotBlank(item.getThenStatus()) ? item.getThenStatus() : "-");
                    item.setBiologyStage(StringUtils.isNotBlank(item.getBiologyStage()) ? item.getBiologyStage() : "-");
                    item.setBiologyTon(StringUtils.isNotBlank(item.getBiologyTon()) ? item.getBiologyTon() : "-");
                    item.setFuelStage(StringUtils.isNotBlank(item.getFuelStage()) ? item.getFuelStage() : "-");
                    item.setFuelTon(StringUtils.isNotBlank(item.getFuelTon()) ? item.getFuelTon() : "-");
                    item.setFuelTon(StringUtils.isNotBlank(item.getFuelTon()) ? item.getFuelTon() : "-");
                    number[0]++;
                }
        );

        response.setContentType("application/vnd.ms-excel");
        // 对响应进行重新编码
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("环保基本面列表", "utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        InputStream templatePathName = this.getClass().getClassLoader().getResourceAsStream("excel/hbjbm.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templatePathName).registerConverter(new LocalDateTimeConverter()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        // 直接写入数据
        excelWriter.fill(tBasicEnvironmentManages, fillConfig, writeSheet);
        // 写入list之前的数据
        excelWriter.finish();
    }

    @Autowired
    private SysDictDataController sysDictDataController;

    /**
     * 转字典值
     *
     * @param baseResponseList
     * @return
     */
    private List<TBasicEnvironmentManage> converDict(List<TBasicEnvironmentManage> baseResponseList) {
        List<TBasicEnvironmentManage> data1 = new ArrayList<>();
        for (TBasicEnvironmentManage datum : baseResponseList) {
            TBasicEnvironmentManage tTrainDatabase = BeanHelper.beanToBean(datum, TBasicEnvironmentManage.class);
            String oneMaterialsType = tTrainDatabase.getIntake();
            // 取水方式
            SysDictDataResponse materials2 = sysDictDataController.getDictTypeDetail("", "INTAKE_WAY", oneMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials2)) {
                String materials = materials2.getDictValue();
                tTrainDatabase.setIntake(materials);
            }
            // 排水方式
            String senMaterialsType = tTrainDatabase.getDrain();
            SysDictDataResponse materials3 = sysDictDataController.getDictTypeDetail("", "DRAIN_WAY", senMaterialsType).getData();
            if (ObjectHelper.isNotEmpty(materials3)) {
                String materials1 = materials3.getDictValue();
                tTrainDatabase.setDrain(materials1);
            }
            // 节能环保-排污许可证办理
            String licence = tTrainDatabase.getLicence();
            SysDictDataResponse licence_tran = sysDictDataController.getDictTypeDetail("", "LICENCE_TRAN", licence).getData();
            if (ObjectHelper.isNotEmpty(licence_tran)) {
                String materials1 = licence_tran.getDictValue();
                tTrainDatabase.setLicence(materials1);
            }

            // 节能环保-环保验收情况
            String checkCase = tTrainDatabase.getCheckCase();
            SysDictDataResponse acceptance_case = sysDictDataController.getDictTypeDetail("", "ACCEPTANCE_CASE", checkCase).getData();
            if (ObjectHelper.isNotEmpty(acceptance_case)) {
                String materials1 = acceptance_case.getDictValue();
                tTrainDatabase.setCheckCase(materials1);
            }

            // 节能环保-是否处于敏感地带
            String sensitiveAreas = tTrainDatabase.getSensitiveAreas();
            SysDictDataResponse sensitivity_zone = sysDictDataController.getDictTypeDetail("", "SENSITIVITY_ZONE", sensitiveAreas).getData();
            if (ObjectHelper.isNotEmpty(sensitivity_zone)) {
                String materials1 = sensitivity_zone.getDictValue();
                tTrainDatabase.setSensitiveAreas(materials1);
            }

            // 节能环保-三线一单是否发布
            String location = tTrainDatabase.getLocation();
            SysDictDataResponse is_release = sysDictDataController.getDictTypeDetail("", "IS_RELEASE", location).getData();
            if (ObjectHelper.isNotEmpty(is_release)) {
                String materials1 = is_release.getDictValue();
                tTrainDatabase.setLocation(materials1);
            }
            if (StringUtils.isNotBlank(tTrainDatabase.getTroubleshoot()) ) {
                String troubleshoot = tTrainDatabase.getTroubleshoot().equals("1") ? "是" : "否";
                tTrainDatabase.setTroubleshoot(troubleshoot);
            }
            data1.add(tTrainDatabase);
        }

        return data1;
    }

    @Override
    public ReportUnitResp lookOrg(String orgId) throws Exception {
        NewSysOrg sysOrg = newSysOrgService.getById(orgId);
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        ReportUnitResp reportUnitResp = new ReportUnitResp();

        reportUnitResp.setParentIds(sysOrg.getParentIds() + "," + sysOrg.getOrgId());
        reportUnitResp.setNature(sysOrg.getNature());
        reportUnitResp.setTreeLevel(sysOrg.getTreeLevel());
        //如果是根节点
        if ("0".equals(sysOrg.getParentId())) {
            reportUnitResp.setFirstLevelDepartmentId(sysOrg.getOrgId());
            reportUnitResp.setFirstLevelDepartment(sysOrg.getOrgName());
            reportUnitResp.setPathIds(sysOrg.getParentIds());
            reportUnitResp.setPath(sysOrg.getOrgName());
            return reportUnitResp;
        }

        String[] parentIds = reportUnitResp.getParentIds().substring(2).split(",");

        reportUnitResp.setFirstLevelDepartmentId(parentIds[0]);

        if (parentIds.length == 1) {
            reportUnitResp.setPathIds(parentIds[0]);
        } else if (parentIds.length == 2) {
            reportUnitResp.setPathIds(Arrays.stream(parentIds).collect(Collectors.joining()));
            reportUnitResp.setRegionalCompanyId(parentIds[1]);
        } else {
            //获取前三级元素
            String[] newParents = Arrays.copyOfRange(parentIds, 0, 3);
            reportUnitResp.setPathIds(Arrays.stream(newParents).collect(Collectors.joining()));
            reportUnitResp.setRegionalCompanyId(parentIds[1]);
            reportUnitResp.setBasicUnitId(parentIds[2]);
        }
        List<SysOrg> sysOrgList = sysOrgService.lambdaQuery().in(SysOrg::getOrgId, parentIds).list();

        if (CollectionUtils.isEmpty(sysOrgList) || parentIds.length != sysOrgList.size()) {
            throw new BusinessException("部门信息有误，请联系管理员！");
        }

        //赋值部门名称
        Map<String, String> sysOrgMap = sysOrgList.stream().collect(Collectors.toMap(SysOrg::getOrgId, SysOrg::getOrgName));
        StringBuilder path = new StringBuilder();

        //一级部门名称赋值
        reportUnitResp.setFirstLevelDepartment(sysOrgMap.get(parentIds[0]));
        path.append(sysOrgMap.get(parentIds[0]));

        //赋值区域公司名称
        if (StringUtils.isNotEmpty(reportUnitResp.getRegionalCompanyId())) {
            reportUnitResp.setRegionalCompany(sysOrgMap.get(reportUnitResp.getRegionalCompanyId()));
            path.append("/" + reportUnitResp.getRegionalCompany());
        }

        //赋值基层单位名称
        if (StringUtils.isNotEmpty(reportUnitResp.getBasicUnitId())) {
            reportUnitResp.setBasicUnit(sysOrgMap.get(reportUnitResp.getBasicUnitId()));
            path.append("/" + reportUnitResp.getBasicUnit());
        }

        //赋值路径名称
        reportUnitResp.setPath(path.toString());
        StringBuilder subSectorPath = new StringBuilder();
        StringBuilder subSectorPathIds = new StringBuilder();
        //没有一级组织路径
        for (int i = 1; i < parentIds.length; i++) {
            if (i > 1) {
                subSectorPath.append("/");
                subSectorPathIds.append(",");
            }
            subSectorPath.append(sysOrgMap.get(parentIds[i]));
            subSectorPathIds.append(parentIds[i]);
        }
        reportUnitResp.setSubSectorPath(subSectorPath.toString());
        reportUnitResp.setSubSectorPathIds(subSectorPathIds.toString());
        convertOrgPath(orgId,reportUnitResp);
        return reportUnitResp;

    }


    private void convertOrgPath(String orgId,ReportUnitResp reportUnitResp ){
        List<NewSysOrg> sysOrgList = newSysOrgDao.findSubSectorPath(orgId);
        if (CollectionUtils.isNotEmpty(sysOrgList)) {
            Collections.reverse(sysOrgList);
            String ids = sysOrgList.stream() .map(NewSysOrg::getOrgId) .collect(Collectors.joining(","));
            String names = sysOrgList.stream() .map(NewSysOrg::getOrgName) .collect(Collectors.joining("/"));
            reportUnitResp.setSubSectorPath(names);
            reportUnitResp.setSubSectorPathIds(ids);
            reportUnitResp.setPath(names);
            reportUnitResp.setPathIds(ids);
        }
    }


    public static void main(String[] args) {
        String str = "安全环保部/中粮贸易（佳木斯建三江）粮食储运有限公司/佳木斯经营部/东北大区/中粮贸易有限公司";

    }
}
