package com.testor.module.partner.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.hazard.dao.THazardWorkPlanDao;
import com.testor.module.partner.controller.TJobStatisticsController;
import com.testor.module.partner.dao.TJobStatisticsDao;
import com.testor.module.partner.model.domain.TJobStatistics;
import com.testor.module.partner.model.dto.TJobStatisticsParam;
import com.testor.module.partner.model.vo.*;
import com.testor.module.partner.service.TJobStatisticsService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperModel;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 现场作业统计Service业务层处理
 *
 * @author testor-framework
 * @date 2022-11-02 10:42:06
 */
@Slf4j
@Service
@EnableScheduling
public class TJobStatisticsServiceImpl extends SuperServiceImpl<TJobStatisticsDao, TJobStatistics> implements TJobStatisticsService {

    @Autowired(required = false)
    private TJobStatisticsDao tJobStatisticsDao;

    @Autowired(required = false)
    private TJobStatisticsController tJobStatisticsController;

    @Autowired(required = false)
    private SysOrgService sysOrgService;

    @Autowired
    private NewSysOrgService newSysOrgService;

    @Value("${tuan.path}")
    private String path;

    @Autowired
    private THazardWorkPlanDao hazardWorkPlanDao;

    //@XxlJob("add_JobStatistics")
    //@Scheduled(cron = "0 */4 * * * ?")
    @Transactional(isolation = Isolation.READ_COMMITTED)
    //@Override
    public void addJob() {
        log.info("===========================================相关作业统计======================================");
        TJobStatisticsParam tJobStatisticsParam = new TJobStatisticsParam();
        //开始时间
        DateTime dateTime = DateUtil.offsetHour(new Date(), -1);


        tJobStatisticsParam.setZyjssj(DateUtil.now());
        tJobStatisticsParam.setZykssj(dateTime.toString());
        // tJobStatisticsParam.setZyjssj("2022-10-01 00:00:00");
        // tJobStatisticsParam.setZykssj("2022-09-01 00:00:00");
        String s1 = JSONObject.toJSONString(tJobStatisticsParam);

        // String url = "http://117.14.55.74:17703/api/dform/index/GetMYDHZY";
        //登录
        String token = toLogin();

        String json = HttpRequest.post(path + "/dform/index/GetMYDHZY").body(s1).header("Authorization", token).execute().body();
//        String json = "{\n" +
//                "    \"code\": 1,\n" +
//                "    \"message\": \"success\",\n" +
//                "    \"data\": [\n" +
//                "        {\n" +
//                "            \"DHZY_ZYZT\": \"已关闭\",\n" +
//                "            \"DHZY_ZYLB\": \"吊装作业\",\n" +
//                "            \"DHZY_ZYKSSJ\": \"2022-07-22 09:50\",\n" +
//                "            \"XGFDWRY\": 5,\n" +
//                "            \"DHZY_ZYJSSJ\": \"2022-07-22 15:40\",\n" +
//                "            \"DHZY_ZKSSPRY\": \"\",\n" +
//                "            \"id\": \"cfd0ab19-911f-d678-4b8a-642724e95ffa\",\n" +
//                "            \"DHZY_GCMZ\": \"北良公司\",\n" +
//                "            \"SFZYK\": \"否\",\n" +
//                "\t\"code\":\"j_mhk\"\n" +
//                "        }\n" +
//                "    ]\n" +
//                "}";
        //{"code":0,"data":"登陆失效！","message":"error"}
        log.info("现场作业统计Service业务层处理_接口调用返回结果:{}", json);
        List<TJobStatistics> tJobStatisticsList = new ArrayList<>();
        try {
            tJobStatisticsList =   JSONObject.parseObject(json, TJobStatisticsParam.class).getData();
        }catch (Exception e){
            log.error("现场作业统计Service业务层处理_接口调用异常:{},接口返回结果:{}", e,json);
        }
        if (CollectionUtils.isEmpty(tJobStatisticsList)) {
            return;
        }
        ArrayList<String> tuanIds = new ArrayList<>();
        for (TJobStatistics tJobStatistics : tJobStatisticsList) {
            String dhzyId = tJobStatistics.getId();
            tuanIds.add(dhzyId);
            tJobStatistics.setDhzyId(dhzyId);
            tJobStatistics.setId(null);
        }
        LambdaUpdateWrapper<TJobStatistics> updateWrapper = new LambdaUpdateWrapper<>();
        if (ObjectUtil.isNotEmpty(tuanIds)) {
            updateWrapper.in(ObjectUtil.isNotEmpty(tuanIds), TJobStatistics::getDhzyId, tuanIds).set(SuperModel::getStatus, 1);
            this.update(updateWrapper);
        }

        boolean b = this.saveBatch(tJobStatisticsList);

    }

