package com.seeyon.apps.src_hxinvoice.node;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.common.config.ICstConfigApi;
import com.seeyon.apps.common.plugin.vo.ConfigVo;
import com.seeyon.apps.common.workflow.constants.WorkFlowType;
import com.seeyon.apps.common.workflow.node.ACommonSuperNode;
import com.seeyon.apps.ext.workflow.vo.FieldDataVo;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.ext.workflow.vo.SuperNodeContext;
import com.seeyon.apps.src_hxinvoice.constants.HxinvoiceConstants;
import com.seeyon.apps.src_hxinvoice.dao.IHxinvoiceDao;
import com.seeyon.apps.src_hxinvoice.dao.impl.HxinvoiceDaoImpl;
import com.seeyon.apps.src_hxinvoice.util.FileUtil;
import com.seeyon.apps.src_hxinvoice.util.FormExportUtil;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumBean;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.v3x.services.form.FormFactory;
import com.seeyon.v3x.services.form.bean.FormExport;
import com.seeyon.v3x.services.form.bean.SubordinateFormExport;
import com.seeyon.v3x.services.form.bean.ValueExport;
import www.seeyon.com.utils.StringUtil;

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

public class AddGenerateQdInvoiceArchivesNode extends ACommonSuperNode {

    private static Log log = Log.get(AddGenerateQdInvoiceArchivesNode.class);

    protected ICstConfigApi cstConfigApi = (ICstConfigApi) AppContext.getBean("cstConfigApi");

    public ConfigVo getHxinvoiceConfig() {
        return cstConfigApi.getConfig(getPluginId());
    }

    private AttachmentManager attachmentManager;

    public void setAttachmentManager(AttachmentManager attachmentManager) {
        this.attachmentManager = attachmentManager;
    }

    public AttachmentManager getAttachmentManager() {
        if (attachmentManager == null) {
            attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
        }
        return attachmentManager;
    }

