package pwc.taxtech.atms.common;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import pwc.taxtech.atms.CommonIT;
import pwc.taxtech.atms.common.util.DateUtils;
import pwc.taxtech.atms.dao.CellTemplateConfigDao;
import pwc.taxtech.atms.entity.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DataMigration extends CommonIT {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    CellTemplateConfigDao cellTemplateConfigDao;

    private List<Map<String, Object>> template20180622List;

    private List<Map<String, Object>> templateList;

    private List<CellTemplate> cellTemplates;

    private List<Template> templates;

    private List<Map<String, Object>> cellTemplate20180622List;

    //1. 这个是原本的id
    String templateGroupId = "'60771384-473c-4f6a-9d40-d2a807dca164'";

    //2.这个是新的templategroupid
    Long templateGroupIdLong = 15081298737631232L;

    @Test
    public void doMigration(){
//        doMigrationTemplateGroup();
//        doMigrationTemplate();
//        doMigrationCellTemplate();
        doMigrationCellTemplateConfig();
    }


    @Test
    public void doMigrationTemplateGroup() {
        // todo String sql = "Select * from template_group where id=" + templateGroupId;
        String sql = "Select * from TemplateGroup_20180622 where id=" + templateGroupId;
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
//        sql = "DELETE FROM template_group";
//        jdbcTemplate.execute(sql);
        TemplateGroup templateGroup;
        for (Map<String, Object> item : queryForList) {
            templateGroup = new TemplateGroup();
            this.templateGroupIdLong = distributedIdService.nextId();
            templateGroup.setId(this.templateGroupIdLong);
            templateGroup.setName((MapUtils.getString(item, "Name")));
            templateGroup.setServiceTypeId((MapUtils.getString(item, "ServiceTypeID")));
            templateGroup.setIndustryIds((MapUtils.getString(item, "IndustryIDs")));
            templateGroup.setPayTaxType((MapUtils.getInteger(item, "PayTaxType") != null ? MapUtils.getInteger(item, "PayTaxType") : 0));
            templateGroup.setGroupType((MapUtils.getInteger(item, "GroupType")));
            templateGroup.setCopyFrom(0L);
            templateGroup.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            templateGroup.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            templateGroup.setIsSystemType((MapUtils.getBoolean(item, "IsSystemType")));
            templateGroup.setCreateBy(StringUtils.EMPTY);
            templateGroup.setUpdateBy(StringUtils.EMPTY);
            templateGroupMapper.insert(templateGroup);
        }
    }

    @Test
    public void doMigrationTemplate() {
        String sql = "Select * from Template_1 where TemplateGroupID=" + templateGroupId;
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
//        sql = "DELETE FROM template";
//        jdbcTemplate.execute(sql);
        Template template;
        for (Map<String, Object> item : queryForList) {
            template = new Template();
            template.setId(distributedIdService.nextId());
            template.setName(MapUtils.getString(item, "Name"));
            template.setCode(MapUtils.getString(item, "Code") != null ? MapUtils.getString(item, "Code") : StringUtils.EMPTY);
            template.setPath(MapUtils.getString(item, "Path"));
            template.setReportType(MapUtils.getInteger(item, "ReportType") != null ? MapUtils.getInteger(item, "ReportType") : 0);
            template.setOrderIndex(MapUtils.getInteger(item, "OrderIndex"));
            template.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            template.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            template.setIsSystemType(MapUtils.getBoolean(item, "IsSystemType"));
            template.setIsActiveAssociation(MapUtils.getBoolean(item, "IsActiveAssociation"));
            template.setParentId(MapUtils.getString(item, "ParentId") != null ? MapUtils.getString(item, "ParentId") : StringUtils.EMPTY);
            template.setCreateBy(StringUtils.EMPTY);
            template.setUpdateBy(StringUtils.EMPTY);
//            template.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupID")));
            template.setTemplateGroupId(templateGroupIdLong);
            templateMapper.insert(template);
        }
    }

    /**
     * 根据老表templategroupid获取新表id
     *
     * @param id 老表templategroupid
     * @return 新表templategroupid
     */
    private Long getIdFromExistTable(String id) {
        try {
//          todo String sql = "SELECT name as Name,update_time as UpdateTime from template_group where id='" + id + "'";
            String sql = "SELECT `Name`,UpdateTime from TemplateGroup_20180622 where id='" + id + "'";
            Map<String, Object> result = jdbcTemplate.queryForMap(sql);
            String name = MapUtils.getString(result, "Name");
            String updateTime = MapUtils.getString(result, "UpdateTime");
            sql = "SELECT id from template_group a WHERE a.update_time='" + updateTime + "' AND `name`='" + name + "'";
            result = jdbcTemplate.queryForMap(sql);
            return MapUtils.getLong(result, "id");
        } catch (Exception e) {
            return 0L;
        }
    }

    //todo:cell_template  --220081
    @Test
    public void doMigrationCellTemplate() {
        String sql = "SELECT * FROM CellTemplate WHERE ReportTemplateID IN " +
                "(SELECT ID FROM Template_1 WHERE TemplateGroupID IN(" + templateGroupId + ") )";
//                " AND path LIKE '%VatTemplate/DefaultVersion/%')";
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
        System.out.println(sql);
//        sql = "DELETE FROM cell_template";
//        System.out.println(sql);
//        jdbcTemplate.execute(sql);
        CellTemplate cellTemplate;
        cellTemplates = new ArrayList<>();
        List<CellTemplate> cellTemplateList = new ArrayList<>();
        sql = "SELECT ID,Name,Code,CreateTime from Template_1";
        template20180622List = jdbcTemplate.queryForList(sql);
//        sql = "SELECT id,`name`,code,create_time from template";
//        templateList = jdbcTemplate.queryForList(sql);

        templates = templateMapper.selectByExample(new TemplateExample());

        int i = 0, j = 0;
        for (Map<String, Object> item : queryForList) {
            i++;
            j++;
            cellTemplate = new CellTemplate();
            cellTemplate.setId(distributedIdService.nextId());
            cellTemplate.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateID")));
            cellTemplate.setRowIndex(MapUtils.getInteger(item, "RowIndex"));
            cellTemplate.setRowName(MapUtils.getString(item, "RowName") != null ? MapUtils.getString(item, "RowName") : "");
            cellTemplate.setColumnIndex(MapUtils.getInteger(item, "ColumnIndex"));
            cellTemplate.setColumnName(MapUtils.getString(item, "ColumnName") != null ? MapUtils.getString(item, "ColumnName") : "");
            cellTemplate.setComment(MapUtils.getString(item, "Comment") != null ? MapUtils.getString(item, "Comment") : "");
            cellTemplate.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            cellTemplate.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            cellTemplate.setCopyFromId(0L);
            cellTemplate.setDataType(MapUtils.getInteger(item, "DataType") != null ? MapUtils.getInteger(item, "DataType") : 0);
            cellTemplate.setIsReadOnly(MapUtils.getInteger(item, "IsReadOnly") != null ? MapUtils.getBoolean(item, "IsReadOnly") : false);
            cellTemplate.setUpdateBy(StringUtils.EMPTY);
            cellTemplate.setCreateBy(StringUtils.EMPTY);
//          cellTemplateMapper.insert(cellTemplate);
            cellTemplateList.add(cellTemplate);
            System.out.println("i=" + i);
            System.out.println("j=" + j);

            if (i == 1000 && j < queryForList.size()) {
                cellTemplateMapper.batchInsert2(cellTemplateList);
                cellTemplateList.clear();
                i = 0;
            } else {
                if (j == queryForList.size()) {
                    cellTemplateMapper.batchInsert2(cellTemplateList);
                    cellTemplateList.clear();
                }
            }
        }
        //handleList(queryForList, 2);

    }

    /**
     * 根据template老表ID获取新表ID
     *
     * @param id template老表ID
     * @return
     */
    private Long getIdFromExistTable2(String id) {
        try {
//            String sql = "SELECT `Name`,Code,CreateTime from Template_20180622 where id='" + id + "'";
//            System.out.println(sql);
            Map<String, Object> item = template20180622List.stream()
                    .filter(a -> MapUtils.getString(a, "ID").equals(id))
                    .findFirst().get();
            //Map<String, Object> result = jdbcTemplate.queryForMap(sql);
            String name = MapUtils.getString(item, "Name");
            String code = MapUtils.getString(item, "Code");
            String createTime = MapUtils.getString(item, "CreateTime");
            //template20180622List.remove(item);
//            item = templateList.stream()
//                    .filter(a -> MapUtils.getString(a, "name").equals(name)
//                            && MapUtils.getString(a, "code").equals(code)
//                            && MapUtils.getString(a, "create_time").equals(createTime))
//                    .findFirst().get();

            Template template = templates.stream()
                    .filter(a -> a.getName().equals(name) && a.getCode().equals(code)
                            && a.getCreateTime().equals(DateUtils.strToDateLong(createTime))
                            && a.getTemplateGroupId().equals(templateGroupIdLong))
                    .findFirst().get();
            //sql = "SELECT id from template a WHERE create_time='" + createTime + "' AND `name`='" + name + "' AND code='" + code + "'";
            //System.out.println(sql);
            //result = jdbcTemplate.queryForMap(sql);
            Long newId = template.getId();
            //templateList.remove(item);
            return newId;
        } catch (Exception e) {
            return 0L;
        } finally {
        }
    }

    /**
     * 多线程处理list
     *
     * @param data      数据list
     * @param threadNum 线程数
     */
    public synchronized void handleList(List<Map<String, Object>> data, int threadNum) {
        int length = data.size();
        int tl = length % threadNum == 0 ? length / threadNum : (length
                / threadNum + 1);

        for (int i = 0; i < threadNum; i++) {
            int end = (i + 1) * tl;
            HandleThread thread = new HandleThread("线程[" + (i + 1) + "] ", data, i * tl, end > length ? length : end);
            System.out.println("线程[" + (i + 1) + "]  started");
            thread.start();
        }
    }

    class HandleThread extends Thread {
        private String threadName;
        private List<Map<String, Object>> data;
        private int start;
        private int end;

        public HandleThread(String threadName, List<Map<String, Object>> data, int start, int end) {
            this.threadName = threadName;
            this.data = data;
            this.start = start;
            this.end = end;
        }

        public void run() {
            // TODO 这里处理数据
            CellTemplate cellTemplate;
            for (Map<String, Object> item : data) {
                cellTemplate = new CellTemplate();
                cellTemplate.setId(distributedIdService.nextId());
                //cellTemplate.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateID")));
                cellTemplate.setRowIndex(MapUtils.getInteger(item, "RowIndex"));
                cellTemplate.setRowName(MapUtils.getString(item, "RowName") != null ? MapUtils.getString(item, "RowName") : "");
                cellTemplate.setColumnIndex(MapUtils.getInteger(item, "ColumnIndex"));
                cellTemplate.setColumnName(MapUtils.getString(item, "ColumnName") != null ? MapUtils.getString(item, "ColumnName") : "");
                cellTemplate.setComment(MapUtils.getString(item, "Comment") != null ? MapUtils.getString(item, "Comment") : "");
                cellTemplate.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
                cellTemplate.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
                cellTemplate.setCopyFromId(0L);
                cellTemplate.setDataType(MapUtils.getInteger(item, "DataType") != null ? MapUtils.getInteger(item, "DataType") : 0);
                cellTemplate.setIsReadOnly(MapUtils.getBoolean(item, "IsReadOnly") != null ? MapUtils.getBoolean(item, "IsReadOnly") : true);
                cellTemplate.setUpdateBy(StringUtils.EMPTY);
                cellTemplate.setCreateBy(StringUtils.EMPTY);
                synchronized (cellTemplates) {
                    cellTemplates.add(cellTemplate);
                }

                if (cellTemplates.size() == 100) {
                    synchronized (cellTemplates) {
                        cellTemplateMapper.batchInsert2(cellTemplates);
                        cellTemplates.clear();
                    }
                    System.out.println(threadName + "处理了" + data.size() + "条!");
                }
                //cellTemplateMapper.insert(cellTemplate);
            }

            synchronized (cellTemplates) {
                cellTemplateMapper.batchInsert2(cellTemplates);
                cellTemplates.clear();
            }
            System.out.println(threadName + "处理了" + data.size() + "条!");

            //doMigrationCellTemplate();
//            List<String> subList = data.subList(start, end)/*.add("^&*")*/;
//            System.out.println(threadName+"处理了"+subList.size()+"条!");
        }

    }

    //todo:cell_template_config --76577
    @Test
    public void doMigrationCellTemplateConfig() {
        String sql = "SELECT *\n" +
                "FROM CellTemplateConfig\n" +
                "WHERE ReportTemplateID IN(SELECT\n" +
                "                            ID\n" +
                "                          FROM Template_1\n" +
                "                          WHERE TemplateGroupID IN(" + templateGroupId + "))" +
//                "                              AND path LIKE '%VatTemplate/DefaultVersion/%')\n" +
                "    AND celltemplateid IN(SELECT\n" +
                "                            id\n" +
                "                          FROM CellTemplate\n" +
                "                          WHERE ReportTemplateID IN(SELECT\n" +
                "                                                      ID\n" +
                "                                                    FROM Template_1\n" +
                "                                                    WHERE TemplateGroupID IN(" + templateGroupId + ")))";
//                "                                                        AND path LIKE '%VatTemplate/DefaultVersion/%'))";
        System.out.println(sql);
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
//        sql = "DELETE FROM cell_template_config";
//        System.out.println(sql);
//        jdbcTemplate.execute(sql);

        sql = "SELECT ID,Name,Code,CreateTime from Template_1 ";
        template20180622List = jdbcTemplate.queryForList(sql);
        templates = templateMapper.selectByExample(new TemplateExample());
        cellTemplates = cellTemplateMapper.selectByExample(new CellTemplateExample());
        sql = "SELECT ID,ReportTemplateID,RowIndex,ColumnIndex from CellTemplate WHERE ReportTemplateID IN " +
                "(SELECT ID FROM Template_1 WHERE TemplateGroupID IN" +
                "(" + templateGroupId + "))";
        cellTemplate20180622List = jdbcTemplate.queryForList(sql);

        List<CellTemplateConfig> cellTemplateConfigList = new ArrayList<>();
        CellTemplateConfig cellTemplateConfig;
        int i = 0, j = 0;
        for (Map<String, Object> item : queryForList) {
            i++;
            j++;
            cellTemplateConfig = new CellTemplateConfig();
            cellTemplateConfig.setId(distributedIdService.nextId());
            cellTemplateConfig.setCellTemplateId(getIdFromExistTable3(MapUtils.getString(item, "CellTemplateID"), MapUtils.getString(item, "ReportTemplateID")));
            cellTemplateConfig.setReportTemplateId(getIdFromExistTable2(MapUtils.getString(item, "ReportTemplateID")));
            cellTemplateConfig.setDataSourceType(MapUtils.getInteger(item, "DataSourceType"));
            cellTemplateConfig.setFormula(MapUtils.getString(item, "Formula") != null ? MapUtils.getString(item, "Formula") : "");
            cellTemplateConfig.setFormulaDescription(MapUtils.getString(item, "FormulaDescription") != null ? MapUtils.getString(item, "FormulaDescription") : "");
            cellTemplateConfig.setAccountCodes(MapUtils.getString(item, "AccountCodes") != null ? MapUtils.getString(item, "AccountCodes") : "");
            cellTemplateConfig.setInvoiceType(MapUtils.getInteger(item, "InvoiceType") != null ? MapUtils.getInteger(item, "InvoiceType") : 0);
            cellTemplateConfig.setTaxRate(MapUtils.getString(item, "TaxRate") != null ? MapUtils.getString(item, "TaxRate") : "");
            cellTemplateConfig.setInvoiceAmountType(MapUtils.getInteger(item, "InvoiceAmountType") != null ? MapUtils.getInteger(item, "InvoiceAmountType") : 0);
            cellTemplateConfig.setModelIds(MapUtils.getString(item, "ModelIDs") != null ? MapUtils.getString(item, "ModelIDs") : "");
            cellTemplateConfig.setCreateBy(MapUtils.getString(item, "Creator") != null ? MapUtils.getString(item, "Creator") : "");
            cellTemplateConfig.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            cellTemplateConfig.setUpdateBy(MapUtils.getString(item, "Updater") != null ? MapUtils.getString(item, "Updater") : "");
            cellTemplateConfig.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            cellTemplateConfig.setInvoiceCategory(MapUtils.getString(item, "InvoiceCategory") != null ? MapUtils.getString(item, "InvoiceCategory") : "");
            cellTemplateConfig.setFormulaDataSource(MapUtils.getString(item, "FormulaDataSource") != null ? MapUtils.getString(item, "FormulaDataSource") : "");
            cellTemplateConfig.setValidation(MapUtils.getString(item, "Validation") != null ? MapUtils.getString(item, "Validation") : "");
            cellTemplateConfig.setValidationDescription(MapUtils.getString(item, "ValidationDescription") != null ? MapUtils.getString(item, "ValidationDescription") : "");
            cellTemplateConfig.setVoucherKeyword(MapUtils.getString(item, "VoucherKeyword") != null ? MapUtils.getString(item, "VoucherKeyword") : "");
            System.out.println("i=" + i);
            System.out.println("j=" + j);
            cellTemplateConfigList.add(cellTemplateConfig);
            if (i == 10 && j < queryForList.size()) {
                cellTemplateConfigDao.batchInsert(cellTemplateConfigList);
                cellTemplateConfigList.clear();
                i = 0;
            } else {
                if (j == queryForList.size()) {
                    cellTemplateConfigDao.batchInsert(cellTemplateConfigList);
                    cellTemplateConfigList.clear();
                }
            }

        }
    }

    /**
     * 根据templateid 和 celltemplateid 获取新表cellTemplate ID
     *
     * @param id  celltemplateid
     * @param id2 templateid
     * @return
     */
    private Long getIdFromExistTable3(String id, String id2) {
        try {
            //根据templateid 获取 新表 templateid
            Long templateId = getIdFromExistTable2(id2);
            //根据新表templateid 还有 rowIndex,columnIndex 获取 celltemplate 新表ID
            Map<String, Object> item = cellTemplate20180622List.stream()
                    .filter(a -> MapUtils.getString(a, "ID").equals(id))
                    .findFirst().get();

            Integer rowIndex = MapUtils.getInteger(item, "RowIndex");
            Integer columnIndex = MapUtils.getInteger(item, "ColumnIndex");

            CellTemplate cellTemplate = cellTemplates.stream()
                    .filter(a -> a.getReportTemplateId().equals(templateId)
                            && a.getRowIndex().equals(rowIndex)
                            && a.getColumnIndex().equals(columnIndex))
                    .findFirst().get();

            return cellTemplate.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    //todo:organization_service_template_group --284
    @Test
    public void doMigrationOrganizationServiceTemplateGroup() {
        String sql = "Select * from OrganizationServiceTemplateGroup";
        System.out.println(sql);
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
        sql = "DELETE FROM organization_service_template_group";
        System.out.println(sql);
        jdbcTemplate.execute(sql);

        OrganizationServiceTemplateGroup organizationServiceTemplateGroup;
        for (Map<String, Object> item : queryForList) {
            organizationServiceTemplateGroup = new OrganizationServiceTemplateGroup();
            organizationServiceTemplateGroup.setId(distributedIdService.nextId());
            organizationServiceTemplateGroup.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupID")));
            organizationServiceTemplateGroup.setOrganizationId(MapUtils.getString(item, "OrganizationID"));
            organizationServiceTemplateGroup.setServiceTypeId(MapUtils.getString(item, "ServiceTypeID"));
            organizationServiceTemplateGroupMapper.insert(organizationServiceTemplateGroup);
        }
    }

    //todo:tax_payer_report_rule --120
    @Test
    public void doMigrationTaxPayerReportRule() {
        String sql = "Select * from TaxPayerReportRule_20180622";
        System.out.println(sql);
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
        sql = "DELETE FROM tax_payer_report_rule";
        System.out.println(sql);
        jdbcTemplate.execute(sql);

        TaxPayerReportRule taxPayerReportRule;
        for (Map<String, Object> item : queryForList) {
            taxPayerReportRule = new TaxPayerReportRule();
            taxPayerReportRule.setId(distributedIdService.nextId());
            taxPayerReportRule.setTemplateGroupId(getIdFromExistTable(MapUtils.getString(item, "TemplateGroupID")));
            taxPayerReportRule.setOrganizationId(MapUtils.getString(item, "OrganizationID"));
            taxPayerReportRule.setTaxPayerType(MapUtils.getInteger(item, "TaxPayerType"));
            taxPayerReportRule.setIsDefault(MapUtils.getBoolean(item, "IsDefault"));
            taxPayerReportRule.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            taxPayerReportRule.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            taxPayerReportRule.setCreateBy(StringUtils.EMPTY);
            taxPayerReportRule.setUpdateBy(StringUtils.EMPTY);
            taxPayerReportRuleMapper.insert(taxPayerReportRule);
        }
    }

    //todo:tax_rule_setting --13
    @Test
    public void doMigrationTaxRuleSetting() {
//        todo String sql = "Select * from tax_rule_setting";
        String sql = "Select * from TaxRuleSetting_20180622";
        System.out.println(sql);
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
        sql = "DELETE FROM tax_rule_setting";
        System.out.println(sql);
        jdbcTemplate.execute(sql);

        TaxRuleSetting taxRuleSetting;
        for (Map<String, Object> item : queryForList) {
            taxRuleSetting = new TaxRuleSetting();
            taxRuleSetting.setId(distributedIdService.nextId());
            taxRuleSetting.setTaxBase(MapUtils.getString(item, "TaxBase"));
            taxRuleSetting.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            taxRuleSetting.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            taxRuleSetting.setGroupName(MapUtils.getString(item, "GroupName"));
            taxRuleSetting.setName(MapUtils.getString(item, "Name"));
            taxRuleSetting.setIsDefault(MapUtils.getBoolean(item, "IsDefault"));
            taxRuleSetting.setTaxRate(MapUtils.getFloat(item, "TaxRate"));
            taxRuleSetting.setCreateBy(StringUtils.EMPTY);
            taxRuleSetting.setUpdateBy(StringUtils.EMPTY);
            taxRuleSettingMapper.insert(taxRuleSetting);
        }
    }

    private List<Map<String, Object>> taxRuleSetting20180622List;
    private List<TaxRuleSetting> taxRuleSettingList;

    //todo:tax_rule_setting_organization --17
    @Test
    public void doMigrationTaxRuleSettingOrganization() {
//        todo String sql = "Select * from tax_rule_setting_organization";
        String sql = "Select * from TaxRuleSettingOrganization_20180622";
        System.out.println(sql);
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);
        sql = "DELETE FROM tax_rule_setting_organization";
        System.out.println(sql);
        jdbcTemplate.execute(sql);

//        todo sql = "SELECT id as ID,create_time as CreateTime FROM tax_rule_setting";
        sql = "SELECT ID,CreateTime  FROM TaxRuleSetting_20180622";
        taxRuleSetting20180622List = jdbcTemplate.queryForList(sql);
        taxRuleSettingList = taxRuleSettingMapper.selectByExample(new TaxRuleSettingExample());

        TaxRuleSettingOrganization taxRuleSettingOrganization;
        for (Map<String, Object> item : queryForList) {
            taxRuleSettingOrganization = new TaxRuleSettingOrganization();
            taxRuleSettingOrganization.setId(distributedIdService.nextId());
            taxRuleSettingOrganization.setTaxSettingId(getIdFromExistTable4(MapUtils.getString(item, "TaxSettingID")));
            taxRuleSettingOrganization.setOrganizationId(MapUtils.getString(item, "OrganizationID"));
            taxRuleSettingOrganization.setCreateTime(DateUtils.strToDateLong(MapUtils.getString(item, "CreateTime")));
            taxRuleSettingOrganization.setUpdateTime(DateUtils.strToDateLong(MapUtils.getString(item, "UpdateTime")));
            taxRuleSettingOrganization.setCreateBy(StringUtils.EMPTY);
            taxRuleSettingOrganization.setUpdateBy(StringUtils.EMPTY);
            taxRuleSettingOrganizationMapper.insert(taxRuleSettingOrganization);
        }
    }

    /**
     * 获取taxSetting 新表ID
     *
     * @param id 旧表ID
     * @return 新表ID
     */
    private Long getIdFromExistTable4(String id) {
        try {
            Map<String, Object> item = taxRuleSetting20180622List.stream()
                    .filter(a -> MapUtils.getString(a, "ID").equals(id))
                    .findFirst().get();
            String name = MapUtils.getString(item, "Name");
            String createTime = MapUtils.getString(item, "CreateTime");
            TaxRuleSetting taxRuleSetting = taxRuleSettingList.stream()
                    .filter(a -> a.getName().equals(name)
                            && a.getCreateTime().equals(createTime))
                    .findFirst().get();
            Long newId = taxRuleSetting.getId();
            return newId;
        } catch (Exception e) {
            return 0L;
        } finally {
        }
    }

}