package com.ruoyi.party.service.impl;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.poi.ExportExcelUtil;
import com.ruoyi.common.utils.poi.ImportExcelUtil;
import com.ruoyi.party.domain.PartyOrganization;
import com.ruoyi.party.domain.PartyOrganizationError;
import com.ruoyi.party.domain.vo.PartyOrganizationVo;
import com.ruoyi.party.mapper.PartyOrganizationErrorMapper;
import com.ruoyi.party.mapper.PartyOrganizationMapper;
import com.ruoyi.party.service.api.IPartyOrganizationService;
import com.ruoyi.system.mapper.system.SysDictDataMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 党组织管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-17
 */
@Service
@DataSource(value = DataSourceType.SLAVE)
public class PartyOrganizationServiceImpl implements IPartyOrganizationService
{
    @Autowired
    private PartyOrganizationMapper partyOrganizationMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private PartyOrganizationErrorMapper partyOrganizationErrorMapper;

    /**
     * 查询党组织管理
     *
     * @param id 党组织管理主键
     * @return 党组织管理
     */
    @Override
    public PartyOrganizationVo selectPartyOrganizationById(String id)
    {
        PartyOrganization partyOrganization = partyOrganizationMapper.selectPartyOrganizationById(id);
        PartyOrganizationVo partyOrganizationVo = new PartyOrganizationVo();
        BeanUtils.copyProperties(partyOrganization, partyOrganizationVo);
        if(StringUtils.isNotBlank(partyOrganizationVo.getSjdzzdm())){
            PartyOrganization sjDzz = this.getByDzzdm(partyOrganizationVo.getSjdzzdm());
            partyOrganizationVo.setSjdzzName(sjDzz == null?"":sjDzz.getDzzmc());
        }
        return partyOrganizationVo;
    }

    /**
     * 查询党组织管理列表
     *
     * @param partyOrganization 党组织管理
     * @return 党组织管理
     */
    @Override
    public List<PartyOrganization> selectPartyOrganizationList(PartyOrganization partyOrganization)
    {
        return partyOrganizationMapper.selectPartyOrganizationList(partyOrganization);
    }

    /**
     * 新增党组织管理
     *
     * @param partyOrganization 党组织管理
     * @return 结果
     */
    @Override
    public int insertPartyOrganization(PartyOrganization partyOrganization)
    {
        return partyOrganizationMapper.insertPartyOrganization(partyOrganization);
    }

    /**
     * 修改党组织管理
     *
     * @param partyOrganization 党组织管理
     * @return 结果
     */
    @Override
    public int updatePartyOrganization(PartyOrganization partyOrganization)
    {
        return partyOrganizationMapper.updatePartyOrganization(partyOrganization);
    }

    /**
     * 批量删除党组织管理
     *
     * @param ids 需要删除的党组织管理主键
     * @return 结果
     */
    @Override
    public int deletePartyOrganizationByIds(String[] ids)
    {
        return partyOrganizationMapper.deletePartyOrganizationByIds(ids);
    }

    /**
     * 删除党组织管理信息
     *
     * @param id 党组织管理主键
     * @return 结果
     */
    @Override
    public int deletePartyOrganizationById(String id)
    {
        return partyOrganizationMapper.deletePartyOrganizationById(id);
    }

    @Override
    public List<PartyOrganizationVo> partyOrganizationTree(PartyOrganization partyOrganization) {
        List<PartyOrganization> list = partyOrganizationMapper.selectPartyOrganizationList(partyOrganization);
        List<PartyOrganizationVo> result = new ArrayList<>();
        for (PartyOrganization item : list) {
            PartyOrganizationVo partyOrganizationVo = new PartyOrganizationVo();
            BeanUtils.copyProperties(item, partyOrganizationVo);
            result.add(partyOrganizationVo);
        }
        return toTree(result);
    }

