package com.hz.pm.api.gov.manage;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hz.pm.api.expert.entity.ExpertGovBusinessStrip;
import com.hz.pm.api.expert.entity.ExpertUserFullInfo;
import com.hz.pm.api.expert.service.IExpertGovBusinessStripService;
import com.hz.pm.api.expert.service.IExpertUserFullInfoService;
import com.hz.pm.api.gov.entity.BelongOrg;
import com.hz.pm.api.gov.enumeration.BelongTypeEnum;
import com.hz.pm.api.gov.model.vo.GovBusinessStripVO;
import com.hz.pm.api.gov.service.IBelongOrgService;
import com.hz.pm.api.organization.model.entity.DingOrganization;
import com.hz.pm.api.organization.service.IDingOrganizationService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuxinxin
 * @date 2023/4/18 下午2:27
 */

@Component
@RequiredArgsConstructor
public class BelongOrgManage {

    private final IBelongOrgService iBelongOrgService;
    private final IExpertUserFullInfoService expertUserFullInfoService;
    private final IDingOrganizationService dingOrganizationService;
    private final IExpertGovBusinessStripService expertGovBusinessStripService;


    public void generateBusinessStripOrg() {
        // 条线Set
        Set<String> businessStripSet = new HashSet<>();

        // 组织 Set
        Set<String> orgSet = new HashSet<>();

        try {
            //创建工作簿对象
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(Files.newInputStream(Paths.get("/Users/liuxinxin/Desktop/gov_business_strip_inport.xlsx")));
            //获取工作簿下sheet的个数
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有：" + sheetNum + "个sheet");
            //遍历工作簿中的所有数据
            for (int i = 0; i < sheetNum; i++) {
                //读取第i个工作表
                System.out.println("读取第" + (i + 1) + "个sheet");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                //获取最后一行的num，即总行数。此处从0开始
                int maxRow = sheet.getLastRowNum();

                // 条线code
                // 条线名称
                String businessStripOrgCode = sheet.getRow(1).getCell(0) + "";
                String businessStripOrgName = sheet.getRow(1).getCell(1) + "";
                String uniqKey = businessStripOrgCode + "####" + businessStripOrgName;
                businessStripSet.add(uniqKey);

                for (int row = 1; row <= maxRow; row++) {
                    //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***

                    String cell2 = getCellStr(sheet, row, 2);
                    String cell3 = getCellStr(sheet, row, 3);
                    if (StringUtils.isNotBlank(cell2) && StringUtils.isNotBlank(cell3)) {
                        String orgUniqKey = uniqKey + "&&&" + cell2 + "####" + cell3;
                        orgSet.add(orgUniqKey);
                    }

                    String cell4 = getCellStr(sheet, row, 4);
                    String cell5 = getCellStr(sheet, row, 5);

                    if (StringUtils.isNotBlank(cell4) && StringUtils.isNotBlank(cell5)) {
                        String orgUniqKey = uniqKey + "&&&" + cell4 + "####" + cell5;
                        orgSet.add(orgUniqKey);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<BelongOrg> orgList = orgSet.stream().map(BelongOrgManage::buildBelongOrg).collect(Collectors.toList());
        List<BelongOrg> belongOrgList = businessStripSet.stream().map(BelongOrgManage::buildBusinessStrip).collect(Collectors.toList());

        iBelongOrgService.saveBatch(orgList);
        iBelongOrgService.saveBatch(belongOrgList);
    }

    public static BelongOrg buildBusinessStrip(String businessStripStr) {
        String[] split = businessStripStr.split("&&&");
        String busStrip = split[0];
        String[] split1 = busStrip.split("####");
        String belongOrgCode = split1[0];
        String belongOrgName = split1[1];

        BelongOrg belongOrg = new BelongOrg();
        belongOrg.setOrgCode(belongOrgCode);
        belongOrg.setOrgName(belongOrgName);
        belongOrg.setBelongCode(belongOrgCode);
        belongOrg.setBelongName(belongOrgName);
        belongOrg.setOrgType(BelongTypeEnum.GOV_BUSINESS_STRIP.name());
        return belongOrg;
    }

    public static BelongOrg buildBelongOrg(String orgStr) {
        String[] split = orgStr.split("&&&");
        String busStrip = split[0];
        String[] split1 = busStrip.split("####");
        String belongOrgCode = split1[0];
        String belongOrgName = split1[1];

        String org = split[1];
        String[] split2 = org.split("####");
        String orgCode = split2[0];
        String orgName = split2[1];

        BelongOrg belongOrg = new BelongOrg();
        belongOrg.setOrgCode(orgCode);
        belongOrg.setOrgName(orgName);
        belongOrg.setBelongCode(belongOrgCode);
        belongOrg.setBelongName(belongOrgName);
        belongOrg.setOrgType(BelongTypeEnum.ORGANIZATION.name());
        return belongOrg;
    }

    public static String getCellStr(XSSFSheet sheet, int row, int col) {
        if (Objects.isNull(sheet)) {
            return null;
        }
        XSSFRow row1 = sheet.getRow(row);
        if (Objects.isNull(row1)) {
            return null;
        }
        XSSFCell cell = row1.getCell(col);
        if (Objects.isNull(cell)) {
            return null;
        }
        return cell + "".trim();
    }


    public List<GovBusinessStripVO> getGovBusinessStripList(String businessStripName) {
        LambdaQueryWrapper<BelongOrg> query = Wrappers.lambdaQuery(BelongOrg.class)
                .like(StrUtil.isNotBlank(businessStripName), BelongOrg::getBelongName, businessStripName)
                .eq(BelongOrg::getOrgType, BelongTypeEnum.GOV_BUSINESS_STRIP.name());
        List<BelongOrg> belongOrgs = iBelongOrgService.list(query);
        return belongOrgs.stream().map(r -> {
            GovBusinessStripVO govBusinessStripVO = new GovBusinessStripVO();
            govBusinessStripVO.setBusinessStripCode(r.getOrgCode());
            govBusinessStripVO.setBusinessStripName(r.getOrgName());
            return govBusinessStripVO;
        }).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public void analysisExpertOrg() {
        List<ExpertUserFullInfo> expertUserFullInfoList = expertUserFullInfoService.list();
        for (ExpertUserFullInfo userFullInfo : expertUserFullInfoList) {
            String company = userFullInfo.getCompany();

            if (StringUtils.isNotBlank(company)) {
                // 获取专家信息
                List<DingOrganization> dingOrganizationList = dingOrganizationService
                        .list(Wrappers.lambdaQuery(DingOrganization.class)
                                .eq(DingOrganization::getOrganizationName, company.trim()));

                if (CollectionUtils.isNotEmpty(dingOrganizationList)) {
                    // 获取专家组织code
                    DingOrganization dingOrganization = dingOrganizationList.get(0);
                    String organizationCode = dingOrganization.getOrganizationCode();

                    List<BelongOrg> belongOrgList = iBelongOrgService
                            .list(Wrappers.lambdaQuery(BelongOrg.class)
                                    .eq(BelongOrg::getOrgCode, organizationCode.trim()));
                    if (CollectionUtils.isNotEmpty(belongOrgList)) {
                        // 获取专家条线code
                        Set<String> belongOrgSet = new HashSet<>();
                        List<BelongOrg> saveList = new ArrayList<>();
                        for (BelongOrg belongOrg : belongOrgList) {
                            if (belongOrgSet.add(belongOrg.getBelongCode())) {
                                saveList.add(belongOrg);
                            }
                        }
                        expertGovBusinessStripService.remove(Wrappers.lambdaQuery(ExpertGovBusinessStrip.class)
                                .eq(ExpertGovBusinessStrip::getExpertUserId, userFullInfo.getUserId()));

                        List<ExpertGovBusinessStrip> expertBusinessStripSaveRecordList = saveList.stream().map(r -> {
                            ExpertGovBusinessStrip expertBusinessStrip = new ExpertGovBusinessStrip();
                            expertBusinessStrip.setExpertUserId(userFullInfo.getUserId());
                            expertBusinessStrip.setBusinessStripCode(r.getBelongCode());
                            expertBusinessStrip.setBusinessStripName(r.getBelongName());
                            return expertBusinessStrip;
                        }).collect(Collectors.toList());
                        expertGovBusinessStripService.saveBatch(expertBusinessStripSaveRecordList);
                    }
                }
            }

        }
    }

}
