package cn.myapps.runtime.dynaform.form.controller;

import java.sql.Connection;
import java.util.Collection;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import cn.myapps.common.controller.Resource;
import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.datasource.DataSource;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.runtime.common.controller.AbstractRuntimeController;
import cn.myapps.runtime.common.dao.WrapConnection;
import cn.myapps.runtime.dynaform.form.ejb.Form;
import cn.myapps.runtime.dynaform.form.ejb.FormTableProcess;
import cn.myapps.runtime.dynaform.form.ejb.FormTableProcessBean;
import cn.myapps.runtime.dynaform.form.service.FormRunTimeService;
import cn.myapps.util.RuntimeDaoManager;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = {"/api/runtime"})
@Scope("prototype")
@Api(tags = "表单同步模块")
public class FormSynController extends AbstractRuntimeController {

    @Autowired
    private FormRunTimeService formRunTimeService;

    //同步表单
    /**
     * 同步数据表单
     *
     * @param applicationId 软件id
     * @return
     * @throws Exception
     */
    @PostMapping("/synchronization/forms")
    @ApiOperation(value = "同步数据表单", notes = "同步数据表单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "applicationId", value = "软件id", required = true, paramType = "query", dataType = "string")

    })
    public Resource syncDataForm(@RequestParam String applicationId) throws Exception {
        try {
            StringBuffer synFormError = new StringBuffer();
            //开个线程进行同步
            new Thread(new Runnable() {
                public void run() {
                    Thread.currentThread().setName("syncDataFormThread");
                    try {
                        ApplicationDesignTimeService applicationService = DesignTimeServiceManager.applicationDesignTimeService();
                        Application application = applicationService.findById(applicationId);
                        //生成软件库的系统表
                        DataSource dataSourceDefine = application.getDataSourceDefine();
                        Connection conn = dataSourceDefine.getConnection();
                        RuntimeDaoManager.getApplicationInitDAO(new WrapConnection(dataSourceDefine.getSqlDataSource(), conn, null, application.getApplicationid()), dataSourceDefine.getDbTypeName())
                                .initTables();
                        //生成软件库的表单tlk...
                        Collection<Form> forms = formRunTimeService.getFormsByApplication(application.getId());
                        FormTableProcess tableProcess = new FormTableProcessBean(application.getId());
                        for(Form form : forms){
                            try{
                                tableProcess.createOrUpdateDynaTable(form, null);
                            }catch (Exception e){
                                e.printStackTrace();
                                synFormError.append("同步"+form.getName()+"表时报错"+e.getMessage()+",");
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            PersistenceUtils.closeSessionAndConnection();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            return success("ok", synFormError.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return error(500, e.getMessage(), null);
        }
    }
    /**
     * 获取同步表单状态
     * @return
     * @throws Exception
     */
    @GetMapping("/synchronization/forms/status")
    @ApiOperation(value = "获取同步表单状态", notes = "获取同步表单状态")
    public Resource getSyncFromStatus() throws Exception {
        try {
            Thread thread = getThreadByName("syncDataFormThread");
            String msg = "正在同步中";
            if(thread == null){
                msg = "同步成功";
            }
            return success("ok", msg);
        } catch (Exception e) {
            e.printStackTrace();
            return error(500, e.getMessage(), null);
        }
    }

    /**
     * 根据线程名称获取线程
     * @param threadName
     * @return
     */
    public Thread getThreadByName(String threadName) {
        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().equals(threadName)) {
                System.out.println(t.getName());
                return t;
            }
        }
        return null;
    }
}