    private List<PartyOrganizationVo> toTree(List<PartyOrganizationVo> list) {
        Map<String, PartyOrganizationVo> treeMap = list.stream().collect(Collectors.toMap(PartyOrganizationVo::getDzzdm, x -> x));
        List<PartyOrganizationVo> toplevelList = list.stream().filter(x -> !treeMap.containsKey(x.getSjdzzdm())).collect(Collectors.toList());
        for (PartyOrganizationVo t : list) {
            if (treeMap.containsKey(t.getSjdzzdm())) {
                PartyOrganizationVo parent = treeMap.get(t.getSjdzzdm());
                List<PartyOrganizationVo> children = parent.getChildren();
                children.add(t);
            }
        }
        return toplevelList;
    }

    @Override
    public int countOrg() {
        return partyOrganizationMapper.countOrg();
    }

    @Override
    public List<Map<String, String>> getPartyOrgBuild(List<SysDictData> partyTypeList) {
        Map<String, SysDictData> treeMap = partyTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, x -> x));
        List<Map<String, String>> list = partyOrganizationMapper.getPartyOrgBuild();
        if(!CollectionUtils.isEmpty(list)){
            for(Map<String, String> map : list){
                String zzlb = map.get("zzlb");
                if(treeMap.containsKey(zzlb)){
                    map.put("zzlb", treeMap.get(zzlb).getDictLabel());
                }
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(Workbook workbook, List<SysDictData> partyTypeList, List<SysDictData> sdgxList) {
        StringBuilder msg;
        //开始执行解析
        Sheet sheet = workbook.getSheetAt(0); //读取工作表
        List<PartyOrganization> list = new ArrayList<>();
        for (int j = 1; j <= sheet.getLastRowNum(); j++) {
            Row row = sheet.getRow(j);
            if (row.getCell(0) != null) {
                PartyOrganization t = new PartyOrganization();
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(0)))) {
                    // msg+="第"+j+"行党组织编码不能为空"+"\n";
                    msg = new StringBuilder("党组织代码不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    PartyOrganization partyOrganization = new PartyOrganization();
                    partyOrganization.setDzzdm(ImportExcelUtil.getValue(row.getCell(0)));
                    List<PartyOrganization> partyOrganizations = partyOrganizationMapper.selectPartyOrganizationList(partyOrganization);
                    if (!partyOrganizations.isEmpty()) {
                        // msg+="第"+j+"行党组织编码重复"+"\n";
                        msg = new StringBuilder("党组织编码重复");
                        //保存错误数据
                        getPartOrgError(row, msg.toString());
                        continue;
                    } else {
                        t.setDzzdm(ImportExcelUtil.getValue(row.getCell(0)));
                    }
                }

                // 党组织名称，非空
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(1)))) {
                    //msg+="第"+j+"行党组织名称不能为空"+"\n";
                    msg = new StringBuilder("党组织名称不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    t.setDzzmc(ImportExcelUtil.getValue(row.getCell(1)));
                }
                // 党组织书记
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(2)))) {
                    msg = new StringBuilder("党组织书记不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    t.setDzzsj(ImportExcelUtil.getValue(row.getCell(2)));
                }

                // 党组织联系人
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(3)))) {
                    msg = new StringBuilder("党组织联系人不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    t.setDzzlxr(ImportExcelUtil.getValue(row.getCell(3)));
                }

                // 党组织联系电话
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(4)))) {
                    msg = new StringBuilder("党组织联系电话不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    t.setDzzlxdh(ImportExcelUtil.getValue(row.getCell(4)));
                }

                // 党组织类别
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(5)))) {
                    msg = new StringBuilder("党组织类别不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {

                    String value = ImportExcelUtil.getValue(row.getCell(5));
                    if (!partyTypeList.isEmpty()) {
                        Map<String, SysDictData> treeMap = partyTypeList.stream().collect(Collectors.toMap(SysDictData::getDictLabel, x -> x));
                        if (treeMap.containsKey(value)) {
                            t.setZzlb(treeMap.get(value).getDictValue());
                        } else {
                            //保存错误数据
                            msg = new StringBuilder("党组织类别错误");
                            getPartOrgError(row, msg.toString());
                            continue;
                        }
                    }
                }

                // 属地关系
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(6)))) {
                    msg = new StringBuilder("属地关系不能为空");
                    //保存错误数据
                    getPartOrgError(row, msg.toString());
                    continue;
                } else {
                    String value = ImportExcelUtil.getValue(row.getCell(6));
                    if (!sdgxList.isEmpty()) {
                        Map<String, SysDictData> treeMap = sdgxList.stream().collect(Collectors.toMap(SysDictData::getDictLabel, x -> x));
                        if (treeMap.containsKey(value)) {
                            t.setSdgx(treeMap.get(value).getDictValue());
                        } else {
                            //保存错误数据
                            msg = new StringBuilder("属地关系错误");
                            getPartOrgError(row, msg.toString());
                            continue;
                        }
                    }
                }

                // 上级党组织代码
                String superName = ImportExcelUtil.getValue(row.getCell(7));
                if (StringUtils.isNotBlank(superName)) {
                    t.setSjdzzdm(superName);
                }

                // 通讯地址
                String txdz = ImportExcelUtil.getValue(row.getCell(8));
                if (StringUtils.isNotBlank(txdz)) {
                    t.setTxdz(txdz);
                }

                // 所属网格
                String sswg = ImportExcelUtil.getValue(row.getCell(9));
                if (StringUtils.isNotBlank(txdz)) {
                    t.setSswg(sswg);
                }

                // 定位
                String dw = ImportExcelUtil.getValue(row.getCell(10));
                if (StringUtils.isNotBlank(txdz)) {
                    t.setDw(dw);
                }
                list.add(t);
            }
        }
        for (PartyOrganization item : list) {
            partyOrganizationMapper.insertPartyOrganization(item);
        }
    }

    //保存错误数据
    private void getPartOrgError(Row row, String errorMsg){
        PartyOrganizationError partyOrgError = new PartyOrganizationError();
        partyOrgError.setDzzdm(ImportExcelUtil.getValue(row.getCell(0)));
        partyOrgError.setDzzmc(ImportExcelUtil.getValue(row.getCell(1)));
        partyOrgError.setDzzsj(ImportExcelUtil.getValue(row.getCell(2)));
        partyOrgError.setDzzlxr(ImportExcelUtil.getValue(row.getCell(3)));
        partyOrgError.setDzzlxdh(ImportExcelUtil.getValue(row.getCell(4)));
        partyOrgError.setZzlb(ImportExcelUtil.getValue(row.getCell(5)));
        partyOrgError.setSdgx(ImportExcelUtil.getValue(row.getCell(6)));
        partyOrgError.setSjdzzdm(ImportExcelUtil.getValue(row.getCell(7)));
        partyOrgError.setTxdz(ImportExcelUtil.getValue(row.getCell(8)));
        partyOrgError.setSswg(ImportExcelUtil.getValue(row.getCell(9)));
        partyOrgError.setDw(ImportExcelUtil.getValue(row.getCell(10)));
        partyOrgError.setRemark(errorMsg);
        partyOrgError.setCreateTime(new Date());
        partyOrganizationErrorMapper.insertPartyOrganizationError(partyOrgError);
    }

    @Override
    public HSSFWorkbook exportTemplate() {
        //首行中文标题
        String[] titleCNName={"*党组织代码","*党组织名称", "*党组织书记","*党组织联系人", "*党组织联系电话", "*组织类别", "*属地关系", "上级党组织代码", "通讯地址", "所属网格", "定位"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        //首行中文标题
        ExportExcelUtil.createSheet(workbook,titleCNName, null, null,0,false,"main");
        return workbook;
    }

    @Override
    public PartyOrganization getByDzzdm(String dzzdm) {
        return partyOrganizationMapper.getByDzzdm(dzzdm);
    }

    @Override
    public PartyOrganization getByDzzmc(String dzzmc) {
        return partyOrganizationMapper.getByDzzmc(dzzmc);
    }
}
