package com.engine.htsc.subcompany.service.impl;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.alibaba.fastjson.JSON;

import weaver.conn.RecordSet;
import weaver.general.GCONST;

// 运维工具，批量导入银行卡信息存储至DB
public class LhBatchImportBankCardServiceImpl {
    private Log log = LogFactory.getLog(this.getClass());

    public Map<String, Object> importExcelAndSaveToDB(HttpServletRequest request) {
        Map<String, Object> data = new HashMap<>();
        data.put("code", "200");
        data.put("msg", "success");
        try {
            List<List<Object>> updateParams = new ArrayList<>();
            // 输入流
            InputStream inputStream = request.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rows; i++) {
                // 跳过表头
                if (i == 0) {
                    continue;
                }
                Row row = sheet.getRow(i);
                List<Object> list = new ArrayList<>();
                for (Cell cell : row) {
                    list.add(cell.getStringCellValue());
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    updateParams.add(list);
                }
                if (CollectionUtils.isNotEmpty(updateParams)) {
                    List<List> processedData = getProcessedData(updateParams);
                    log.info(String.format("lh bankinfo save to DB,data %s", JSON.toJSONString(processedData)));
                    saveToDB(processedData);
                }
            }
        } catch (Exception e) {
            data.put("code", "500");
            data.put("msg", "批量导入发生错误，详情请查看日志");
            log.info("batch import error!", e);
        }
        return data;
    }

    private void saveToDB(List<List> updateParams) {
        RecordSet rs = new RecordSet();
        String sql =
            "insert into uf_lhclyxxx(khr,yxmc,yxkh,ngr,ss,modedatacreatedate,modedatacreatetime) values(?,?,?,?,?,?,?)";
        rs.executeBatchSql(sql, updateParams);
    }

    private List<List> getProcessedData(List<List<Object>> updateParams) {
        List<List> result = new ArrayList<>(updateParams.size());
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        updateParams.forEach(item -> {
            List<Object> list = new ArrayList<>();
            // 工号 = 开户人
            list.add(item.get(0));
            // 发放银行 = 银行名称
            list.add(item.get(2));
            // 银行账号 = 银行卡号
            list.add(item.get(3));
            // 拟稿人
            list.add(getFWID((String)item.get(0),(String)item.get(4)));
            // 省市信息
            list.add(getSSInfo((String)item.get(5)));
            String[] now = LocalDateTime.now().format(df).split(" ");
            // 数据创建日期 时间
            list.add(now[0]);
            list.add(now[1]);
            result.add(list);
        });
        return result;
    }

    private String getFWID(String workCode,String departmentName) {
        String empID = "";
        RecordSet rs = new RecordSet();
        String sql = "select s.id from hrmresource s where s.workcode = ? and s.departmentid in (" +
                     "select m.id\n" + "           from hrmdepartment m\n" +
                     "          where DEPARTMENTNAME = ?)";
        rs.executeQuery(sql, workCode, departmentName);
        while (rs.next()) {
            empID = rs.getString("id");
            break;
        }
        return empID;
    }

    private String getSSInfo(String city) {
        RecordSet rs = new RecordSet();
        String ss = "";
        String sql = "select c.parentcode , c.code from uf_city c where c.name = ? ";
        rs.executeQuery(sql, city);
        while (rs.next()) {
            ss = rs.getString("parentcode") + "," + rs.getString("code");
            break;
        }
        return ss;
    }

    public static void main(String[] args) throws Exception {
        GCONST.setRootPath("");
        GCONST.setServerName("ecology");
        String fileName = "D:/导入员工银行账户.xlsx";
        // InputStream inputStream = new FileInputStream(fileName);
        // new LhBatchImportBankCardServiceImpl().importExcelAndSaveToDB(inputStream);
        List<Object> list = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String[] now = LocalDateTime.now().format(df).split(" ");
        List<List> updateParams = new ArrayList<>();
        // 工号 = 开户人
        list.add("016328");
        // 发放银行 = 银行名称
        list.add("test");
        // 银行账号 = 银行卡号
        list.add("6212260200079910267");
        // 拟稿人
        list.add("016328");
        // 省市信息
        list.add("11,1101");
        // 数据创建日期 时间
        list.add(now[0]);
        list.add(now[1]);
        updateParams.add(list);
        RecordSet rs = new RecordSet();
        String sql =
            "insert into uf_lhclyxxx(khr,yxmc,yxkh,ngr,ss,modedatacreatedate,modedatacreatetime) values(?,?,?,?,?,?,?)";
        // rs.executeBatchSql(sql, updateParams);
        rs.executeUpdate(sql,list);
    }
}
