package com.ylcm.sys.dto;

import com.ylcm.sys.common.ProjectUtil;
import com.ylcm.sys.domain.AdTheatre;
import com.ylcm.sys.form.AdTheatreAnalysisDetailQueryForm;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import net.sf.cglib.core.Local;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Data
public class AdTvQueryDTO {

    @ApiModelProperty("剧名")
    private String name;

    @ApiModelProperty(value = "媒体")
    private String mediaName;

    private String startDate;

    private String endDate;

    private String timeQuery;

    private String startTime;

    private String endTime;

    public static AdTvQueryDTO from(AdTheatreAnalysisDetailQueryForm queryForm) {
        AdTvQueryDTO queryDTO = new AdTvQueryDTO();
        BeanUtils.copyProperties(queryForm, queryDTO);

        if (queryForm.getTheatreTime() != null) {
            List<LocalTime> localTimes = ProjectUtil.getLocalTimeByType(queryForm.getTheatreTime());
            queryDTO.setStartTime(localTimes.get(0).format(DateTimeFormatter.ofPattern("HH:mm:ss")));
            queryDTO.setEndTime(localTimes.get(1).format(DateTimeFormatter.ofPattern("HH:mm:ss")));

            if (!localTimes.get(0).format(DateTimeFormatter.ISO_TIME).equals(ProjectUtil.MORNING_STR)) {
                queryDTO.setTimeQuery(String.format("b.show_time >= '%s' AND b.show_time < '%s' ", localTimes.get(0), localTimes.get(1)));
            } else {
                queryDTO.setTimeQuery(String.format("( (b.show_time >='%s' ) or (b.show_time < '%s'))", localTimes.get(0), localTimes.get(1)));
            }
        }


        if (StringUtils.isNotBlank(queryForm.getSeason())){
            List<LocalDate> season = ProjectUtil.getLocalDateByString(queryForm.getSeason());
            // 开始时间
            if (StringUtils.isNotBlank(queryForm.getStartDate())) {
                LocalDate startDate = LocalDate.parse(queryForm.getStartDate(), DateTimeFormatter.ISO_DATE);
                if (startDate.compareTo(season.get(0)) < 0) {
                    queryDTO.setStartDate(season.get(0).format(DateTimeFormatter.ISO_DATE));
                }
            } else {
                queryDTO.setStartDate(season.get(0).format(DateTimeFormatter.ISO_DATE));
            }
            // 截至时间
            if (StringUtils.isNotBlank(queryForm.getEndDate())) {
                LocalDate endDate = LocalDate.parse(queryForm.getEndDate(), DateTimeFormatter.ISO_DATE);
                if (endDate.compareTo(season.get(1)) > 0) {
                    queryDTO.setEndDate(season.get(1).format(DateTimeFormatter.ISO_DATE));
                }
            } else {
                queryDTO.setEndDate(season.get(1).format(DateTimeFormatter.ISO_DATE));
            }
        }

        return queryDTO;
    }
}
