package com.engine.recruit.service.impl;

import com.engine.core.impl.Service;
import com.engine.recruit.entity.workbench.OptionVO;
import com.engine.recruit.entity.workbench.RecruitInterviewPO;
import com.engine.recruit.entity.workbench.RecruitPortalCommonVO;
import com.engine.recruit.entity.workbench.SeriesParam;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author liang.cheng
 * @Date 2023/10/18 4:44 PM
 * @Version 1.0
 */
public class WorkBenchPortalServiceImpl extends Service implements com.engine.recruit.service.WorkBenchPortalService {

    private final DecimalFormat df = new DecimalFormat("#.00");

    @Override
    public List<RecruitPortalCommonVO> getRecruitPortalTop() {
        RecordSet rs = new RecordSet();
        List<RecruitPortalCommonVO> recruitList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        rs.executeQuery("select b.zpzwfzr,b.zpxzr from uf_jcl_yppc a left join uf_jcl_zp_zpzw b on a.ypzw = b.id\n" +
                "where a.zt = 1");
        while (rs.next()) {
            String zpzwfzr = Util.null2String(rs.getString("zpzwfzr"));
            String zpxzr = Util.null2String(rs.getString("zpxzr"));
            list.add(mergeStrings(zpzwfzr, zpxzr));
        }
        String uId = String.valueOf(user.getUID());

        List<String> filteredList = list.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        recruitList.add(RecruitPortalCommonVO.builder().title("待处理简历").count(filteredList.size()).icon("${appRes}/1.png").build());
        recruitList.add(selectRecruitInterview("select msg,ptmsg,msrq from uf_jcl_ms", "今日面试", "${appRes}/2.png", uId));
        recruitList.add(selectRecruitInterview("select msg,ptmsg,msrq from uf_jcl_ms where zt = 0", "待评价面试", "${appRes}/3.png", uId));
        recruitList.add(selectOffer("select b.zpzwfzr,b.zpxzr from uf_jcl_offer a left join uf_jcl_zp_zpzw b on a.ypzw = b.id where a.zt = 0",
                "待发offer", "${appRes}/4.png", uId));
        recruitList.add(selectOffer("select b.zpzwfzr,b.zpxzr from uf_jcl_offer a left join uf_jcl_zp_zpzw b on a.ypzw = b.id where a.zt = 1",
                "待反馈offer", "${appRes}/5.png", uId));
        recruitList.add(RecruitPortalCommonVO.builder().title("待入职").count(waitHired()).icon("${appRes}/6.png").build());


        return recruitList;
    }

    @Override
    public OptionVO getJobTenure() {
        RecordSet rs = new RecordSet();
        List<RecruitPortalCommonVO> list = new ArrayList<>();
        rs.executeQuery("select a.xxnr,b.sum from uf_sjzd a \n" +
                "left join (select gznx,count(1) as sum from uf_jcl_zp_zpzw group by gznx) b \n" +
                "on a.id = b.gznx where a.zdlxmc = 9");
        while (rs.next()) {
            list.add(RecruitPortalCommonVO.builder().count(Util.getIntValue(rs.getString("sum"),0)).title(Util.null2String(rs.getString("xxnr"))).build());
        }


        List<String> xData = list.stream()
                .map(RecruitPortalCommonVO::getTitle)
                .collect(Collectors.toList());

        List<Integer> barSeriesData = list.stream()
                .map(RecruitPortalCommonVO::getCount)
                .collect(Collectors.toList());

        return OptionVO.builder()
                .text("职位年限要求分布")
                .xData(xData)
                .barSeriesData(barSeriesData)
                .build();
    }

    @Override
    public OptionVO getWaitStepPerson() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select dqypjd,count(1) as sum  from uf_jcl_yppc where dqypjd is not null group by dqypjd");
        List<String> xData = new ArrayList<>();
        List<Integer> barSeriesData = new ArrayList<>();
        while (rs.next()) {

            xData.add(Util.null2String(rs.getString("xxnr")));
            barSeriesData.add(Util.getIntValue(rs.getString("sum")),0);
        }

