package com.ruoyi.gysl.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.gysl.entity.*;
import com.ruoyi.gysl.entity.request.AuditRequest;
import com.ruoyi.gysl.entity.request.BasicInformationPageReq;
import com.ruoyi.gysl.entity.request.RemarkPageReq;
import com.ruoyi.gysl.entity.request.ZwIdPageReq;
import com.ruoyi.gysl.entity.response.BasicInformationResponse;
import com.ruoyi.gysl.entity.response.ProjectBuildingExcel;
import com.ruoyi.gysl.entity.response.ProjectExcelInfo;
import com.ruoyi.gysl.mapper.BasicInformationMapper;
import com.ruoyi.gysl.service.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

/**
 * 基本信息(BasicInformation)表服务实现类
 *
 * @author makejava
 * @since 2025-02-24 09:25:55
 */
@Service("basicInformationService")
public class BasicInformationServiceImpl extends ServiceImpl<BasicInformationMapper, BasicInformation> implements BasicInformationService {


    /**
     * 项目规划信息
     */
    @Resource
    private PlanInformationService planInformationService;


    /**
     * 建筑信息
     */
    @Resource
    private BuildingInformationService buildingInformationService;

    /**
     * 五要素模型信息
     */
    @Resource
    private WysmxInformationService wysmxInformationService;

    /**
     * 企业入驻信息
     */
    @Resource
    private QyrzInformationService qyrzInformationService;

    /**
     * 项目图例信息
     */
    @Resource
    private ProjectLegendService projectLegendService;

    /**
     * 项目备忘录
     */
    @Resource
    private ProjectRemarkService projectRemarkService;

    /**
     * 月度进展信息
     */
    @Resource
    private ProjectMonthInfoService projectMonthInfoService;

    /**
     * 项目巡礼
     */
    @Resource
    private XmxlService xmxlService;

    /**
     * 项目备忘录
     */
    @Resource
    private ProjectOtherInfoService otherInfoService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param req  查询实体
     * @return 所有数据
     */
    @Override
    public Page<BasicInformation> page(Page<BasicInformation> page, BasicInformationPageReq req) {
        return baseMapper.page(page, req);
    }

    /**
     * 根据基本信息的id列表来查找
     */
    @Override
    public List<ProjectExcelInfo> selectList(List<Long> idList) {
        return baseMapper.selectList(idList);
    }


    /**
     * 填充数据
     */
    @Override
    public void approvalMethodfillInData(XSSFSheet sheet, XSSFCellStyle contentStyle, int rowNum, List<ProjectExcelInfo> info, List<String> sc, List<String> ec, int num) {
        Class<?> classBuilding = ProjectBuildingExcel.class;
        for (ProjectExcelInfo projectExcelInfo : info) {
            XSSFRow tempRow = sheet.createRow(rowNum++);
            tempRow.setHeight((short) 1400);
            int i1;
            for (i1 = 0; i1 < sc.size(); i1++) {
                XSSFCell tempCell = tempRow.createCell(i1);
                tempCell.setCellStyle(contentStyle);
                if (!ec.get(i1).endsWith("厂房")) {
                    if (Objects.equals(sc.get(i1), "")) {
                        tempCell.setCellValue(projectExcelInfo.getId());
                    } else {
                        tempCell.setCellValue(getExcelData(projectExcelInfo, sc.get(i1)));
                    }
                }
            }
//            XSSFCell tempCell = tempRow.createCell(8);
//            tempCell.setCellStyle(contentStyle);
//            tempCell.setCellValue("12312321");

            for (int i2 = 0; i2 < projectExcelInfo.getXmjzxx().size(); i2++) {
                switch (projectExcelInfo.getXmjzxx().get(i2).getFloor()) {
                    case 1:
                        i1 = ec.indexOf("一层厂房");
                        break;
                    case 2:
                        i1 = ec.indexOf("双层厂房");
                        break;
                    case 3:
                        i1 = ec.indexOf("三层厂房");
                        break;
                    case 4:
                        i1 = ec.indexOf("四层厂房");
                        break;
                    case 5:
                        i1 = ec.indexOf("五层厂房");
                        break;
                    default:
                        i1 = ec.indexOf("六层及以上厂房");
                }
                for (Field field : classBuilding.getDeclaredFields()) {
                    XSSFCell tempCell = tempRow.createCell(i1);
                    tempCell.setCellStyle(contentStyle);
                    Excel excelColumn = field.getAnnotation(Excel.class);
                    if (excelColumn != null) {
                        tempCell.setCellValue(getBuildingData(projectExcelInfo.getXmjzxx().get(i2), sc.get(i1)));
                        i1++;
                    }
                }
            }
        }
    }

    /**
     * 填充数据-项目基础信息获取
     */
    @Override
    public String getExcelData(ProjectExcelInfo item, String str) {
        String a = null;
        switch (str) {
            case "":
                a = item.getId() == null ? "-" : item.getId();
                break;
            case "项目名称":
                a = item.getName() == null ? "-" : item.getName();
                break;
            case "项目法人单位":
                a = item.getXmfrdwxz() == null ? "-" : item.getXmfrdwxz();
                break;
            case "项目法人单位性质":
                a = String.valueOf(item.getNature() == null ? "-" : item.getNature());
                break;
            case "总用地面积":
                a = String.valueOf(item.getZydmj() == null ? "-" : item.getZydmj());
                break;
            case "容积率":
                a = String.valueOf(item.getRjl() == null ? "-" : item.getRjl());
                break;
            case "总建筑面积":
                a = String.valueOf(item.getZjzmj() == null ? "-" : item.getZjzmj());
                break;
            case "标准层建筑面积":
                a = String.valueOf(item.getBzcjzmj() == null ? "-" : item.getBzcjzmj());
                break;
        }
        return a;
    }

