package com.gitee.sop.admin.service.doc;

import com.gitee.sop.admin.common.support.ServiceSupport;
import com.gitee.sop.admin.common.user.User;
import com.gitee.sop.admin.common.util.CopyUtil;
import com.gitee.sop.admin.dao.entity.DocApp;
import com.gitee.sop.admin.dao.mapper.DocAppMapper;
import com.gitee.sop.admin.service.doc.dto.DocAppDTO;
import com.gitee.sop.admin.service.doc.dto.torna.TornaModuleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author 六如
 */
@Service
public class DocAppService implements ServiceSupport<DocApp, DocAppMapper> {

    @Autowired
    private TornaClient tornaClient;

    @Autowired
    private DocInfoService docInfoService;
    @Autowired
    private DocInfoSyncService docInfoSyncService;

    public Long addDocApp(String token, User user) {
        TornaModuleDTO tornaModuleDTO = tornaClient.execute("module.get", null, token, TornaModuleDTO.class);
        DocApp docApp = this.get(DocApp::getToken, token);
        if (docApp == null) {
            docApp = new DocApp();
            docApp.setAppName(tornaModuleDTO.getName());
            docApp.setToken(token);
            this.save(docApp);
        } else {
            docApp.setAppName(tornaModuleDTO.getName());
            this.update(docApp);
        }
        // 同步文档
        docInfoSyncService.syncDocInfo(docApp, null, user);
        return docApp.getId();
    }

    public List<DocAppDTO> listDocApp() {
        List<DocApp> docApps = this.listAll();
        return CopyUtil.copyList(docApps, DocAppDTO::new);
    }

}
