package com.docus.server.archive.controller;

import com.docus.infrastructure.web.api.CommonResult;
import com.docus.server.archive.entity.TBasic;
import com.docus.server.archive.job.MmRyOrderIndexSyncJob;
import com.docus.server.archive.mapper.TBasicMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author YongBin Wen
 * @date 2024/3/8 15:21
 */
@Slf4j
@RequestMapping("/mmry-collect")
@Api(tags = "茂名人医同步接口")
@RestController
public class MmRySyncController {
    @Resource
    private MmRyOrderIndexSyncJob orderIndexSyncJob;

    @ApiOperation(value = "根据时间进行同步医嘱序号 yyyy-MM-dd HH:mm:ss")
    @GetMapping("/sync/orderIndex")
    public CommonResult<String> syncOrderIndex(@RequestParam("dateTime") String dateTime) {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        int patternLen = pattern.length();
        if (dateTime.length() != patternLen) {
            return CommonResult.failed("请传入正确的时间格式 yyyy-MM-dd HH:mm:ss");
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            sdf.parse(dateTime);
        } catch (Exception ex) {
            return CommonResult.failed("请传入正确的时间格式 yyyy-MM-dd HH:mm:ss");
        }
        TBasicMapper tBasicMapper = orderIndexSyncJob.gettBasicMapper();
        int offset = 0;
        int size = 100;
        int total = 0;
        try {
            while (true) {
                List<TBasic> tBasicList = tBasicMapper.getBasicByDate(dateTime, offset, size);
                int basicSize = tBasicList.size();
                total += basicSize;
                if (basicSize == 0) {
                    break;
                }
                for (TBasic basic : tBasicList) {
                    orderIndexSyncJob.mmRyOrderIndexSync(basic);
                }
                offset += size;
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return CommonResult.success("同步失败");
        }

        return CommonResult.success("同步完成,共同步患者条数：" + total);
    }


}
