package com.weaver.seconddev.njwebservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.njwebservice.entity.DiscountApplicationReq;
import com.weaver.seconddev.njwebservice.entity.ResponseInfo;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author liang.cheng
 * @Date 2025/1/21 17:44
 * @Description: CW24-直贷业务申请流程（供应链金融系统触发）
 * @Version 1.0
 */

@Service("discountApplicationService")
public class DiscountApplicationService {

    private final static Logger log = LoggerFactory.getLogger(DiscountApplicationService.class);

    @Autowired
    private AutoCreateWorkflowService autoCreateWorkflowService;

    public ResponseInfo discountApplicate(DiscountApplicationReq param) {
        log.error("DiscountApplicationService:"+param.toString());
        String systemFlag = param.getSystemFlag();
        ResponseInfo res = new ResponseInfo();
        if(!"SCF".equals(systemFlag)){
            res.setISTAT("E");
            res.setRequestid("");
            res.setSRMSAGE("系统标识不符！");
            return res;
        }

        String creator = "";
        String companycode = param.getCompanyCode();
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
        rs.executeSql("select oafqrgh from uf_applyUser where companycode='"+companycode+"' and lclx=1", CONN_TYPE.ebuilder.getType());
        if(rs.next()){
            creator = Util.null2String(rs.getString("oafqrgh"));
        }
        log.error("申请人："+creator);

        if("".equals(creator)){
            res.setISTAT("E");
            res.setRequestid("");
            res.setSRMSAGE(param.getCompanyName()+"在OA系统里没有维护折现申请人");
            return res;
        }

        if(param.getCompanyName() != null && !"".equals(param.getCompanyName())){
            rs.executeSql("select id from eteams.dbo.department where type = 'subcompany' and name = '"+param.getCompanyName()+"'",CONN_TYPE.hrm.getType());
            if(!rs.next()){
                res.setISTAT("E");
                res.setRequestid("");
                res.setSRMSAGE("申请公司在OA系统中不存在！");
                return res;
            }
        }

        if(param.getDiscountNo() != null && !"".equals(param.getDiscountNo())){
            rs.executeSql("select discountNo from e10_core_business.dbo.formtable_main_2302 where discountNo='"+param.getDiscountNo()+"'",CONN_TYPE.workflow.getType());
            if(rs.next()){
                res.setISTAT("E");
                res.setRequestid("");
                res.setSRMSAGE("申请单号已存在，请不要重复申请！");
                return res;
            }
        }

        String loginname = "SCF";
        String password = "123456";
        String workflowId = "4206";
        String requestLevel = "0";

        Map<String,String> map = new HashMap<>();
        map.put("hrm:sqr", creator);
        map.put("com:sqr:sqdw", "");
        map.put("dep:sqr:sqbm", "");
        map.put("discountNo", param.getDiscountNo());
        map.put("companyName", param.getCompanyName());
        map.put("companyCode", param.getCompanyCode());
        map.put("vendorName", param.getVendorName());
        map.put("vendorCode", param.getVendorCode());
        map.put("applyDate", param.getApplyDate());
        map.put("amount", param.getAmount());
        map.put("rate", param.getRate());
        map.put("remarks", param.getRemarks());
//        map.put("busType",param.getBusType());
        String mainTable = JSON.toJSONString(map);

        int len = param.getDiscountApplicationReqItem().length;
        String detailTables = "";
        if(len>0){
            detailTables = "[[";
            for(int i=0;i<len;i++){
                detailTables += JSON.toJSONString(param.getDiscountApplicationReqItem()[i]);
                detailTables += ",";
            }
            detailTables = detailTables.substring(0, detailTables.length()-1)+"]]";
        }
        log.error("明细表："+detailTables);


        JSONArray outerArray = JSONArray.parseArray(detailTables);
        System.out.println(outerArray);
        String[] detailArray = new String[outerArray.size()];
        for (int i = 0; i < outerArray.size(); i++) {
            detailArray[i] = outerArray.getString(i);
        }
//        //转成数组
//        JSONArray jsonArrays = JSON.parseArray(detailTables);
//        JSONArray innerArray = jsonArrays.getJSONArray(0);
//        String[] detailArray = new String[innerArray.size()];
//        for (int i = 0; i < innerArray.size(); i++) {
//            detailArray[i] = innerArray.getString(i);
//        }
        String result = autoCreateWorkflowService.createWorkflow(loginname, password, workflowId, creator, requestLevel, mainTable, detailArray);
        log.error("DiscountApplicationImpl:"+result);

        if(result.matches("^[1-9]+[0-9]*$")){
            res.setISTAT("S");
            res.setRequestid(result);
            res.setSRMSAGE("流程创建成功！");
        }else{
            res.setISTAT("E");
            res.setRequestid("");
            res.setSRMSAGE(result);
        }
        return res;
    }
}