    private EnumManager enumManagerNew;
    public void setEnumManagerNew(EnumManager enumManagerNew) {this.enumManagerNew = enumManagerNew; }
    public EnumManager getEnumManagerNew() {
        if (enumManagerNew == null) {enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");}return enumManagerNew;
    }

    private FormFactory formFactory;

    public FormFactory getFormFactory() {
        if (formFactory == null) {
            formFactory = (FormFactory) AppContext.getBean("formFactory");
        }
        return formFactory;
    }

    private OrgManager orgManager;

    public OrgManager getOrgManager() {
        if (this.orgManager == null) {
            this.orgManager = ((OrgManager)AppContext.getBean("orgManager"));
        }
        return orgManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public void setFormFactory(FormFactory formFactory) {
        this.formFactory = formFactory;
    }

    @Override
    public String getPluginId() {
        return HxinvoiceConstants.getPluginId();
    }

    @Override
    public String getFormParse() {
        return "json";
    }

    @Override
    public WorkFlowType[] getTypes() {
        return new WorkFlowType[0];
    }

    @Override
    public SuperNodeContext proceed(String request, FormDataVo formDataVo, FormDataMasterBean formDataMasterBean) throws Exception {
        System.out.println("进入开票档案表创建超级节点");
        SuperNodeContext context = new SuperNodeContext();
        try{
        IHxinvoiceDao hxinvoiceDao = new HxinvoiceDaoImpl();
        ConfigVo configVo = getHxinvoiceConfig();
        FileUtil fileUtil = new FileUtil();
        FormExportUtil formExportUtil = new FormExportUtil();
//        根据附件ID获取文件信息
        JSONObject jsonObject = JSONObject.parseObject(request);
        String fileIdStr = jsonObject.getString("fileId");
//        查询附件路径,解析附件文件
        JSONArray jsonArray = fileUtil.getFileContent(Long.parseLong(fileIdStr));
        context.setRequest(jsonArray.toString());
        context.setNeedSave(true);
//        主表通用字段
        FieldDataVo ddqqpchvo = formDataVo.getFieldData("订单请求批次号");
        String ddqqpcl = ddqqpchvo.getStringValue();
        FieldDataVo jbbmvo = formDataVo.getFieldData("经办部门");
//        String jbbm = jbbmvo.getStringValue();
            String jbbm = "";
            String jbbmid = "";
            if(jbbmvo.getDbValue()!=null){
                String jbbmdb = jbbmvo.getDbValue().toString();
                V3xOrgDepartment v3xOrgDepartment = orgManager.getDepartmentById(Long.parseLong(jbbmdb));
                jbbm = v3xOrgDepartment.getName();
                jbbmid = v3xOrgDepartment.getId()+"";
            }

        FieldDataVo jbryvo = formDataVo.getFieldData("经办人员");
        String jbry = "";
        String jbryid = "";
        if(jbryvo.getDbValue()!=null){
            String jbrydb = jbryvo.getDbValue().toString();
            V3xOrgMember v3xOrgMember = orgManager.getMemberById(Long.parseLong(jbrydb));
            jbry = v3xOrgMember.getName();
            jbryid = v3xOrgMember.getId()+"";
        }
        FieldDataVo jbrqvo = formDataVo.getFieldData("经办日期");
        String jbrq = jbrqvo.getStringValue();
        FieldDataVo fqlxvo = formDataVo.getFieldData("发票类型");
        Object fqlx = fqlxvo.getDbValue();
        FieldDataVo xtlyvo = formDataVo.getFieldData("系统来源标识");
        String txly = xtlyvo.getStringValue();
        FieldDataVo kqlxvo = formDataVo.getFieldData("红蓝开票类型");
        Object kqlx = kqlxvo.getDbValue();
        FieldDataVo fqlxdmvo = formDataVo.getFieldData("发票类型代码");
        String fqlxdm = fqlxdmvo.getStringValue();
        FieldDataVo kjfpzlvo = formDataVo.getFieldData("开具发票种类");
        Object kjfpzl = kjfpzlvo.getDbValue();
        FieldDataVo dzqsxtfhjgvo = formDataVo.getFieldData("电子税票系统返回结果");
        String dzqsxtfhjg = dzqsxtfhjgvo.getStringValue();
        FieldDataVo kqryvo = formDataVo.getFieldData("开票人");
        String kqry = kqryvo.getStringValue();
        FieldDataVo kqrqvo = formDataVo.getFieldData("开票日期");
        String kqrq = kqrqvo.getStringValue();
        FieldDataVo kqdjhvo = formDataVo.getFieldData("开票单据号");
        String kqdjh = kqdjhvo.getStringValue();
        FieldDataVo gsmcvo = formDataVo.getFieldData("公司名称");
        String gsmc = gsmcvo.getStringValue();
        FieldDataVo gsbhvo = formDataVo.getFieldData("公司编号");
        String gsbh = gsbhvo.getStringValue();
        FieldDataVo ddqqlshvo = formDataVo.getFieldData("订单请求流水号");
        String ddqqlsh = ddqqlshvo.getStringValue();
        FieldDataVo shxmcvo = formDataVo.getFieldData("公司名称");
        String shxmc = shxmcvo.getStringValue();
        FieldDataVo xhfnsrsbhvo = formDataVo.getFieldData("销售方税号");
        String xhfnsrsbh = xhfnsrsbhvo.getStringValue();
//        根据文件信息创建创建档案表参数
        for(int i = 0 ; i < jsonArray.size() ; i++){
            FormExport formExport = new FormExport();
            JSONObject paramjson = jsonArray.getJSONObject(i);
            log.info(paramjson.toString());
//            System.out.println(paramjson.toString());
//            设置主表数据
            Map<String,Object> map = new HashMap<>();
            map.put("订单请求批次号",ddqqpcl);
            map.put("订单请求流水号",ddqqlsh+"_"+paramjson.getString("DDH"));
            map.put("订单号",kqdjh);
            map.put("开票单据号",kqdjh);
            map.put("公司名称",gsmc);
            map.put("公司编号",gsbh);
            map.put("经办部门",jbbmid);
            map.put("经办人员",jbryid);
            map.put("经办日期",jbrq);
            map.put("销售方编号",xhfnsrsbh);
            map.put("销售方名称",shxmc);
            map.put("销售方纳税人识别号",xhfnsrsbh);
            map.put("购买方编号",paramjson.getString("GMFNSRSBH"));
            map.put("购买方信息",paramjson.getString("GMFMC"));
//            map.put("购买方类型",paramjson.getString("XHFNSRSBH"));
            map.put("购买方税号",paramjson.getString("GMFNSRSBH"));
            map.put("购买方联系方式",paramjson.getString("GMFSJ"));
            map.put("购买方邮箱地址",paramjson.getString("GMFYX"));
            map.put("发票类型",fqlx);
            map.put("系统来源标识",txly);
            map.put("开票类型",kqlx);
            map.put("开具发票种类",kjfpzl);
            map.put("申请开票日期",kqrq);
            map.put("开票人",kqry);
            map.put("发票类型代码",fqlxdm);
            map.put("电子税票系统返回结果",dzqsxtfhjg);
            context.setResponse(map.toString());

//            设置明细表数据
            JSONArray sps = paramjson.getJSONArray("SPS");
            List<Map<String,Object>> subMaps = new ArrayList<>();
//          总金额
            double zje = 0;
            for(int n = 0 ; n <sps.size();n++ ){
                Map<String,Object> spmap = new HashMap<>();
                JSONObject sp = sps.getJSONObject(n);
                String spcode = sp.get("SPBM").toString();
                Map<String,Object> goods = hxinvoiceDao.getGoodsByCode(spcode);
                spmap.put("商品税目分类编码",spcode);
                spmap.put("税目编码",spcode);
                spmap.put("项目名称",goods.get("spmc"));
                if("折扣行".equals(sp.getString("FXHXZ"))){
                    spmap.put("发票行性质编码","1");//发票行性质
                }else if ("被折扣行".equals(sp.getString("FXHXZ"))){
                    spmap.put("发票行性质编码","2");//发票行性质
                }else{
                    spmap.put("发票行性质编码","0");//发票行性质
                }
//                Map<String,Object> fxhxzMap = hxinvoiceDao.getGoodsByCode(spcode);
                String enumProCode = configVo.getParamVal(HxinvoiceConstants.enumProCode.name());
                CtpEnumBean fxhxzEnum = enumManagerNew.getEnumByProCode(enumProCode);
                List<CtpEnumItem> fxhxzEnumItems = enumManagerNew.getCtpEnumItem(fxhxzEnum.getId(),0);

                for (CtpEnumItem fxhxzEnumItem:fxhxzEnumItems) {
                    if(fxhxzEnumItem.getShowvalue().equals(sp.getString("FXHXZ"))){
                        spmap.put("发票行性质",fxhxzEnumItem.getId());
                    }
                }
                spmap.put("单位",sp.getString("DW"));
                spmap.put("数量",sp.getString("NUM"));
                spmap.put("单价",sp.getString("SPDJ"));
                spmap.put("项目名称",sp.getString("XMMC"));
                spmap.put("商品税目名称",goods.get("spmc"));//商品税目名称
                spmap.put("规格",sp.getString("GGXH"));//商品税目名称
                spmap.put("金额",sp.getString("JE"));
                if(StringUtil.isNotEmpty(sp.getString("JE"))){
                    zje = zje+Double.parseDouble(sp.getString("JE"));
                }
                spmap.put("折扣金额",sp.getString("ZKJE"));
//                if(!(goods.get("lsbs") == null)){
//                    String lsbs = goods.get("lsbs").toString();
//                    CtpEnumItem lsbsEnum = getEnumManagerNew().getCtpEnumItem(Long.parseLong(lsbs));
//                    String lsbsstr = lsbsEnum.getValue();
//                    spmap.put("零税率标识",lsbsstr);//零税标识
//                }
//                if(!(goods.get("yhzcbs") == null)){
//                    String yhzcbs = goods.get("yhzcbs").toString();
//                    CtpEnumItem yhzcbsEnum = getEnumManagerNew().getCtpEnumItem(Long.parseLong(yhzcbs));
//                    String yhzcbsstr = yhzcbsEnum.getValue();
//                    spmap.put("优惠政策标识",yhzcbsstr);//优惠政策标识
//                }
                if(StringUtil.isNotEmpty(sp.getString("ZZSTSGL"))){
                    spmap.put("增值税特殊管理","免税");//增值税特殊管理
                    String yhzcbsProCode = configVo.getParamVal(HxinvoiceConstants.yhzcbsProCode.name());
                    CtpEnumBean yhzcbsEnum = enumManagerNew.getEnumByProCode(yhzcbsProCode);
                    List<CtpEnumItem> yhzcbsItems = enumManagerNew.getCtpEnumItem(yhzcbsEnum.getId(),0);
                    String yhzcbsstr = "";
                    for (CtpEnumItem yhzcbsItem:yhzcbsItems) {
                        if("免税".equals(yhzcbsItem.getShowvalue())){
                            yhzcbsstr = yhzcbsItem.getId().toString();
                        }
                    }
                    spmap.put("优惠政策标识",yhzcbsstr);//优惠政策标识
                    String lsbsProCode = configVo.getParamVal(HxinvoiceConstants.lsbsProCode.name());
                    CtpEnumBean lsbsEnum = enumManagerNew.getEnumByProCode(lsbsProCode);
                    List<CtpEnumItem> lsbsItems = enumManagerNew.getCtpEnumItem(lsbsEnum.getId(),0);
                    String lsbsstr = "";
                    for (CtpEnumItem lsbsItem:lsbsItems) {
                        if("零税率".equals(lsbsItem.getShowvalue())){
                            lsbsstr = lsbsItem.getId().toString();
                        }
                    }
                    spmap.put("零税率标识",lsbsstr);//零税标识
                }
                String sl = sp.getString("SL");
                spmap.put("税率",sl);//税率
                subMaps.add(spmap);
            }
            map.put("合计金额",zje);
            List<ValueExport> valueExports =  formExportUtil.setFormValue(map);
            List<SubordinateFormExport> subordinateFormExports = formExportUtil.setSubordinateFormValue(subMaps);
            formExport.setValues(valueExports);
            formExport.setSubordinateForms(subordinateFormExports);
            log.info("准备创建开票档案表");
            String loginName = configVo.getParamVal(HxinvoiceConstants.uploadMemberLoginName.name());
            getFormFactory().importBusinessFormData(loginName, "KPSJDA",formExport, new String[] {});
        }
            context.success("档案表创建完成！！！", false);
        }catch (Exception e){
            e.printStackTrace();
            context.setResponse(e.toString());
            context.setException(true);
            context.back("档案表创建失败！！！");
        }
//        封装档案表参数
//        使用档案表创建方法生成档案表

        return context;
    }

    @Override
    public String getNodeId() {
        return "AddGenerateQdInvoiceArchivesNode";
    }

    @Override
    public String getNodeName() {
        return "批量数电发票开票档案表创建";
    }
}
