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.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
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;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 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;
        IESignGlobalStatusOverview overview = ESignGlobalStatusOverviewFactory.getLocalInstance(context);
        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);
//        List<String> list = Lists.newArrayList();
//        list.add("2");
//        jsonMap.put("signFlowStatus", list);
        do {
            pageNum++;
            jsonMap.put("pageNum", pageNum);
            jsonMap.put("pageSize", pageSize);
            try {
                EsignHttpResponse response = EsignHttpUtil.sign_flow_list(context, jsonMap, "查询签署流程列表");
                if (response.getStatus() >= 200 && response.getStatus() < 300) {
                    if (StringUtils.isBlank(response.getBody())) {
                        continue;
                    }
                    //System.out.println(response.getBody());
                    JSONObject jsonObject = JSON.parseObject(response.getBody());
                    int code = jsonObject.getInteger("code");
                    if (0 != code) {
                        continue;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (null == data) {
                        continue;
                    }
                    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 signFlowTitle = signFlowInfo.getString("signFlowTitle");

                        String sel = "select fid from CT_ESI_ESGSO where CFSignFlowId ='" + signFlowId + "'";
                        IRowSet rowSet = DbUtil.executeQuery(context, sel);
                        if (rowSet.next()) {
                            String id = rowSet.getString("fid");
                            updateSignFlow(context, overview, signFlowId, id);
                        } else {
                            if (signFlowTitle.indexOf("人资") < 0 && signFlowTitle.indexOf("人力资源") < 0) {
                                continue;
                            }
                            addNewSignFlow(context, overview, signFlowInfo, signFlowId, signFlowTitle);
                        }
                    }
                }
            } catch (EsignException | SQLException e) {
                e.printStackTrace();
            }
        } while (pageNum < totalNum);

        return "ok";
    }

    private boolean updateSignFlow(Context context, IESignGlobalStatusOverview overview, String signFlowId, String id) throws BOSException, EASBizException, EsignException, SQLException {
        ESignGlobalStatusOverviewInfo oldInfo = overview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(id));
        EsignHttpResponse respsf = EsignHttpUtil.getSign_fields(context, signFlowId, "查询签署流程详情");
        if (respsf.getStatus() < 200 || respsf.getStatus() >= 300) {
            return true;
        }
        if (StringUtils.isBlank(respsf.getBody())) {
            return true;
        }
        JSONObject jsonObjsf = JSON.parseObject(respsf.getBody());
        int codesf = jsonObjsf.getInteger("code");
        if (0 != codesf) {
            return true;
        }
        JSONObject datasf = jsonObjsf.getJSONObject("data");
        if (null == datasf) {
            return true;
        }
        Integer signFlowStatus = datasf.getInteger("signFlowStatus");
        String statusDescription = datasf.getString("statusDescription");
        //签署中
        if (null != signFlowStatus && 1 == signFlowStatus) {
            JSONArray signers = datasf.getJSONArray("signers");
            StringBuilder signNames = new StringBuilder();
            for (int j = 0; j < signers.size(); j++) {
                JSONObject signer = signers.getJSONObject(j);
                JSONObject psnSigner = signer.getJSONObject("psnSigner");
                JSONObject orgSigner = signer.getJSONObject("orgSigner");
                JSONArray signFields = signer.getJSONArray("signFields");
                boolean signFieldBool=false;
                for (int x = 0; x < signFields.size(); x++) {
                    JSONObject sign = signFields.getJSONObject(x);
                    Integer signFieldStatus = Integer.parseInt(sign.getString("signFieldStatus"));
                    //这三种情况的话说明是当前这个签署区所属的签署人在签署：1 - 执行中、2 - 执行失败、3 - 审批中
                    if (signFieldStatus > 0 && signFieldStatus < 4) {
                        signFieldBool=true;
                    }
                }
                oldInfo.setEsignStatus(EsignStatusEnum.getEnum(signFlowStatus));
                //oldInfo.setDescription(statusDescription);
                oldInfo.setNowOperator("");
                if (signFieldBool) {
                    signNames = getPsnName(context, signNames, psnSigner);
                    signNames = getOrgName(context, signNames, orgSigner);
                }
            }
            if(signNames.indexOf(",") == 0) {
                signNames.delete(0,1);
            }
            if (signNames.length() > 500) {
                oldInfo.setNowOperator(signNames.substring(0, 500));
            } else {
                oldInfo.setNowOperator(signNames.toString());
            }
        } else {
            String signFlowDescription = datasf.getString("signFlowDescription");
            String revokeReason = datasf.getString("revokeReason");
            oldInfo.setNowOperator("");
            oldInfo.setErrorMsg(signFlowDescription);
            oldInfo.setErrorMsg(revokeReason);
        }
        overview.save(oldInfo);
        return false;
    }

    private StringBuilder getOrgName(Context context, StringBuilder signNames, JSONObject orgSigner) throws BOSException, SQLException {
        if (null == orgSigner) {
            return signNames;
        }
        String orgName = orgSigner.getString("orgName");
        JSONObject transactor = orgSigner.getJSONObject("transactor");
        if (null == transactor) {
            return signNames;
        }
        String psnName = transactor.getString("psnName");
        if (StringUtils.isNotBlank(psnName)) {
            signNames.append("," + orgName + "(" + psnName + ")");
            return signNames;
        }
        JSONObject psnAccount = transactor.getJSONObject("psnAccount");
        if (null == psnAccount) {
            return signNames;
        }
        String accountMobile = psnAccount.getString("accountMobile");
        String accountEmail = psnAccount.getString("accountEmail");
        if (StringUtils.isNotBlank(accountMobile)) {
            String selp = "select fid,fname_l2,fnumber from t_bd_person where FNCELL='" + accountMobile + "'";
            IRowSet rs = DbUtil.executeQuery(context, selp);
            if (rs.next()) {
                String fid = rs.getString("fid");
                String fname_l2 = rs.getString("fname_l2");
                String fnumber = rs.getString("fnumber");
                signNames.append("," + orgName + "(" + fname_l2 + ")");
                return signNames;
            }
        }
        if (StringUtils.isNotBlank(accountEmail)) {
            String selp = "select fid,fname_l2,fnumber from t_bd_person where FEMail='" + accountEmail + "'";
            IRowSet rs = DbUtil.executeQuery(context, selp);
            if (rs.next()) {
                String fid = rs.getString("fid");
                String fname_l2 = rs.getString("fname_l2");
                String fnumber = rs.getString("fnumber");
                signNames.append("," + orgName + "(" + fname_l2 + ")");
                return signNames;
            }
        }

        return signNames;
    }

    private StringBuilder getPsnName(Context context, StringBuilder signNames, JSONObject psnSigner) throws BOSException, SQLException {
        if (null == psnSigner) {
            return signNames;
        }
        String psnName = psnSigner.getString("psnName");
        if (StringUtils.isNotBlank(psnName)) {
            signNames.append("," + psnName);
            return signNames;
        }
        JSONObject psnAccount = psnSigner.getJSONObject("psnAccount");
        if (null == psnAccount) {
            return signNames;
        }
        String accountMobile = psnAccount.getString("accountMobile");
        String accountEmail = psnAccount.getString("accountEmail");
        if (StringUtils.isNotBlank(accountMobile)) {
            String selp = "select fid,fname_l2,fnumber from t_bd_person where FNCELL='" + accountMobile + "'";
            IRowSet rs = DbUtil.executeQuery(context, selp);
            if (rs.next()) {
                String fid = rs.getString("fid");
                String fname_l2 = rs.getString("fname_l2");
                String fnumber = rs.getString("fnumber");
                signNames.append("," + fname_l2);
                return signNames;
            }
        }
        if (StringUtils.isNotBlank(accountEmail)) {
            String selp = "select fid,fname_l2,fnumber from t_bd_person where FEMail='" + accountEmail + "'";
            IRowSet rs = DbUtil.executeQuery(context, selp);
            if (rs.next()) {
                String fid = rs.getString("fid");
                String fname_l2 = rs.getString("fname_l2");
                String fnumber = rs.getString("fnumber");
                signNames.append("," + fname_l2);
                return signNames;
            }
        }

        return signNames;
    }

    private void addNewSignFlow(Context context, IESignGlobalStatusOverview overview, JSONObject signFlowInfo, String signFlowId, String signFlowTitle) throws BOSException, SQLException, EASBizException {
        ESignGlobalStatusOverviewInfo nowInfo = new ESignGlobalStatusOverviewInfo();
        nowInfo.setSignFlowId(signFlowId);
        nowInfo.setFileName(signFlowTitle);
        nowInfo.setEsignStatus(EsignStatusEnum.COMPLETED);
        nowInfo.setEsignName(EsignConfigEnum.sign_flow_list);
        nowInfo.setRequestParams(signFlowInfo.toJSONString());
        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);
            ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
            scheduledThreadPoolExecutor.schedule(() -> {
                try {
                    this.updateSignFlow(context, overview, signFlowId, nowInfo.getId().toString());
                    SyncSignedFilesUtil.syncAttachmentsForEmpPage(context, nowInfo.getId().toString());
                } catch (BOSException e) {
                    e.printStackTrace();
                } catch (EASBizException e) {
                    e.printStackTrace();
                } catch (EsignException e) {
                    e.printStackTrace();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }, 1, TimeUnit.MINUTES);
        //}
    }


    public static void main(String[] args) throws EsignException {
        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 = formatter("2026-02-01");;
//        }
//        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("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);
//        System.out.println(12 + (3 - 1) / 2 * 1);
//        EsignHttpResponse r = EsignHttpUtil.getSign_fields(null,"d4d12e6ed7374775a9dcb4747e1e5e59");
//        System.out.println(r.getBody());
        FilterInfo filterInfo2 = new FilterInfo();
        FilterItemInfo f = new FilterItemInfo();
        f.setPropertyName("isnull(t.fid,'2199-12-30')");
        f.setCompareValue("1");
        f.setCompareType(CompareType.EQUALS);
        filterInfo2.getFilterItems().add(f);
        System.out.println(filterInfo2.toSql());
    }
}