    /**
     * 登录获取token
     * @return
     */
    public String toLogin() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "18727779999");
        jsonObject.put("password", "");
        JSONObject outcome = JSONObject.parseObject(HttpRequest.post(path + "/auth/ssoLogin").body(jsonObject.toJSONString()).execute().body());
        String token = outcome.get("message").toString();
        return token;
    }


    @Override
    public List<DangerousNumVO> dangerousNum(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.dangerousNum(param);
//        if (param.getAdd()&& !CollectionUtils.isEmpty(dangerousNumVOList)) {
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            addJob();
//        }
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> regionalGrain(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.regionalGrain(param);
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> area(TJobStatisticsParam param) {

        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.area(param);
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> grainDepot(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.grainDepot(param);
        return dangerousNumVOList;
    }

    @Override
    public HazardousOperation distributionSum(TJobStatisticsParam param) {
        List<HazardousOperation> dangerousNumVOS = tJobStatisticsDao.distributionSum(param);

        return dangerousNumVOS.get(0);
    }

    @Override
    public HazardousOperation distributionRegionalCompanyGrainDepot(TJobStatisticsParam param) {


        List<HazardousOperation> dangerousNumVOS = tJobStatisticsDao.distributionRegionalCompanyGrainDepot(param);


        return dangerousNumVOS.get(0);

    }

    @Override
    public HazardousOperation distributionRegionalCompaniesRentStorage(TJobStatisticsParam param) {
        List<HazardousOperation> dangerousNumVOList = tJobStatisticsDao.distributionRegionalCompaniesRentStorage(param);
        return dangerousNumVOList.get(0);

    }

    @Override
    public HazardousOperation distributionGrainDepot(TJobStatisticsParam param) {

        List<HazardousOperation> dangerousNumVOList = tJobStatisticsDao.distributionGrainDepot(param);

        return dangerousNumVOList.get(0);
    }

    @Override
    public List<DangerousNumVO> foreignHeadquarters(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.foreignHeadquarters(param);
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> foreignRegionalGrain(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.foreignRegionalGrain(param);
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> foreignRentalLibrary(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.foreignRentalLibrary(param);
        return dangerousNumVOList;
    }

    @Override
    public List<DangerousNumVO> foreignGrainDepot(TJobStatisticsParam param) {
        List<DangerousNumVO> dangerousNumVOList = tJobStatisticsDao.foreignGrainDepot(param);
        return dangerousNumVOList;
    }

    @Override
    public List<FieldStatisticsFormVO> fieldStatisticsFormHeadquarters(TJobStatisticsParam param) {
        ArrayList<FieldStatisticsFormVO> fieldStatisticsFormVOS = new ArrayList<>();
        param.setAdd(false);
        //危险作业次数
        Map<String, List<DangerousNumVO>> wxzyMap = tJobStatisticsController.dangerousNum(param).getData().stream().collect(Collectors.groupingBy(DangerousNumVO::getOrgId));

        //外来作业相关方人次数量
        List<DangerousNumVO> dangerousNumVOS = tJobStatisticsController.foreignNum(param).getData();

        param.setFlag("1");

        List<HazardousOperation> hazardousOperation = tJobStatisticsDao.distributionSum(param);

        Map<String, List<HazardousOperation>> hazardousOperationMap = hazardousOperation.stream().collect(Collectors.groupingBy(HazardousOperation::getOrgId));

        for (DangerousNumVO dangerousNumVO : dangerousNumVOS) {
            FieldStatisticsFormVO fieldStatisticsFormVO = new FieldStatisticsFormVO();
            fieldStatisticsFormVO.setHazardousOperation(hazardousOperationMap.get(dangerousNumVO.getOrgId()).get(0));
            fieldStatisticsFormVO.setRelevantUnits(dangerousNumVO.getNum());
            fieldStatisticsFormVO.setUnitName(dangerousNumVO.getName());
            fieldStatisticsFormVO.setHazardousOperations(wxzyMap.get(dangerousNumVO.getOrgId()).get(0).getNum());
            fieldStatisticsFormVOS.add(fieldStatisticsFormVO);
        }
        return fieldStatisticsFormVOS;
    }

    @Override
    public List<FieldStatisticsFormVO> fieldStatisticsFormRegionalCorporateRentalLibrary(TJobStatisticsParam param) {

        ArrayList<FieldStatisticsFormVO> fieldStatisticsFormVOS = new ArrayList<>();
        param.setAdd(false);
        //危险作业次数
        Map<String, List<DangerousNumVO>> wxzyMap = tJobStatisticsController.dangerousNum(param).getData().stream().collect(Collectors.groupingBy(DangerousNumVO::getOrgId));

        //外来作业相关方人次数量
        List<DangerousNumVO> dangerousNumVOS = tJobStatisticsController.foreignNum(param).getData();

        param.setFlag("1");

        List<HazardousOperation> hazardousOperation = tJobStatisticsDao.distributionRegionalCompaniesRentStorage(param);

        Map<String, List<HazardousOperation>> hazardousOperationMap = hazardousOperation.stream().collect(Collectors.groupingBy(HazardousOperation::getOrgId));

        for (DangerousNumVO dangerousNumVO : dangerousNumVOS) {
            FieldStatisticsFormVO fieldStatisticsFormVO = new FieldStatisticsFormVO();
            fieldStatisticsFormVO.setHazardousOperation(hazardousOperationMap.get(dangerousNumVO.getOrgId()).get(0));
            fieldStatisticsFormVO.setRelevantUnits(dangerousNumVO.getNum());
            fieldStatisticsFormVO.setUnitName(dangerousNumVO.getName());
            fieldStatisticsFormVO.setHazardousOperations(wxzyMap.get(dangerousNumVO.getOrgId()).get(0).getNum());
            fieldStatisticsFormVOS.add(fieldStatisticsFormVO);
        }
        return fieldStatisticsFormVOS;
    }

    @Override
    public List<FieldStatisticsFormVO> fieldStatisticsFormGrainDepot(TJobStatisticsParam param) {

        ArrayList<FieldStatisticsFormVO> fieldStatisticsFormVOS = new ArrayList<>();
        param.setAdd(false);
        //危险作业次数
        Map<String, List<DangerousNumVO>> wxzyMap = tJobStatisticsController.dangerousNum(param).getData().stream().collect(Collectors.groupingBy(DangerousNumVO::getOrgId));

        //外来作业相关方人次数量
        List<DangerousNumVO> dangerousNumVOS = tJobStatisticsController.foreignNum(param).getData();

        param.setFlag("1");

        List<HazardousOperation> hazardousOperation = tJobStatisticsDao.distributionRegionalCompanyGrainDepot(param);

        Map<String, List<HazardousOperation>> hazardousOperationMap = hazardousOperation.stream().collect(Collectors.groupingBy(HazardousOperation::getOrgId));

        for (DangerousNumVO dangerousNumVO : dangerousNumVOS) {
            FieldStatisticsFormVO fieldStatisticsFormVO = new FieldStatisticsFormVO();
            fieldStatisticsFormVO.setHazardousOperation(hazardousOperationMap.get(dangerousNumVO.getOrgId()).get(0));
            fieldStatisticsFormVO.setRelevantUnits(dangerousNumVO.getNum());
            fieldStatisticsFormVO.setUnitName(dangerousNumVO.getName());
            fieldStatisticsFormVO.setHazardousOperations(wxzyMap.get(dangerousNumVO.getOrgId()).get(0).getNum());
            fieldStatisticsFormVOS.add(fieldStatisticsFormVO);
        }
        return fieldStatisticsFormVOS;

    }

    @Override
    public List<FieldStatisticsFormVO> fieldStatisticsFormSingle(TJobStatisticsParam param) {

        ArrayList<FieldStatisticsFormVO> fieldStatisticsFormVOS = new ArrayList<>();
        param.setAdd(false);
        //危险作业次数
        Map<String, List<DangerousNumVO>> wxzyMap = tJobStatisticsController.dangerousNum(param).getData().stream().collect(Collectors.groupingBy(DangerousNumVO::getOrgId));

        //外来作业相关方人次数量
        List<DangerousNumVO> dangerousNumVOS = tJobStatisticsController.foreignNum(param).getData();

        param.setFlag("1");

        List<HazardousOperation> hazardousOperation = tJobStatisticsDao.distributionGrainDepot(param);

        Map<String, List<HazardousOperation>> hazardousOperationMap = hazardousOperation.stream().collect(Collectors.groupingBy(HazardousOperation::getOrgId));

        for (DangerousNumVO dangerousNumVO : dangerousNumVOS) {
            FieldStatisticsFormVO fieldStatisticsFormVO = new FieldStatisticsFormVO();
            fieldStatisticsFormVO.setHazardousOperation(hazardousOperationMap.get(dangerousNumVO.getOrgId()).get(0));
            fieldStatisticsFormVO.setRelevantUnits(dangerousNumVO.getNum());
            fieldStatisticsFormVO.setUnitName(dangerousNumVO.getName());
            fieldStatisticsFormVO.setHazardousOperations(wxzyMap.get(dangerousNumVO.getOrgId()).get(0).getNum());
            fieldStatisticsFormVOS.add(fieldStatisticsFormVO);
        }
        return fieldStatisticsFormVOS;
    }

    @Override
    public HazardousWorkStatisticsVo regionalStatistics(String orgId) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }
        HazardousWorkStatisticsVo hazardousWorkStatisticsVo = new HazardousWorkStatisticsVo();
        List<RegionalStatisticsVO> regionalStatisticsVOList = new ArrayList<>();
        TJobStatisticsParam tJobStatisticsParam = new TJobStatisticsParam();
        tJobStatisticsParam.setOrgId(orgId);
        String today = DateUtil.today();
        tJobStatisticsParam.setZykssj(today);
        List<String> orgIds = newSysOrgService.getOrgIdListByParentId(orgId);
        //如果没有下级查看当前单位数据
        if (orgIds == null || orgIds.isEmpty()) {
            regionalStatisticsVOList = hazardWorkPlanDao.selectWorkTypeCount(tJobStatisticsParam);
            hazardousWorkStatisticsVo.setCount(regionalStatisticsVOList.size());
        }else {
            tJobStatisticsParam.setOrgId("");
            for (String id : orgIds) {
                List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(id);
                tJobStatisticsParam.setOrgIds(idsChildrenById);
                RegionalStatisticsVO regionalStatisticsVO = new RegionalStatisticsVO();
                regionalStatisticsVO.setId(id);
                SysOrg org = sysOrgService.getById(id);
                if(null != org){
                    regionalStatisticsVO.setName(org.getOrgName());
                }
                List<RegionalStatisticsVO> regionalStatisticsVOS = hazardWorkPlanDao.selectOrgWorkPlanCount(tJobStatisticsParam);
                if(null != regionalStatisticsVOS && !regionalStatisticsVOS.isEmpty()){
                    regionalStatisticsVO.setDone(regionalStatisticsVOS.get(0).getDone());
                    regionalStatisticsVO.setUndone(regionalStatisticsVOS.get(0).getUndone());
                }else{
                    regionalStatisticsVO.setDone("0");
                    regionalStatisticsVO.setUndone("0");
                }
                regionalStatisticsVOList.add(regionalStatisticsVO);
            }

            // 计算所有组织的已完成和未完成作业总数
            int totalDone = 0;
            int totalUndone = 0;

            for (RegionalStatisticsVO vo : regionalStatisticsVOList) {
                // 将字符串转换为整数，处理可能的空值或非数字情况
                try {
                    totalDone += Integer.parseInt(vo.getDone());
                } catch (NumberFormatException e) {
                    // 如果转换失败，则默认为0
                }

                try {
                    totalUndone += Integer.parseInt(vo.getUndone());
                } catch (NumberFormatException e) {
                    // 如果转换失败，则默认为0
                }
            }

            int totalCount = totalDone + totalUndone;
            hazardousWorkStatisticsVo.setCount(totalCount);
        }

        hazardousWorkStatisticsVo.setRegionalStatistics(regionalStatisticsVOList);
        return hazardousWorkStatisticsVo;
    }
    /*public HazardousWorkStatisticsVo regionalStatistics(String orgId) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }
        HazardousWorkStatisticsVo hazardousWorkStatisticsVo = new HazardousWorkStatisticsVo();
        List<RegionalStatisticsVO> regionalStatisticsVOList = new ArrayList<>();
        TJobStatisticsParam tJobStatisticsParam = new TJobStatisticsParam();
        tJobStatisticsParam.setOrgId(orgId);
        String today = DateUtil.today();
        tJobStatisticsParam.setZykssj(today);
        List<String> orgIds = newSysOrgService.getOrgIdListByParentId(orgId);
        Integer count = 0;
        //如果没有下级查看当前单位数据
        if (orgIds == null || orgIds.isEmpty()) {
            regionalStatisticsVOList = tJobStatisticsDao.regionalStatisticsGrain(tJobStatisticsParam);
            count = regionalStatisticsVOList.size();
        }else {
            for (String id : orgIds) {
                List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(id);
                RegionalStatisticsVO regionalStatisticsVO = tJobStatisticsDao.selectCountBatch(idsChildrenById, today);
                // 获取已关闭和进行中的统计数据
                Integer completedCount = Integer.valueOf(regionalStatisticsVO.getDone());
                Integer ongoing = Integer.valueOf(regionalStatisticsVO.getUndone());
                NewSysOrg byId = newSysOrgService.getById(id);
                regionalStatisticsVO.setName(byId.getOrgName());
                regionalStatisticsVOList.add(regionalStatisticsVO);
                count += completedCount + ongoing;
            }
        }
        hazardousWorkStatisticsVo.setRegionalStatistics(regionalStatisticsVOList);
        hazardousWorkStatisticsVo.setCount(count);
        return hazardousWorkStatisticsVo;
    }*/

    @Override
    public Long regionalStatisticsCount(String orgId) {
        UserInfo loginUser = ContextUtils.getLoginUser();
        if (StringHelper.isEmpty(orgId)) {
            orgId = loginUser.getOrgId();
        }
        NewSysOrg sysOrg = newSysOrgService.getOne(new LambdaQueryWrapper<NewSysOrg>().eq(NewSysOrg::getOrgId, orgId));
        TJobStatisticsParam tJobStatisticsParam = new TJobStatisticsParam();
        tJobStatisticsParam.setOrgId(orgId);
        String today = DateUtil.today();
        tJobStatisticsParam.setZykssj(today);
        Long regionalStatisticsVOList = 0L;
        String nature = sysOrg.getNature();
        if (StringUtils.isBlank(nature)){
            nature = sysOrg.getTreeLevel().toString();
        }
        int treeLevel = Integer.parseInt(nature);
        //总部
        if (treeLevel == 1) {
            regionalStatisticsVOList = tJobStatisticsDao.regionalStatisticsCount(tJobStatisticsParam);
        }
        //区域
        if (treeLevel == 2 || treeLevel == 3) {
            regionalStatisticsVOList = tJobStatisticsDao.regionalStatisticsCount(tJobStatisticsParam);
        }
        //粮库
        if (treeLevel == 4) {
            regionalStatisticsVOList = tJobStatisticsDao.regionalStatisticsCountGrain(tJobStatisticsParam);
        }
        return regionalStatisticsVOList;
    }
}
