package thyyxxk.webserver.controller.coordinatecleaning;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.dao.his.reports.PatientDistributionAddressDao;
import thyyxxk.webserver.entity.inpatient.patient.Patient;
import thyyxxk.webserver.utils.BaiduMapGeocoderUtil;
import thyyxxk.webserver.utils.ListUtil;
import thyyxxk.webserver.utils.StringUtil;

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

@RestController
@Slf4j
@RequestMapping("/updatePatientLatitudeAndLongitude")
public class UpdatePatientLatitudeAndLongitudeController {
    private final PatientDistributionAddressDao dao;

    public UpdatePatientLatitudeAndLongitudeController(PatientDistributionAddressDao dao) {
        this.dao = dao;
    }

    /**
     * 每天一点执行定时任务
     * 患者地址转坐标
     */

    @GetMapping("/start")
    @PassToken
    public void start() {
        String tableName = "a_patient_mi";
        String patNo = "inpatient_no";
        List<Patient> list = dao.timedTaskPatientData();

        if (ListUtil.isBlank(list)) {
            tableName = "mz_patient_mi";
            patNo = "patient_id";
            list = dao.mzTimedTaskPatientData();
        }

        if (ListUtil.isBlank(list)) return;

        for (Patient patient : list) {
            if (StringUtil.notBlank(patient.getHomeStreet())) {
                String[] address = BaiduMapGeocoderUtil.getlocation(patient.getHomeStreet());
                if (address == null) {
                    patient.setAddrTransedFlag(1);
                    patient.setLatitude(null);
                    patient.setLongitude(null);
                } else {
                    patient.setAddrTransedFlag(0);
                    patient.setLongitude(new BigDecimal(address[0]));
                    patient.setLatitude(new BigDecimal(address[1]));
                }
                log.info("住院号:{},地址:{},经度:{},纬度:{}", patient.getInpatientNo(),
                        patient.getHomeStreet(),
                        patient.getLongitude(), patient.getLatitude());
            }
        }

        List<List<Patient>> performAnUpdate = ListUtils.partition(list, 50);

        for (List<Patient> patients : performAnUpdate) {
            dao.updatePatientAddress(patients, tableName, patNo);
        }

    }

}