    /**
     * 填充数据-项目建筑信息获取
     */
    @Override
    public String getBuildingData(ProjectBuildingExcel item, String str) {
        String a = null;
        switch (str) {
            case "层数":
                a = item.getFloor() == null ? "-" : String.valueOf(item.getFloor());
                break;
            case "总建筑高度":
                a = item.getTotalBuildingHeight() == null ? "-" : String.valueOf(item.getTotalBuildingHeight());
                break;
            case "首层高度":
                a = String.valueOf(item.getScgd() == null ? "-" : item.getScgd());
                break;
            case "2至4层高":
                a = String.valueOf(item.getTwoAndFourCg() == null ? "-" : item.getTwoAndFourCg());
                break;
            case "4层以上层高":
                a = String.valueOf(item.getFourYscg() == null ? "-" : item.getFourYscg());
                break;
        }
        return a;
    }

    /**
     * 有经纬度的项目列表
     */
    @Override
    public Page<BasicInformation> projectList(Page<BasicInformation> page) {
        return baseMapper.projectList(page);
    }

    /**
     * 查看当前用户是否有权限查看或者修改新增
     */
    @Override
    public BasicInformation testXmId(Serializable xmId) {
        BasicInformation byId = getById(xmId);
        // 获取当前登录用户是否是企业端
        try {
            if (SecurityUtils.hasRole("company") && byId != null) {
                if (!Objects.equals(byId.getTyshxydm(), SecurityUtils.getUsername())) {
                    throw new ServiceException("禁止修改!");
                }
            }
        } catch (Exception ignored) {
        }
        return byId;
    }

    /**
     * 企业端和政务端信息修改
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long audit(AuditRequest req,int status) {
        req.getBasicInformation().setStatus(status);
        //企业端提交审核直接修改，不需要挂起等待审批
        //修改项目基本信息
        updateById(req.getBasicInformation());
        //修改项目规划信息
        planInformationService.updateById(req.getPlanInformation());
        //修改企业入驻信息
        qyrzInformationService.updateById(req.getQyrzInformation());
        //修改五要素模型信息
        wysmxInformationService.lambdaUpdate()
                .eq(WysmxInformation::getXmId, req.getBasicInformation().getId())
                .remove();
        wysmxInformationService.saveBatch(req.getWysmxInformations());
        //修改其他信息
        otherInfoService.lambdaUpdate()
                .eq(ProjectOtherInfo::getXmId, req.getBasicInformation().getId())
                .remove();
        otherInfoService.saveBatch(req.getProjectOtherInfos());
        return req.getBasicInformation().getId();
    }

    /**
     * 通过主键查询单条项目所有数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @Override
    public BasicInformationResponse selectOne(Long id) {

        BasicInformationResponse basicInformationResponse = new BasicInformationResponse();
        //项目基本信息
        basicInformationResponse.setBasicInformation(getById(id));
        //项目规划信息
        basicInformationResponse.setPlanInformation(planInformationService.lambdaQuery()
                .eq(PlanInformation::getXmId, id)
                .one());
        //项目建筑信息
        basicInformationResponse.setBuildingInformation(buildingInformationService.lambdaQuery()
                .eq(BuildingInformation::getXmId, id)
                .list());
        //五要素模型信息
        ZwIdPageReq zwIdPageReq = new ZwIdPageReq();
        zwIdPageReq.setXmId(id);
        basicInformationResponse.setWysmxResponses(wysmxInformationService.list(zwIdPageReq));
        //企业入驻信息
        basicInformationResponse.setQyrzInformation(qyrzInformationService.selectAll(zwIdPageReq));
        //项目图例
        basicInformationResponse.setProjectLegendResponses(projectLegendService.page(zwIdPageReq));
        //项目巡礼
        basicInformationResponse.setXmxl(xmxlService.list(zwIdPageReq));
        RemarkPageReq remarkPageReq = new RemarkPageReq();
        remarkPageReq.setXmId(id);
        //项目备忘录
        basicInformationResponse.setProjectRemarks(projectRemarkService.list(remarkPageReq));
        //其他信息
        basicInformationResponse.setProjectOtherInfos(otherInfoService.searchId(zwIdPageReq));
        return basicInformationResponse;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeByXmIds(List<Long> idList) {
        idList.forEach(x->{
            //删除项目基本信息
            lambdaUpdate()
                    .eq(BasicInformation::getId,x)
                    .remove();
            //删除项目规划信息
            planInformationService.lambdaUpdate()
                    .eq(PlanInformation::getXmId, x)
                    .remove();
            //删除项目建筑信息
            buildingInformationService.lambdaUpdate()
                    .eq(BuildingInformation::getXmId,x)
                    .remove();
            //删除五要素模型信息
            wysmxInformationService.lambdaUpdate()
                    .eq(WysmxInformation::getXmId,x)
                    .remove();
            //删除月度进展信息
            projectMonthInfoService.lambdaUpdate()
                    .eq(ProjectMonthInfo::getXmId,x)
                    .remove();
            //删除企业入驻信息
            qyrzInformationService.lambdaUpdate()
                    .eq(QyrzInformation::getXmId,x)
                    .remove();
            //删除项目图例
            projectLegendService.lambdaUpdate()
                    .eq(ProjectLegend::getXmId,x)
                    .remove();
            //删除项目巡礼
            xmxlService.lambdaUpdate()
                    .eq(Xmxl::getXmId, x)
                    .remove();
            //删除项目备忘录
            projectRemarkService.lambdaUpdate()
                    .eq(ProjectRemark::getXmId, x)
                    .remove();
            //删除其他信息
            otherInfoService.lambdaUpdate()
                    .eq(ProjectOtherInfo::getXmId, x)
                    .remove();
        });
    }
}
