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.bean.BeanCopyUtil;
import com.ruoyi.common.utils.poi.ExportExcelUtil;
import com.ruoyi.common.utils.poi.ImportExcelUtil;
import com.ruoyi.party.domain.PartyMember;
import com.ruoyi.party.domain.PartyMemberError;
import com.ruoyi.party.domain.PartyOrganization;
import com.ruoyi.party.domain.vo.PartyMemberVo;
import com.ruoyi.party.mapper.PartyMemberErrorMapper;
import com.ruoyi.party.mapper.PartyMemberMapper;
import com.ruoyi.party.mapper.PartyOrganizationMapper;
import com.ruoyi.party.service.api.IPartyMemberService;
import com.ruoyi.system.mapper.system.SysDictDataMapper;
import org.apache.commons.collections.CollectionUtils;
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 java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 党员Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-17
 */
@Service
@DataSource(value = DataSourceType.SLAVE)
public class PartyMemberServiceImpl implements IPartyMemberService
{
    @Autowired
    private PartyMemberMapper partyMemberMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private PartyMemberErrorMapper partyMemberErrorMapper;

    @Autowired
    private PartyOrganizationMapper partyOrganizationMapper;

    /**
     * 查询党员
     *
     * @param id 党员主键
     * @return 党员
     */
    @Override
    public PartyMemberVo selectPartyMemberById(Long id)
    {
        PartyMember partyMember = partyMemberMapper.selectPartyMemberById(id);
        PartyMemberVo partyMemberVo = new PartyMemberVo();
        BeanUtils.copyProperties(partyMember, partyMemberVo);
        if(StringUtils.isNotBlank(partyMember.getDzzmc())){
            PartyOrganization partyOrganization = partyOrganizationMapper.getByDzzdm(partyMember.getDzzmc());
            partyMemberVo.setDzzName(partyOrganization == null?"": partyOrganization.getDzzmc());
        }
        return partyMemberVo;
    }

    /**
     * 查询党员列表
     *
     * @param partyMember 党员
     * @return 党员
     */
    @Override
    public List<PartyMember> selectPartyMemberList(PartyMember partyMember)
    {
        return partyMemberMapper.selectPartyMemberList(partyMember);
    }

    /**
     * 新增党员
     *
     * @param partyMember 党员
     * @return 结果
     */
    @Override
    public int insertPartyMember(PartyMember partyMember)
    {
        if(StringUtils.isNotBlank(partyMember.getDzzmc())){
            PartyOrganization partyOrganization = partyOrganizationMapper.getByDzzdm(partyMember.getDzzmc());
            partyMember.setWgCode(partyOrganization == null?"":partyOrganization.getSswg());
        }
        return partyMemberMapper.insertPartyMember(partyMember);
    }

    /**
     * 修改党员
     *
     * @param partyMember 党员
     * @return 结果
     */
    @Override
    public int updatePartyMember(PartyMember partyMember)
    {
        if(StringUtils.isNotBlank(partyMember.getDzzmc())){
            PartyOrganization partyOrganization = partyOrganizationMapper.getByDzzdm(partyMember.getDzzmc());
            partyMember.setWgCode(partyOrganization == null?"":partyOrganization.getSswg());
        }
        return partyMemberMapper.updatePartyMember(partyMember);
    }

    /**
     * 批量删除党员
     *
     * @param ids 需要删除的党员主键
     * @return 结果
     */
    @Override
    public int deletePartyMemberByIds(String[] ids)
    {
        return partyMemberMapper.deletePartyMemberByIds(ids);
    }

    /**
     * 删除党员信息
     *
     * @param id 党员主键
     * @return 结果
     */
    @Override
    public int deletePartyMemberById(String id)
    {
        return partyMemberMapper.deletePartyMemberById(id);
    }


    @Override
    public Integer getPartyCount() {
        return partyMemberMapper.getPartyCount();
    }

    @Override
    public List<Map<String, String>> getXLFB(String orgId) {
        return partyMemberMapper.getXLFB(orgId);
    }

