package com.ecep.contract.service;

import java.time.Instant;

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.model.CloudTyc;
import com.ecep.contract.model.Company;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.CloudTycInfoViewModel;

import javafx.application.Platform;

@Service
public class CloudTycService extends QueryService<CloudTyc, 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();
        CloudTyc cloudTyc = findById(infoId);
        if (cloudTyc == null) {
            return;
        }
        if (viewModel.copyTo(cloudTyc)) {
            cloudTyc.setLatestUpdate(Instant.now());
            CloudTyc 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 CloudTyc getOrCreateCloudTyc(Company company) {
        throw new UnsupportedOperationException("Unimplemented method 'getOrCreateCloudTyc'");
    }
}
