package com.hz.pm.api.scheduler.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ningdatech.basic.model.GenericResult;
import com.hz.pm.api.common.model.constant.BizConst;
import com.hz.pm.api.ding.constants.DingOrganizationContant;
import com.hz.pm.api.irs.manage.ProjectIrsManage;
import com.hz.pm.api.irs.model.entity.ProjectCoreBiz;
import com.hz.pm.api.irs.service.IProjectCoreBizService;
import com.hz.pm.api.organization.model.entity.DingOrganization;
import com.hz.pm.api.organization.service.IDingOrganizationService;
import com.hz.pm.api.projectdeclared.contants.ProjectCodeContant;
import com.ningdatech.zwdd.client.ZwddClient;
import com.ningdatech.zwdd.model.dto.DingOrgInfoDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ZPF
 * @since 2023/09/13 18:16
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class SynProjectCoreBizTask {

    @Value("${hostname}")
    public String HOST;

    @Value("${spring.profiles.active}")
    public String active;

    @Autowired
    private IProjectCoreBizService projectCoreBizService;

    @Autowired
    private IDingOrganizationService organizationService;

    @Autowired
    private ZwddClient zwddClient;

    @Autowired
    private ProjectIrsManage projectIrsManage;

    private final Integer MAX_PAGE_SIZE = 1000;

    /**
     * 前置机每天晚上10点自动清空，第二天早上6点获取数据
     * 定时同步前置机数据 每天1点开始执行一次 不按照单位
     *
     */
//    @Scheduled(cron = "0 0 2 * * ?")
    public void doTask() throws UnknownHostException {
        if (!HOST.equals(InetAddress.getLocalHost().getHostName())) {
            log.info("定时器没开启或者host不对! {}:{}",
                    HOST,InetAddress.getLocalHost().getHostName());
            return;
        }

        log.info("同步项目核心业务开始=====");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        List<DingOrganization> orgs = organizationService.list(Wrappers.lambdaQuery(DingOrganization.class)
                .in(DingOrganization::getTypeCode, Lists.newArrayList(DingOrganizationContant.UNIT_TYPE
                        , DingOrganizationContant.GOV_TEMPORARY)));

        log.info("总共需要同步 orgs size ：{}",orgs.size());

        syncCoreBiz(orgs);
        stopWatch.stop();
        log.info("同步项目核心业务结束====={}s",stopWatch.getTotalTimeSeconds());
    }

    public void doTask(String orgCode) throws UnknownHostException {
        log.info("同步项目核心业务开始=====");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        List<DingOrganization> orgs = organizationService.list(Wrappers.lambdaQuery(DingOrganization.class)
                .in(DingOrganization::getTypeCode, Lists.newArrayList(DingOrganizationContant.UNIT_TYPE
                        , DingOrganizationContant.GOV_TEMPORARY))
                .eq(StringUtils.isNotBlank(orgCode),DingOrganization::getOrganizationCode,orgCode));

        log.info("总共需要同步 orgs size ：{}",orgs.size());

        syncCoreBiz(orgs);

        stopWatch.stop();
        log.info("同步项目核心业务结束====={}s",stopWatch.getTotalTimeSeconds());
    }

    private void syncCoreBiz(List<DingOrganization> orgs) {
        for(DingOrganization organization : orgs){
            GenericResult<DingOrgInfoDTO> dingResult = zwddClient.getOrganizationByCode(organization.getOrganizationCode());

            log.info("core biz result : {}",JSON.toJSONString(dingResult));

            if(dingResult.isSuccess()){
                DingOrgInfoDTO data = dingResult.getData();
                String unifiedSocialCreditCode = data.getUnifiedSocialCreditCode();
                if(StringUtils.isNotBlank(unifiedSocialCreditCode)){
                    organization.setUnifiedSocialCreditCode(unifiedSocialCreditCode);
                    organizationService.updateById(organization);
                }

                //去请求IRS接口
                JSONObject jsonObject = projectIrsManage.searchCoreBiz(null, organization.getOrganizationCode(), 1000, 1);

                JSONArray jsonArray = jsonObject.getJSONArray(BizConst.RESPONSE_KEY_DATA);
                if(CollUtil.isNotEmpty(jsonArray)){
                    jsonArray.forEach(j -> {
                        JSONObject jsonData = JSON.parseObject(JSON.toJSONString(j));
                        ProjectCoreBiz coreBiz = new ProjectCoreBiz();
                        //
                        Long irsId = jsonData.getLong(BizConst.RESPONSE_KEY_ID);
                        String dingCode = jsonData.getString(BizConst.RESPONSE_KEY_DING_CODE);
                        String matterName = jsonData.getString(BizConst.RESPONSE_KEY_MATTER_NAME);
                        String orgName = jsonData.getString(BizConst.RESPONSE_KEY_ORG_NAME);
                        String userState = jsonData.getString(BizConst.RESPONSE_KEY_USER_STATE);
                        String areaName = jsonData.getString(BizConst.RESPONSE_KEY_AREA_NAME);
                        ProjectCoreBiz old = projectCoreBizService.getOne(Wrappers.lambdaQuery(ProjectCoreBiz.class)
                                .eq(ProjectCoreBiz::getIrsId, irsId)
                                .last(BizConst.LIMIT_1));

                        if(Objects.nonNull(old)){
                            coreBiz.setId(old.getId());
                        }else{
                            coreBiz.setCreateOn(LocalDateTime.now());
                        }
                        coreBiz.setUpdateOn(LocalDateTime.now());
                        coreBiz.setIrsId(irsId);
                        coreBiz.setMatterName(matterName);
                        coreBiz.setOrgCode(dingCode);
                        coreBiz.setOrgName(orgName);
                        coreBiz.setUserState(userState);
                        coreBiz.setAreaName(areaName);
                        coreBiz.setMatterCode(irsId.toString());
                        projectCoreBizService.saveOrUpdate(coreBiz);
                        coreBiz.setMatterCode(genirate(unifiedSocialCreditCode,coreBiz.getId()));
                        projectCoreBizService.updateById(coreBiz);
                    });
                }
            }
        }
    }

    private void syncCoreBiz() {
        Map<String,DingOrganization> map = organizationService.list().stream().distinct().collect(Collectors.toMap(DingOrganization::getOrganizationCode, o -> o));

        Integer currentSize = MAX_PAGE_SIZE;
        Integer page = 1;
        while (currentSize.equals(MAX_PAGE_SIZE)) {
            //去请求IRS接口
            JSONObject jsonObject = projectIrsManage.searchCoreBiz(null, null, MAX_PAGE_SIZE, page);

            JSONArray jsonArray = jsonObject.getJSONArray(BizConst.RESPONSE_KEY_DATA);

            if(Objects.isNull(jsonArray)){
                return;
            }

            currentSize = jsonArray.size();
            if (CollUtil.isNotEmpty(jsonArray)) {
                if (currentSize.equals(MAX_PAGE_SIZE)) {
                    page++;
                }
                jsonArray.forEach(j -> {
                    JSONObject jsonData = JSON.parseObject(JSON.toJSONString(j));
                    ProjectCoreBiz coreBiz = new ProjectCoreBiz();
                    //
                    Long irsId = jsonData.getLong(BizConst.RESPONSE_KEY_ID);
                    String dingCode = jsonData.getString(BizConst.RESPONSE_KEY_DING_CODE);
                    String matterName = jsonData.getString(BizConst.RESPONSE_KEY_MATTER_NAME);
                    String orgName = jsonData.getString(BizConst.RESPONSE_KEY_ORG_NAME);
                    String userState = jsonData.getString(BizConst.RESPONSE_KEY_USER_STATE);
                    String areaName = jsonData.getString(BizConst.RESPONSE_KEY_AREA_NAME);
                    ProjectCoreBiz old = projectCoreBizService.getOne(Wrappers.lambdaQuery(ProjectCoreBiz.class)
                            .eq(ProjectCoreBiz::getIrsId, irsId)
                            .last(BizConst.LIMIT_1));

                    if (Objects.nonNull(old)) {
                        coreBiz.setId(old.getId());
                    } else {
                        coreBiz.setCreateOn(LocalDateTime.now());
                    }

                    if(map.containsKey(dingCode)){
                        DingOrganization organization = map.get(dingCode);

                        String unifiedSocialCreditCode = organization.getUnifiedSocialCreditCode();
                        if(StringUtils.isBlank(unifiedSocialCreditCode)){
                            GenericResult<DingOrgInfoDTO> dingResult = zwddClient.getOrganizationByCode(organization.getOrganizationCode());

                            log.info("ding org result : {}",JSON.toJSONString(dingResult));

                            if(dingResult.isSuccess()){
                                DingOrgInfoDTO data = dingResult.getData();
                                unifiedSocialCreditCode = data.getUnifiedSocialCreditCode();
                                organization.setUnifiedSocialCreditCode(unifiedSocialCreditCode);
                                organizationService.updateById(organization);
                            }
                        }

                        coreBiz.setUpdateOn(LocalDateTime.now());
                        coreBiz.setIrsId(irsId);
                        coreBiz.setMatterName(matterName);
                        coreBiz.setOrgCode(dingCode);
                        coreBiz.setOrgName(orgName);
                        coreBiz.setUserState(userState);
                        coreBiz.setAreaName(areaName);
                        coreBiz.setMatterCode(irsId.toString());
                        projectCoreBizService.saveOrUpdate(coreBiz);
                        coreBiz.setMatterCode(genirate(unifiedSocialCreditCode, coreBiz.getId()));
                        projectCoreBizService.updateById(coreBiz);
                    }
                });
            }
        }
    }

    /**
     * 生成 编号
     * @param unifiedSocialCreditCode
     * @param id
     * @return
     */
    private String genirate(String unifiedSocialCreditCode, Long id) {
        String formatId = String.format(ProjectCodeContant.SHUZI_4, id);
        return unifiedSocialCreditCode + formatId;
    }

}
