import com.sdtool.business.dao.DesignDao
import com.sdtool.common.api.NoSqlKeysService
import com.sdtool.common.datas.RedisKeys
import com.dySweetFishPlugin.redis.RedisService
import com.sdtool.common.entity.design.DesignOrder
import com.sdtool.common.entity.design.DesignOrderItem
import com.sdtool.common.entity.design.DesignTemplate
import com.sdtool.common.entity.design.DesignTemplateItem
import com.sweetfish.convert.json.JsonConvert
import com.sweetfish.source.PageFlipper
import org.apache.commons.lang3.StringUtils
import org.apache.logging.log4j.Logger
import org.rex.RMap

import java.nio.file.Files
import java.nio.file.Paths

/**
 * @Author: xl Created on 2024-05-11
 * @Content:
 */

static def createRunnable(RedisService redisService, NoSqlKeysService keysService,
                          DesignDao designDao, Logger logger, JsonConvert jsonConvert, String dataSourceId, long supplierCode) {
    RMap params = new RMap()
    return {
        redisService.del(keysService.getRedisKey(RedisKeys.KEY_DESIGNER_DESIGN_ORDER_EDIT, supplierCode))
        redisService.del(keysService.getRedisKey(RedisKeys.KEY_DESIGNER_DESIGN_ORDER_IMPOSITION, supplierCode))
        Ignore_ExecPageFlipper.execute(1000, { PageFlipper p ->
            List<DesignOrder> orders = designDao.selectDesignOrders(params, dataSourceId, supplierCode, p)

            if (!orders.isEmpty()) {
                orders.each {
                    if (StringUtils.isNotEmpty(it.jsonContent)) {
                        File file = new File(it.jsonContent)
                        if (file.exists()) {
                            String content = new String(Files.readAllBytes(Paths.get(it.jsonContent)), "UTF-8")
                            it.setJsonContent(content)
                        }
                    }
                }
                Map<String, String> redisMap = orders.collectEntries { [String.valueOf(it.getId()), jsonConvert.convertTo(it)] }
                redisService.hmset(keysService.getRedisKey(RedisKeys.KEY_DESIGNER_DESIGN_ORDER_EDIT, supplierCode), redisMap)

                RMap itemParams = new RMap()
                orders.each {
                    itemParams.set("idOrder", it.id)
                    List<DesignOrderItem> itemList = designDao.selectDesignOrderItems(itemParams, dataSourceId, supplierCode)
                    it.setItemList(itemList)
                    it.setJsonContent("")
                }
                redisMap = orders.collectEntries { [String.valueOf(it.getId()), jsonConvert.convertTo(it)] }
                redisService.hmset(keysService.getRedisKey(RedisKeys.KEY_DESIGNER_DESIGN_ORDER_IMPOSITION, supplierCode), redisMap)

                logger.info("设计订单共" + orders.size() + "条记录")
            }
        })
    } as Runnable
}

createRunnable(redisService, keysService, designDao, logger, jsonConvert, dataSourceId, supplierCode)