    @Override
    public List<Map<String, String>> getDl(String orgId) {
        return partyMemberMapper.getDl(orgId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(Workbook workbook, Map<String, SysDictData> treeMap, Map<String, SysDictData> educationMap) {
        StringBuilder msg;
        //开始执行解析
        Sheet sheet = workbook.getSheetAt(0); //读取工作表
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat ft2 = new SimpleDateFormat("yyyy-MM-dd");
        List<PartyMember> list = new ArrayList<>();
        for (int j = 1; j <= sheet.getLastRowNum(); j++) {
            Row row = sheet.getRow(j);
            if (null != row && row.getCell(0) != null) {
                // 姓名
                PartyMember partyMember = new PartyMember();
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(0)))) {
                    msg = new StringBuilder("姓名不能为空");
                    insertPartyMemberError(row, msg.toString());
                    continue;
                } else {
                    partyMember.setXm(ImportExcelUtil.getValue(row.getCell(0)));
                }

                // 性别
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(1)))) {
                    msg = new StringBuilder("性别不能为空");
                    insertPartyMemberError(row, msg.toString());
                    continue;
                } else {
                    partyMember.setXb(ImportExcelUtil.getValue(row.getCell(1)));
                }

                // 身份证号
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(2)))) {
                    msg = new StringBuilder("身份证号不能为空");
                    insertPartyMemberError(row, msg.toString());
                    continue;
                } else {
                    partyMember.setSfzh(ImportExcelUtil.getValue(row.getCell(2)));
                }

                // 出生日期
                String birthValue = ImportExcelUtil.getValue(row.getCell(3));
                if (StringUtils.isNotBlank(birthValue)) {
                    try {
                        Date birthDate = ft.parse(birthValue);
                        partyMember.setCsrq(ft2.format(birthDate));
                    } catch (ParseException e) {
                        msg = new StringBuilder("出生日期转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                }else{
                    msg = new StringBuilder("出生日期不能为空");
                    insertPartyMemberError(row, msg.toString());
                }

                // 民族
                if (StringUtils.isBlank(ImportExcelUtil.getValue(row.getCell(4)))) {
                    msg = new StringBuilder("民族不能为空");
                    insertPartyMemberError(row, msg.toString());
                    continue;
                } else {
                    partyMember.setMz(ImportExcelUtil.getValue(row.getCell(4)));
                }

                // 籍贯
                String jgValue = ImportExcelUtil.getValue(row.getCell(5));
                if (StringUtils.isNotBlank(jgValue)) {
                    partyMember.setJg(jgValue);
                }

                // 学历
                String xlValue = ImportExcelUtil.getValue(row.getCell(6));
                if (StringUtils.isNotBlank(xlValue)) {
                    if(educationMap.isEmpty()){
                        msg = new StringBuilder("学历转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                    if (educationMap.containsKey(xlValue)) {
                        partyMember.setXl(educationMap.get(xlValue).getDictValue());
                    }
                }

                // 入党日期
                String rdrqValue = ImportExcelUtil.getValue(row.getCell(7));
                if (StringUtils.isNotBlank(rdrqValue)) {
                    try {
                        Date rdDate = ft.parse(rdrqValue);
                        partyMember.setRdrq(ft2.format(rdDate));
                    } catch (ParseException e) {
                        msg = new StringBuilder("入党日期转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                }

                // 转正日期
                String zzrqValue = ImportExcelUtil.getValue(row.getCell(8));
                if (StringUtils.isNotBlank(zzrqValue)) {
                    try {
                        Date zzDate = ft.parse(rdrqValue);
                        partyMember.setZzrq(ft2.format(zzDate));
                    } catch (ParseException e) {
                        msg = new StringBuilder("转正日期转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                }

                // 人员类别
                String rylbValue = ImportExcelUtil.getValue(row.getCell(9));
                if (StringUtils.isNotBlank(rylbValue)) {
                    if (!treeMap.isEmpty()) {
                        if (treeMap.containsKey(rylbValue)) {
                            partyMember.setRylb(treeMap.get(rylbValue).getDictValue());
                        }
                    } else {
                        msg = new StringBuilder("人员类别转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                }

                // 联系电话
                String lxdhValue = ImportExcelUtil.getValue(row.getCell(10));
                if (StringUtils.isNotBlank(lxdhValue)) {
                    partyMember.setLxdh(lxdhValue);
                }

                // 党组织名称
                String dzzmcValue = ImportExcelUtil.getValue(row.getCell(11));
                if (StringUtils.isNotBlank(dzzmcValue)) {
                    PartyOrganization partyOrganization = partyOrganizationMapper.getByDzzmc(dzzmcValue);
                    //只保存党组织代码以防名称改变
                    partyMember.setDzzmc(partyOrganization == null?"":partyOrganization.getDzzdm());
                } else {
                    msg = new StringBuilder("党组织名称不能为空");
                    insertPartyMemberError(row, msg.toString());
                    continue;
                }

                // 照片
                String zpValue = ImportExcelUtil.getValue(row.getCell(12));
                if (StringUtils.isNotBlank(zpValue)) {
                    partyMember.setDyphoto(zpValue);
                }

                // 入库时间
                String rksjValue = ImportExcelUtil.getValue(row.getCell(13));
                if (StringUtils.isNotBlank(rksjValue)) {
                    try {
                        Date rkDate = ft.parse(rksjValue);
                        partyMember.setRksj(ft2.format(rkDate));
                    } catch (ParseException e) {
                        msg = new StringBuilder("入库时间转换出错");
                        insertPartyMemberError(row, msg.toString());
                        continue;
                    }
                }
                list.add(partyMember);
            }
        }
        for (PartyMember item : list) {
            partyMemberMapper.insertPartyMember(item);
        }
    }

    private void insertPartyMemberError(Row row,String errorMsg) {
        PartyMemberError upe = new PartyMemberError();
        upe.setXm(ImportExcelUtil.getValue(row.getCell(0)));
        upe.setXb(ImportExcelUtil.getValue(row.getCell(1)));
        upe.setSfzh(ImportExcelUtil.getValue(row.getCell(2)));
        upe.setCsrq(ImportExcelUtil.getValue(row.getCell(3)));
        upe.setMz(ImportExcelUtil.getValue(row.getCell(4)));
        upe.setJg(ImportExcelUtil.getValue(row.getCell(5)));
        upe.setXl(ImportExcelUtil.getValue(row.getCell(6)));
        upe.setRdrq(ImportExcelUtil.getValue(row.getCell(7)));
        upe.setZzrq(ImportExcelUtil.getValue(row.getCell(8)));
        upe.setRylb(ImportExcelUtil.getValue(row.getCell(9)));
        upe.setLxdh(ImportExcelUtil.getValue(row.getCell(10)));
        upe.setDzzmc(ImportExcelUtil.getValue(row.getCell(11)));
        upe.setRksj(ImportExcelUtil.getValue(row.getCell(13)));
        upe.setRemark(errorMsg);
        upe.setCreateTime(new Date());
        partyMemberErrorMapper.insertPartyMemberError(upe);
    }

    @Override
    public HSSFWorkbook exportTemplate() {
        //首行中文标题
        String[] titleCNName={"*姓名","*性别", "*身份证号","*出生日期", "*民族", "籍贯", "学历", "入党日期", "转正日期", "人员类别(“正式党员、预备党员、发展对象、入党积极分子、入党申请人”)", "联系电话", "*党组织名称", "照片", "入库时间"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        //首行中文标题
        ExportExcelUtil.createSheet(workbook,titleCNName, null, null,0,false,"main");
        return workbook;
    }

    @Override
    public List<PartyMemberVo> convertToVo(List<PartyMember> memberList) {
        List<PartyMemberVo> voList = BeanCopyUtil.bathToBean(memberList, PartyMemberVo.class);
        if(!CollectionUtils.isEmpty(voList)){
            voList.forEach( e ->{
                if(com.ruoyi.common.utils.StringUtils.isNotBlank(e.getDzzmc())){
                    PartyOrganization partyOrganization = partyOrganizationMapper.getByDzzdm(e.getDzzmc());
                    e.setDzzName(partyOrganization == null?"":partyOrganization.getDzzmc());
                }
            });
        }
        return voList;
    }

    @Override
    public List<String> getAgeList() {
        return partyMemberMapper.getAgeList();
    }
}
