package com.weaver.seconddev.njwebservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.weaver.common.hrm.util.Util;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.njwebservice.entity.BillingApplicationReq;
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.HashMap;
import java.util.Map;

/**
 * @Author liang.cheng
 * @Date 2025/1/21 15:56
 * @Description: CW23-商票开票申请流程（供应链金融系统触发）
 * @Version 1.0
 */
@Service("billingApplicationService")
public class BillingApplicationService {

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

    @Autowired
    private AutoCreateWorkflowService autoCreateWorkflowService;

    public ResponseInfo billingApplicate(BillingApplicationReq param) {
        log.error("BillingApplicationService:"+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=0", 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.getApplyNo()!=null&&!"".equals(param.getApplyNo())){
            rs.executeSql("select applyNo from formtable_main_2301 where applyNo='"+param.getApplyNo()+"'",CONN_TYPE.workflow.getType());
            if(rs.next()){
                res.setISTAT("E");
                res.setRequestid("");
                res.setSRMSAGE("申请单号已存在，请不要重复申请！");
                return res;
            }
        }

//		if(param.getSh()==null||"".equals(param.getSh())){
//			res.setISTAT("E");
//			res.setRequestid("");
//			res.setSRMSAGE("税号不能为空！");
//			return res;
//
//		}
        String loginname = "SCF";
        String password = "123456";
        String workflowId = "4205";
        String requestLevel = "0";
        String billType = "";
        if("1".equals(param.getBillType())){
            billType = "0";
        }else if ("2".equals(param.getBillType())){
            billType = "1";
        }
        Map<String,String> map = new HashMap<String,String>();
        map.put("hrm:sqr", creator);
        map.put("com:sqr:sqdw", "");
        map.put("dep:sqr:sqbm", "");
        map.put("applyNo", param.getApplyNo());
        map.put("companyName", param.getCompanyName());
        map.put("companyCode", param.getCompanyCode());
        map.put("billType", billType);
        map.put("vendorName", param.getVendorName());
        map.put("vendorCode", param.getVendorCode());
        map.put("applyDate", param.getApplyDate());
        map.put("amount", param.getAmount());
        map.put("REMARKS", param.getREMARKS());
        String mainTable = JSON.toJSONString(map);
        int len = param.getBillingApplicationResItem().length;

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

        //转成数组
        JSONArray jsonArrays = JSON.parseArray(detailTables);
        JSONArray innerArray = jsonArrays.getJSONArray(0);
        String[] detailArray = new String[innerArray.size()];

        String result = autoCreateWorkflowService.createWorkflow(loginname, password, workflowId, creator, requestLevel, mainTable, detailArray);
        log.error("BillingApplicationImpl:"+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;
    }



}
