package cn.palmte.work.service;

import cn.palmte.work.bean.StatusEnum;
import cn.palmte.work.model.Admin;
import cn.palmte.work.model.Project;
import cn.palmte.work.model.SysRole;
import cn.palmte.work.model.SysRoleRepository;
import cn.palmte.work.pojo.SpaceVO;
import cn.palmte.work.utils.InterfaceUtil;
import cn.palmte.work.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jfunc.common.db.QueryHelper;
import top.jfunc.common.db.bean.Page;
import top.jfunc.common.db.bean.Record;
import top.jfunc.common.db.utils.Pagination;
import top.jfunc.common.utils.CollectionUtil;
import top.jfunc.common.utils.StrUtil;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SpaceService {
    private static final Logger logger = LoggerFactory.getLogger(SpaceService.class);

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private Pagination pagination;

    public Page<Project> list(Map<String, String> searchInfo, int pageNumber, int pageSize){
        QueryHelper queryHelper = getQueryHelper(searchInfo);

        Page<Project> page = pagination.paginate(queryHelper.getSql(), Project.class, pageNumber, pageSize);
        List<Project> list = page.getList();
        if(CollectionUtil.isNotEmpty(list)) {
            //查询项目当前审批任务节点
            for (Project project : list) {
                if (project.getApproveStatusBudget() > -1 && project.getIsBudget() == 1) {
                    project.setContractRound(project.getContractRound2());
                    project.setHuizhiRound(project.getHuizhiRound2());
                    project.setHuazhiRound(project.getHuazhiRound2());
                    project.setHuasanRound(project.getHuasanRound2());
                    project.setZiguangRound(project.getZiguangRound2());
                    project.setGrossProfitRound(project.getGrossProfitRound2());
                    project.setGrossProfitMarginRound(project.getGrossProfitMarginRound2());
                    project.setAdvancePeakAmountRound(project.getAdvancePeakAmountRound2());
                    project.setAdvanceInterestAmountRound(project.getAdvanceInterestAmountRound2());
                }
                if(null == project.getStage()){
                    project.setStageName(projectService.getStageName(-1));
                }else {
                    project.setStageName(projectService.getStageName(project.getStage()));
                }
            }
        }
        return page;
    }

    private QueryHelper getQueryHelper(Map<String, String> searchInfo) {
        QueryHelper queryHelper = new QueryHelper("SELECT p.*, FORMAT(p.contract_amount,2) as contractRound, FORMAT(p.huazhi_product_amount,2) as huazhiRound, FORMAT(p.huizhi_product_amount,2) as huizhiRound, FORMAT(p.huasan_product_amount,2) as huasanRound, FORMAT(p.ziguang_other_amount,2) as ziguangRound" +
                ", FORMAT(p.gross_profit,2) as grossProfitRound, FORMAT(p.gross_profit_margin,2) as grossProfitMarginRound, FORMAT(p.advance_interest_amount,2) as advanceInterestAmountRound, FORMAT(p.advance_peak_amount,2) as advancePeakAmountRound, pe.is_budget as isBudget" +
                ", FORMAT(pe.contract_amount,2) as contractRound2, FORMAT(pe.huazhi_product_amount,2) as huazhiRound2, FORMAT(pe.huizhi_product_amount,2) as huizhiRound2, FORMAT(pe.huasan_product_amount,2) as huasanRound2, FORMAT(pe.ziguang_other_amount,2) as ziguangRound2" +
                ", FORMAT(pe.gross_profit,2) as grossProfitRound2, FORMAT(pe.gross_profit_margin,2) as grossProfitMarginRound2, FORMAT(pe.advance_interest_amount,2) as advanceInterestAmountRound2, FORMAT(pe.advance_peak_amount,2) as advancePeakAmountRound2","project","p");
        queryHelper.leftJoin("project_extend pe", "p.id = pe.project_id and pe.is_budget = 1");

        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("name")),"p.name LIKE ?", "%"+searchInfo.get("name")+"%");
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("customer")),"p.customer LIKE ?", "%"+searchInfo.get("customer")+"%");
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("terminalCustomer")),"p.terminal_customer LIKE ?", "%"+searchInfo.get("terminalCustomer")+"%");
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("principal")),"p.principal LIKE ?", "%"+searchInfo.get("principal")+"%");
        if(StrUtil.isNotEmpty(searchInfo.get("certainty")) && !"-1".equals(searchInfo.get("certainty"))){
            queryHelper.addCondition("p.certainty=?", Integer.parseInt(searchInfo.get("certainty")));
        }

        if(StrUtil.isNotEmpty(searchInfo.get("approveStatus")) && !"-1".equals(searchInfo.get("approveStatus"))){
            int approveStatus = Integer.parseInt(searchInfo.get("approveStatus"));
            //四种状态满足其一即可
            queryHelper.addCondition("((p.status=? AND p.approve_status_estimate=?) OR (p.status=? AND p.approve_status_budget=?) OR (p.status=? AND p.approve_status_settle=?) OR (p.status=? AND p.approve_status_final=?))",
                    StatusEnum.ESTIMATE_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.BUDGET_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.SETTLE_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.FINAL_ACCOUNTS.getStatus(),approveStatus);
        }
        if(StrUtil.isNotEmpty(searchInfo.get("type")) && !"-1".equals(searchInfo.get("type"))){
            queryHelper.addCondition("p.type=?", Integer.parseInt(searchInfo.get("type")));
        }
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("deptName")),"p.dept_name = ?", searchInfo.get("deptName"));
        if(StrUtil.isNotEmpty(searchInfo.get("estimateStatus")) && !"-1".equals(searchInfo.get("estimateStatus"))){
            queryHelper.addCondition("p.approve_status_estimate>=1 and p.approve_status_estimate<=2");
        }

        if (StrUtil.isNotEmpty(searchInfo.get("isSecond")) && !"-1".equals(searchInfo.get("isSecond"))) {
            queryHelper.addCondition("p.is_second=?", Integer.parseInt(searchInfo.get("isSecond")));
        }
        if (StrUtil.isNotEmpty(searchInfo.get("resolvePlan")) && !"-1".equals(searchInfo.get("resolvePlan"))) {
            queryHelper.addCondition("p.resolve_plan=?", Integer.parseInt(searchInfo.get("resolvePlan")));
        }
        /**
         * 只选择了一个时间的情况，就项目时间包括这个时间的
         */
        if (StrUtil.isNotEmpty(searchInfo.get("startDate")) && StrUtil.isEmpty(searchInfo.get("endDate"))) {
            String time = searchInfo.get("startDate") + " 00:00:00";
            queryHelper.addCondition("p.start_date<=? AND p.end_date>=?", time, time);
        }
        if (StrUtil.isNotEmpty(searchInfo.get("endDate")) && StrUtil.isEmpty(searchInfo.get("startDate"))) {
            String time = searchInfo.get("endDate") + " 00:00:00";
            queryHelper.addCondition("p.start_date<=? AND p.end_date>=?", time, time);
        }
        /**
         * 两个时间都选了，则包含项目时间
         */
        if (StrUtil.isNotEmpty(searchInfo.get("startDate")) && StrUtil.isNotEmpty(searchInfo.get("endDate"))) {
            String startTime = searchInfo.get("startDate") + " 00:00:00";
            String endTime = searchInfo.get("endDate") + " 23:59:59";
            queryHelper.addCondition("p.start_date>=? AND p.end_date<=?", startTime, endTime);
        }
        if (StrUtil.isNotEmpty(searchInfo.get("contractStartTime"))) {
            String time = searchInfo.get("contractStartTime") + " 00:00:00";
            queryHelper.addCondition("p.contract_time>=?", time);
        }
        if (StrUtil.isNotEmpty(searchInfo.get("contractEndTime"))) {
            String time = searchInfo.get("contractEndTime") + " 00:00:00";
            queryHelper.addCondition("p.contract_time<=?", time);
        }

        //项目可见性，根据角色和人员id
        Admin admin = InterfaceUtil.getAdmin();
        int roleId = admin.getRoleId();
        Integer adminId = admin.getId();
        //自己创建的肯定能看见，配置的可以看见，系统管理员可以看见
        SysRole sysRole = sysRoleRepository.findSysRoleById(roleId);
        if(SysRole.ROLE_TYPE_SYSTEM != sysRole.getType()){
            queryHelper.addCondition("(p.creator_id=? OR p.approve_id=? OR p.id in (SELECT pv1.project_id FROM project_visible pv1 WHERE pv1.type=1 AND pv1.tid=? UNION SELECT pv2.project_id FROM project_visible pv2 WHERE pv2.type=2 AND pv2.tid=?))", adminId, adminId, roleId, adminId);
        }

        queryHelper.addDescOrderProperty("p.last_update_time");

        return queryHelper;
    }

    public SpaceVO getListData() {

        String sql = "SELECT count(id) as sum, certainty, certainty_str as name FROM project WHERE certainty >= 1 and approve_status_estimate >= 1 and approve_status_estimate <= 2 and dept_name = '销售管理部' GROUP BY certainty";
        List<Record> pie = pagination.find(sql);

        String sql2 = "SELECT sum(IFNULL(IF(pe.is_budget = 1, pe.contract_amount, p.contract_amount),0)) AS sum, avg(IFNULL(IF(pe.is_budget = 1, pe.gross_profit_margin, p.gross_profit_margin),0)) AS average, p.certainty, p.certainty_str as name, pe.is_budget FROM project p LEFT JOIN project_extend pe ON p.id = pe.project_id WHERE p.certainty >= 1 and p.approve_status_estimate >= 1 AND p.approve_status_estimate <= 2 AND p.dept_name = '销售管理部' GROUP BY p.certainty";
        List<Record> bar = pagination.find(sql2);
        return combineData(pie, bar);
    }

    private SpaceVO combineData(List<Record> pie, List<Record> bar) {
        Map<String, Record> map = pie.stream().peek(a -> a.set("name", "把握度" + a.getStr("name"))).collect(Collectors.toMap(record -> String.valueOf(record.getInt("certainty")), Function.identity()));

        bar = bar.stream().peek(a -> a.set("average", Utils.format(a.getBigDecimal("average")))).collect(Collectors.toList());

        SpaceVO spaceVO = new SpaceVO();
        spaceVO.setMap(map);
        spaceVO.setList(bar);
        return spaceVO;
    }
}
