package com.artfess.file.extend;

import com.deepoove.poi.data.DocxRenderData;
import com.deepoove.poi.policy.DocxRenderPolicy;
import com.deepoove.poi.policy.DynamicTableRenderPolicy;
import com.deepoove.poi.policy.RenderPolicy;
import com.artfess.base.util.StringUtil;
import com.artfess.file.util.HtmlUtil;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DetailTablePolicy extends DynamicTableRenderPolicy {

    // 货品填充数据所在行数
    int goodsStartRow = 2;


    @Override
    public void render(XWPFTable table, Object data) {
        String subKey="";
        if (null == data) return;

        // 字表数据明细
        List<Map> subTable = new ArrayList<>();
        if(data instanceof List){
            subTable= (List<Map>) data;
        }else{
            subTable.add(((Map) data));
        }
        List<XWPFTableCell> templateCell =  table.getRow(goodsStartRow).getTableCells();
        Map<Integer,String> mapCell=new HashMap<>();
        for (int i = 0; i < templateCell.size(); i++) {
            String key=templateCell.get(i).getText().replace("{","").replace("}","");
            if(StringUtil.isNotEmpty(key)){
                subKey=key.substring(0,key.indexOf("."));
                key=key.substring(key.indexOf(".")+1,key.length());
            }
            mapCell.put(i,key);
        }
        if (null != subTable) {
            table.removeRow(goodsStartRow);
            for (int i = subTable.size()-1; i >= 0; i--) {
                XWPFTableRow insertNewTableRow = table.insertNewTableRow(goodsStartRow);
                Map subMap=subTable.get(i);
                for (int j = 0; j <  templateCell.size(); j++) {
                    XWPFTableCell cell=insertNewTableRow.createCell();
                    String key=mapCell.get(j);
                    if(subMap.containsKey(key)){
                        Object value=subMap.get(key);
                        if(value instanceof DocxRenderData){
                            if(subTable.size()==1){
                                cell.setText(String.format("{{+%s.%s}}",subKey,key));
                            }else{
                                cell.setText(String.format("{{+%s[%s].%s}}",subKey,i,key));
                            }
                        }else{
                            cell.setText(value.toString());
                        }
                    }else{
                        cell.setText("");
                    }

                }
            }
        }


    }


}
