package com.kingdee.eas.custom.esign.osf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.rabbitmq.guava.Lists;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewCollection;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewFactory;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewInfo;
import com.kingdee.eas.custom.esign.IESignGlobalStatusOverview;
import com.kingdee.eas.custom.esign.bizEnum.EsignConfigEnum;
import com.kingdee.eas.custom.esign.bizEnum.EsignStatusEnum;
import com.kingdee.eas.custom.esign.bizEnum.SendStatusEnum;
import com.kingdee.eas.custom.esign.tsign.hz.comm.EsignHttpResponse;
import com.kingdee.eas.custom.esign.tsign.hz.exception.EsignException;
import com.kingdee.eas.custom.esign.util.EsignHttpUtil;
import com.kingdee.eas.custom.esign.util.SyncSignedFilesUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 *
 * description: EsignFlowListOSFService <br>
 * date: 4/1/2026 下午 4:23 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class EsignFlowListOSFService implements IHRMsfService {

    public static LocalDateTime formatter(String time) {
        LocalDateTime dateTime = null;
        if (time.length() == 10) {
            LocalDate localD = LocalDate.parse(time);
            LocalTime localT = LocalTime.of(0, 0, 0);
            dateTime = LocalDateTime.of(localD, localT);
        } else if (time.length() == 16) {
            dateTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } else if (time.length() == 19) {
            dateTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        return dateTime;
    }

    public static LocalDateTime startDateTimeNow() {
        LocalDate localD1 = LocalDate.now();
        LocalTime time1 = LocalTime.now();
        LocalTime localT1 = LocalTime.of(time1.getHour(), 0, 0);
        LocalDateTime dateTime = LocalDateTime.of(localD1, localT1);
        dateTime=dateTime.minusHours(1);
        return dateTime;
    }

    public static LocalDateTime endDateTimeNow() {
        LocalDate localD2 = LocalDate.now();
        LocalTime localT2 = LocalTime.of(23, 59, 59);
        LocalDateTime dateTime = LocalDateTime.of(localD2, localT2);
        return dateTime;
    }

    @Override
    public Object process(Context context, Map<String, Object> map) throws EASBizException, BOSException {
        String param = (String) map.get("data");
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        StringBuilder msg = new StringBuilder();
        if (StringUtils.isNotBlank(param)) {
            JSONObject object = JSON.parseObject(param);
            String startTime = object.getString("startTime");
            String endTime = object.getString("endTime");
            String status = object.getString("status");
            String advanceHours = object.getString("advanceHours");

            if (StringUtils.isNotBlank(startTime)
                    &&
                    StringUtils.isNotBlank(endTime)
            ) {
                startDateTime = this.formatter(startTime);
                endDateTime = this.formatter(endTime);
            }
            if (null == startDateTime || null == endDateTime) {
                startDateTime = startDateTimeNow();
                endDateTime = endDateTimeNow();
            }
            startDateTime = startDateTime.minusHours(Integer.parseInt(advanceHours));
        }
        if (null == startDateTime || null == endDateTime) {
            startDateTime = startDateTimeNow();
            endDateTime = endDateTimeNow();
        }
        int pageNum=0;
        int pageSize=100;
        long totalNum=1;
        do {
            pageNum++;
            Map<String, Object> jsonMap = Maps.newHashMap();
            long signFlowStartTimeFrom = startDateTime.atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
            long signFlowStartTimeTo = endDateTime.atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
            jsonMap.put("signFlowStartTimeFrom", signFlowStartTimeFrom);
            jsonMap.put("signFlowStartTimeTo", signFlowStartTimeTo);
            jsonMap.put("pageNum", pageNum);
            jsonMap.put("pageSize", pageSize);
            List<String> list = Lists.newArrayList();
            list.add("2");
            jsonMap.put("signFlowStatus", list);
            try {
                IESignGlobalStatusOverview overview = ESignGlobalStatusOverviewFactory.getLocalInstance(context);
                EsignHttpResponse response = EsignHttpUtil.sign_flow_list(context, jsonMap, "查询签署流程列表");
                JSONObject jsonObject = JSON.parseObject(response.getBody());
                int code =jsonObject.getInteger("code");
                if (0==code){
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (null!=data){
                        long total = data.getLong("total");
                        if(total%pageSize==0){
                            totalNum=total/pageSize;
                        }else {
                            totalNum=total/pageSize+1;
                        }
                        JSONArray signFlowInfos = data.getJSONArray("signFlowInfos");
                        for (int i=0;i<signFlowInfos.size();i++){
                            JSONObject signFlowInfo = signFlowInfos.getJSONObject(i);
                            String signFlowId = signFlowInfo.getString("signFlowId");
                            String sel = "select fid from CT_ESI_ESGSO where CFSignFlowId ='"+signFlowId+"'";
                            IRowSet rowSet = DbUtil.executeQuery(context,sel);
                            if(rowSet.size()<=0){
                                ESignGlobalStatusOverviewInfo nowInfo = new ESignGlobalStatusOverviewInfo();
                                nowInfo.setSignFlowId(signFlowId);
                                nowInfo.setEsignStatus(EsignStatusEnum.COMPLETED);
                                nowInfo.setEsignName(EsignConfigEnum.sign_flow_list);
                                nowInfo.setRequestParams(response.getBody());
                                nowInfo.setFiesign(true);
                                nowInfo.setSendStatus(SendStatusEnum.SUCCESS);
                                JSONArray signers = signFlowInfo.getJSONArray("signers");
                                for(int x=0;x<signers.size();x++) {
                                    JSONObject signer = signers.getJSONObject(x);
                                    JSONObject psnSigner=signer.getJSONObject("psnSigner");
                                    if (null==psnSigner){
                                        continue;
                                    }
                                    JSONObject psnAccount=psnSigner.getJSONObject("psnAccount");
                                    String accountMobile = psnAccount.getString("accountMobile");
                                    String accountEmail = psnAccount.getString("accountEmail");
                                    if(StringUtils.isNotBlank(accountMobile)){
                                        String selp = "select fid from t_bd_person where FNCELL='"+accountMobile+"'";
                                        IRowSet rs = DbUtil.executeQuery(context,selp);
                                        if (rs.next()){
                                            String fid = rs.getString("fid");
                                            PersonInfo personInfo = new PersonInfo();
                                            personInfo.setId(BOSUuid.read(fid));
                                            nowInfo.setPerson(personInfo);
                                        }
                                    }else {
                                        String selp = "select fid from t_bd_person where FEMail='"+accountEmail+"'";
                                        IRowSet rs = DbUtil.executeQuery(context,selp);
                                        if (rs.next()){
                                            String fid = rs.getString("fid");
                                            PersonInfo personInfo = new PersonInfo();
                                            personInfo.setId(BOSUuid.read(fid));
                                            nowInfo.setPerson(personInfo);
                                        }
                                    }
                                }
                                if(null!=nowInfo.getPerson()) {
                                    IObjectPK pk = overview.addnew(nowInfo);
                                    SyncSignedFilesUtil.syncAttachmentsForEmpPage(context,pk.toString());
                                }
                            }
                        }
                    }
                }
            } catch (EsignException | SQLException e) {
                e.printStackTrace();
            }
        } while (pageNum<totalNum);
        return "ok";
    }

    public static void main(String[] args) {
        System.setProperty("EAS_HOME","D:\\project\\kingdeeV90\\Project_hty\\tengda");
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (null == startDateTime || null == endDateTime) {
            startDateTime = formatter("2025-02-01");;
            endDateTime = endDateTimeNow();
        }
        int pageNum=0;
        int pageSize=20;
        long totalNum=1;
        do {
            pageNum++;
            Map<String, Object> jsonMap = Maps.newHashMap();
            long signFlowStartTimeFrom = startDateTime.atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
            long signFlowStartTimeTo = endDateTime.atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli();
            jsonMap.put("signFlowStartTimeFrom", signFlowStartTimeFrom);
            jsonMap.put("signFlowStartTimeTo", signFlowStartTimeTo);
            jsonMap.put("pageNum", pageNum);
            jsonMap.put("pageSize", pageSize);
            List<String> list = Lists.newArrayList();
            //list.add("1");
            list.add("2");
            //list.add("3");
            jsonMap.put("signFlowStatus", list);
            try {
                EsignHttpResponse response = EsignHttpUtil.sign_flow_list(null, jsonMap, "查询签署流程列表");
                System.out.println(response.getBody());
                JSONObject jsonObject = JSON.parseObject(response.getBody());
                int code =jsonObject.getInteger("code");
                if (0==code){
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (null!=data){
                        JSONArray signFlowInfos = data.getJSONArray("signFlowInfos");
                        System.out.println(signFlowInfos.size());
                        long total = data.getLong("total");
                        if(total%pageSize==0){
                            totalNum=total/pageSize;
                        }else {
                            totalNum=total/pageSize+1;
                        }
                    }
                }
            } catch (EsignException e) {
                e.printStackTrace();
            }
        } while (pageNum<totalNum);
    }
}