        return OptionVO.builder()
                .text("候选中应聘者各阶段数")
                .xData(xData)
                .barSeriesData(barSeriesData)
                .build();
    }

    @Override
    public OptionVO getRecruitTransform() {
        List<String> colorList = Arrays.asList("#6e94f3","#faf0e6","#7cfc00","#ao20f0","#00ced1","#83d8ae","#697695","#8ac9e9","#9933fa","#c0ff3e","#ffe4c4","#cd6090");
        RecordSet rs = new RecordSet();
        rs.executeQuery("select a.xxnr,b.sum from uf_sjzd a \n" +
                "left join (select gznx,count(1) as sum from uf_jcl_zp_zpzw group by gznx) b \n" +
                "on a.id = b.gznx where a.zdlxmc = 9");
        LinkedList<SeriesParam> seriesData = new LinkedList<>();
        while (rs.next()) {
            String name = Util.null2String(rs.getString("xxnr"));
            double value = Util.getDoubleValue(rs.getString("sum"), 0);
            Random r = new Random();
            seriesData.add(SeriesParam.builder().value(value).name(name).color(colorList.get(r.nextInt(colorList.size()))).build());

        }

        return  OptionVO.builder()
                .text("招聘转化")
                .seriesData(seriesData)
                .build();
    }

    @Override
    public OptionVO getPeopleFrom() {
        List<String> colorList = Arrays.asList("#6e94f3","#faf0e6","#7cfc00","#ao20f0","#00ced1","#83d8ae","#697695","#8ac9e9","#9933fa","#c0ff3e","#ffe4c4","#cd6090");
        RecordSet rs = new RecordSet();
        rs.executeQuery("select a.xxnr,b.sum from uf_sjzd a \n" +
                "left join (select jlly,count(1) as sum from uf_jcl_yppc group by jlly) b \n" +
                "on a.id = b.jlly where a.zdlxmc = 2");
        LinkedList<SeriesParam> seriesData = new LinkedList<>();
        while (rs.next()) {
            Random r = new Random();
            String name = Util.null2String(rs.getString("xxnr"));
            double value = Util.getDoubleValue(rs.getString("sum"), 0);
            seriesData.add(SeriesParam.builder().value(value).name(name).color(colorList.get(r.nextInt(colorList.size()))).build());
        }

        List<Double> values = seriesData.stream().map(SeriesParam:: getValue).collect(Collectors.toList());
        double percentage = values.stream().mapToDouble(Double::doubleValue).sum();
        seriesData.forEach(item -> item.setValue(Double.valueOf(df.format((item.getValue() * 100) / percentage))));

        return OptionVO.builder()
                .text("人才来源")
                .seriesData(seriesData)
                .build();
    }

    @Override
    public List<RecruitPortalCommonVO> getRecruitProgress() {
        List<RecruitPortalCommonVO> recruitList = new ArrayList<>();
        //招聘需求完成进度
        recruitList.add(getProgress());
        //面试出席率
        recruitList.add(getInterview(1));
        //面试通过率
        recruitList.add(getInterview(2));
        //接受offer
        recruitList.add(getOffer());
        //取消入职
        recruitList.add(getEntry(1));
        //按期入职
        recruitList.add(getEntry(2));

        return recruitList;
    }


    private RecruitPortalCommonVO getEntry(int type) {
        RecordSet rs = new RecordSet();
        String uId = String.valueOf(user.getUID());
        int complete;
        String title;
        String color;
        rs.executeQuery("select count(1) as sum from uf_jcl_rzgl where modedatacreater = ?",uId);
        rs.next();
        int all = Util.getIntValue(rs.getString("sum"));
        if (type == 1) {
            rs.executeQuery("select count(1) as complete from uf_jcl_rzgl where modedatacreater = ? and rzzt = 2",uId);
            rs.next();
            complete = Util.getIntValue(rs.getString("complete"));
            title = "取消入职";
            color = "#ff2516";
        }else {
            rs.executeQuery("select count(1) as complete from uf_jcl_rzgl where modedatacreater = ? and rzzt = 2 and rzrq = yjrzrq",uId);
            rs.next();
            complete = Util.getIntValue(rs.getString("complete"));
            title = "按期入职";
            color = "#a1e073";
        }

        double progress = all == 0 ? 0 :((double) complete / all) * 100;
        return RecruitPortalCommonVO.builder().title(title).scale(progress).color(color).build();
    }

    private RecruitPortalCommonVO getOffer() {
        RecordSet rs = new RecordSet();
        String uId = String.valueOf(user.getUID());
        rs.executeQuery("select count(1) as sum from uf_jcl_offer where sqr = ? and zt != 0",uId);
        rs.next();
        int all = Util.getIntValue(rs.getString("sum"));
        rs.executeQuery("select count(1) as complete from uf_jcl_offer where sqr = ? and zt = 3",uId);
        rs.next();
        int complete = Util.getIntValue(rs.getString("complete"));
        double progress = all == 0 ? 0 :((double) complete / all) * 100;
        return RecruitPortalCommonVO.builder().title("接受offer").scale(progress).color("#4cbadd").build();
    }


    private RecruitPortalCommonVO getProgress() {
        RecordSet rs = new RecordSet();
        List<String> all = new ArrayList<>();
        rs.executeQuery("select sqr,zpxqfzr from uf_jcl_zpxqjh");
        while (rs.next()) {
            String sqr = Util.null2String(rs.getString("sqr"));
            String zpxqfzr = Util.null2String(rs.getString("zpxqfzr"));
            all.add(mergeStrings(sqr, zpxqfzr));
        }
        String uId = String.valueOf(user.getUID());
        List<String> filterAll = all.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        List<String> complete = new ArrayList<>();
        rs.executeQuery("select sqr from uf_jcl_zpxqjh where xqzt = 1");
        while (rs.next()) {
            String sqr = Util.null2String(rs.getString("sqr"));
            String zpxqfzr = Util.null2String(rs.getString("zpxqfzr"));
            complete.add(mergeStrings(sqr, zpxqfzr));
        }
        List<String> filterComplete = complete.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        double progress = filterAll.size() == 0 ? 0 : ((double) filterComplete.size() / filterAll.size()) * 100;
        return RecruitPortalCommonVO.builder().title("招聘需求完成进度").scale(progress).color("#fdac3a").build();
    }

    private RecruitPortalCommonVO getInterview(int type) {
        RecordSet rs = new RecordSet();
        String uId = String.valueOf(user.getUID());
        String title;
        String color;
        rs.executeQuery("select msg,ptmsg from uf_jcl_ms");
        List<String> all = new ArrayList<>();
        List<String> complete = new ArrayList<>();
        while (rs.next()) {
            String msg = Util.null2String(rs.getString("msg"));
            String ptmsg = Util.null2String(rs.getString("ptmsg"));
            all.add(mergeStrings(msg, ptmsg));
        }
        List<String> filterAll = all.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        if (type == 1) {
            title = "面试出席率";
            color = "#5671fb";
            rs.executeQuery("select msg,ptmsg from uf_jcl_ms where zt = 1");
            while (rs.next()) {
                String msg = Util.null2String(rs.getString("msg"));
                String ptmsg = Util.null2String(rs.getString("ptmsg"));
                complete.add(mergeStrings(msg, ptmsg));
            }
        }else {
            title = "面试通过率";
            color = "#42d39e";
            rs.executeQuery("select msg,ptmsg from uf_jcl_ms where zt = 1 and jg = 1");
            while (rs.next()) {
                String msg = Util.null2String(rs.getString("msg"));
                String ptmsg = Util.null2String(rs.getString("ptmsg"));
                complete.add(mergeStrings(msg, ptmsg));
            }

        }
        List<String> filterComplete = complete.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        double progress = filterAll.size() == 0 ? 0 : ((double) filterComplete.size() / filterAll.size()) * 100;
        return RecruitPortalCommonVO.builder().title(title).scale(progress).color(color).build();

    }


    private Integer waitHired() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select count(1) as sum  from uf_jcl_rzgl where rzzt = 0");
        rs.next();
        return Util.getIntValue(rs.getString("sum"));
    }


    private RecruitPortalCommonVO selectOffer(String sql, String title, String icon, String uId) {
        RecordSet rs = new RecordSet();
        List<String> list = new ArrayList<>();
        rs.executeQuery(sql);
        while (rs.next()) {
            String zpzwfzr = Util.null2String(rs.getString("zpzwfzr"));
            String zpxzr = Util.null2String(rs.getString("zpxzr"));
            list.add(mergeStrings(zpzwfzr, zpxzr));
        }

        List<String> filteredList = list.stream()
                .filter(s -> s.contains(uId))
                .collect(Collectors.toList());
        return  RecruitPortalCommonVO.builder().title(title).count(filteredList.size()).icon(icon).build();
    }


    private RecruitPortalCommonVO selectRecruitInterview(String sql, String title, String icon, String uId) {
        RecordSet rs = new RecordSet();
        List<RecruitInterviewPO> recruitInterview = new ArrayList<>();
        rs.executeQuery(sql);
        while (rs.next()) {
            String msg = Util.null2String(rs.getString("msg"));
            String ptmsg = Util.null2String(rs.getString("ptmsg"));
            String msrq = Util.null2String(rs.getString("msrq")).substring(0,9);
            recruitInterview.add(RecruitInterviewPO.builder().ids(mergeStrings(msg, ptmsg)).interviewDate(msrq).build());
        }

        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateString = currentDate.format(formatter);

        List<RecruitInterviewPO> filterInterview = recruitInterview.stream()
                .filter(s -> s.getIds().contains(uId))
                .filter(s -> dateString.equals(s.getInterviewDate()))
                .collect(Collectors.toList());
        return RecruitPortalCommonVO.builder().title(title).count(filterInterview.size()).icon(icon).build();
    }

    private  String mergeStrings(String string1, String string2) {
        boolean isString1Empty = string1.isEmpty();
        boolean isString2Empty = string2.isEmpty();
        if (isString1Empty && isString2Empty) {
            return "";
        } else if (isString1Empty) {
            return string2;
        } else if (isString2Empty) {
            return string1;
        } else {
            return string1 + "," + string2;
        }
    }
}
