package com.ecep.contract.service;

import java.time.LocalDateTime;

import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.DesktopUtils;
import com.ecep.contract.SpringApp;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.CloudTycInfoViewModel;
import com.ecep.contract.vo.CloudTycVo;
import com.ecep.contract.vo.CompanyVo;

import javafx.application.Platform;

@Service
public class CloudTycService extends QueryService<CloudTycVo, CloudTycInfoViewModel> {
    /**
     * 天眼查报告，文件名中必须包含 天眼查 字样
     *
     * @param fileName 文件名
     * @return 是否是天眼查报告
     */
    public static boolean isTycReport(String fileName) {
        // 文件名中包含 天眼查 字样
        return fileName.contains(CloudServiceConstant.TYC_NAME);
    }

    public void save(CloudTycInfoViewModel viewModel) {
        int infoId = viewModel.getId().get();
        CloudTycVo cloudTyc = findById(infoId);
        if (cloudTyc == null) {
            return;
        }
        if (viewModel.copyTo(cloudTyc)) {
            cloudTyc.setLatestUpdate(LocalDateTime.now());
            CloudTycVo saved = save(cloudTyc);
            Platform.runLater(() -> viewModel.update(saved));
        }
    }

    public void showInBrowse(String cloudId) {
        String baseUrl = SpringApp.getBean(SysConfService.class).getString("cloud.tyc.company");
        if (!StringUtils.hasText(baseUrl)) {
            UITools.showAlertAndWait("系统参数 cloud.tyc.company 未配置");
            return;
        }

        String url = baseUrl + cloudId;

        DesktopUtils.showInBrowse(url);

        // UITools.showExceptionAndWait("使用浏览器打开网址出现异常", e);

    }

    public CloudTycVo getOrCreateCloudTyc(CompanyVo company) {
        CloudTycVo cloudTyc = findByCompany(company);
        if (cloudTyc == null) {
            cloudTyc = new CloudTycVo();
            cloudTyc.setCompanyId(company.getId());
            cloudTyc.setCloudId("");
            cloudTyc.setScore(0);
            cloudTyc.setActive(false);
            cloudTyc.setVersion(1);
            cloudTyc = save(cloudTyc);
        }
        return cloudTyc;
    }

    public CloudTycVo findByCompany(CompanyVo company) {
        return findAll(ParamUtils.builder().equals("company", company.getId()).build(), Pageable.ofSize(1)).stream()
                .findFirst().orElse(null);
    }

}
