import Ignore_ExecPageFlipper as ExecPageFlipper
import com.sdtool.business.dao.SystemDao
import com.sdtool.common.api.NoSqlKeysService
import com.sdtool.common.datas.ESKeys
import com.sdtool.common.entity.system.DataPurview
import com.sdtool.common.tool.ERPUtils
import com.dySweetFishPlugin.elasticsearch.ESClient
import com.sweetfish.convert.json.JsonConvert
import com.sweetfish.source.PageFlipper
import com.sweetfish.util.Utility
import org.apache.logging.log4j.Logger
import org.elasticsearch.action.bulk.BulkRequestBuilder
import org.elasticsearch.action.bulk.BulkResponse
import org.elasticsearch.action.index.IndexRequestBuilder
import org.elasticsearch.common.xcontent.XContentType
import org.rex.RMap

static def createRunnable(NoSqlKeysService keysService, ESClient esClient, SystemDao systemDao, JsonConvert jsonConvert, Logger logger, String dataSourceId, long supplierCode) {
    return {
        esClient.createIndex(keysService.getESKey(ESKeys.ESERPDATAPURVIEW_INDEX, supplierCode), ESKeys.INDEX_CONFIG,
                Utility.ofMap(ESKeys.ESERPDEFAULT_TYPE, "dataPurview.json"))

        RMap params = ERPUtils.ofRMap("voidFlag", -1)
        ExecPageFlipper.execute(500, { PageFlipper p ->
            List<DataPurview> dataPurviewList = systemDao.selectDataPurview(params, p, dataSourceId, supplierCode)

            if (!dataPurviewList.isEmpty()) {
                //产品基本信息，存入es
                BulkRequestBuilder bulkRequest = esClient.getClient().prepareBulk()
                dataPurviewList.forEach((x) -> {
                    IndexRequestBuilder indexRequest = esClient.getClient()
                            .prepareIndex(keysService.getESKey(ESKeys.ESERPDATAPURVIEW_INDEX, supplierCode), ESKeys.ESERPDEFAULT_TYPE)
                            .setId(x.getIdData() + "_" + x.getIdUser() + "_" + x.getIdCreateUser())
                            .setSource(jsonConvert.convertTo(x), XContentType.JSON)
                    bulkRequest.add(indexRequest)
                })
                BulkResponse bulkResponse = bulkRequest.execute().actionGet()

                if (bulkResponse.hasFailures()) {
                    logger.error("索引数据权限出错：" + bulkResponse.buildFailureMessage())
                } else {
                    logger.info("索引数据权限,共" + dataPurviewList.size() + "条记录")
                }
            }
        })
    } as Runnable
}

//groovy最后一个表达式的值为返回
createRunnable(keysService, esClient, systemDao, jsonConvert, logger, dataSourceId, supplierCode)



