<template>
    <!-- 按钮 -->
    <div style="margin: 50px 50px">
        <el-space :size="30">
            <el-button type="primary" icon="Finished" @click="handleCheck">校验</el-button>
            <el-button :type="flag === 1 ? 'info' : 'primary'" icon="SwitchButton" @click="handleOpen">启用同步</el-button>
            <el-button :type="flag === 1 ? 'primary' : 'info'" icon="CircleClose" @click="handleClose">关闭同步</el-button>
            <el-button type="primary" icon="Refresh" @click="handleManual">手动同步</el-button>
            <el-button type="primary" @click="handleSelected">导入 lic 文件</el-button>
            <input ref="uploadInput" type="file" style="display: none;" accept=".tmp" @change="submitUpload">
        </el-space>
    </div>

    <!-- 表单区域 -->
    <div style="margin: 100px 40% 0 10%">
        <el-form ref="ruleFormRef" :rules="rules" :model="sybchronizationForm" :disabled="isDisabled"
            label-position="right" label-width="155px" class="demo-ruleForm" style="margin-top: 50px">
            <el-row>
                <el-col :span="24">
                    <el-col :span="24">
                        <el-form-item label="第三方地址：" prop="thirdPartyUrl">
                            <el-input v-model="sybchronizationForm.thirdPartyUrl" placeholder="请输入第三方地址：" clearable />
                        </el-form-item>
                    </el-col>
                    <el-form-item label="金蝶地址：" prop="k3CloudUrl">
                        <el-input v-model="sybchronizationForm.k3CloudUrl" placeholder="请输入金蝶地址：" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="账套ID：" prop="dbid">
                        <el-input v-model="sybchronizationForm.dbid" placeholder="请输入账套ID：" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="端口：" prop="lang">
                        <el-input v-model="sybchronizationForm.lang" placeholder="请输入端口：" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="账号：" prop="uid">
                        <el-input v-model="sybchronizationForm.uid" placeholder="请输入账号：" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="密码：" prop="pwd">
                        <el-input v-model="sybchronizationForm.pwd" type="password" placeholder="请输入密码：" clearable
                            show-password />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="间隔时间/分钟：" prop="duration">
                        <el-input type="number" v-model="sybchronizationForm.duration" placeholder="间隔时间：" clearable
                            @input="(val: any) => { if (val <= 0 || val >= 60) sybchronizationForm.duration = '' }" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item style="margin-left: 20%">
                        <el-button type="primary" icon="Download" @click="handleSave(ruleFormRef)">保存配置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import {
    getSynchronization,
    putSynchronization,
    getStart,
    getManual,
    getOff,
    getSRecords,
    getCheck,
    importFile
} from "@/services/api/systemApi/synchronization/synchronizationAPI";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const sybchronizationForm = ref({
    k3CloudUrl: "",
    thirdPartyUrl: '',
    dbid: "",
    lang: "",
    uid: "",
    pwd: "",
    duration: '',
});
// 校验规则
const rules = ref<FormRules>({
    k3CloudUrl: [{ required: true, message: "金蝶地址不为空", trigger: "blur" }],
    thirdPartyUrl: [{ required: true, message: "第三方地址不为空", trigger: "blur" }],
    dbid: [{ required: true, message: "数据库ID不为空", trigger: "blur" }],
    lang: [{ required: true, message: "端口不为空", trigger: "blur" }],
    uid: [{ required: true, message: "账号不为空", trigger: "blur" }],
    pwd: [{ required: true, message: "密码不为空", trigger: "blur" }],
    duration: [{ required: true, message: "间隔时间不为空, 且大于0 小于60", trigger: "blur" },]
});

const ruleFormRef = ref<FormInstance>();
const isDisabled = ref(true);

// 1、 启动 0、 关闭
const flag = ref()
const handleCheck = async () => {
    if (!isDisabled.value) {
        const res: any = await getCheck(sybchronizationForm.value)
        if (res.code === 200) {
            initSRecords()
            return ElMessage({ type: "success", message: "校验成功" });
        }
    } else return ElMessage({ type: "warning", message: "请先关闭同步" });
}

let uploadInput = ref()
// 点击导入文件
const handleSelected = () => uploadInput.value.click()


// //选好文件之后点击打开按钮
const submitUpload = (e: any) => {
    const files = e.target.files
    const rawFile = files[0]
    console.log(rawFile);
    if (!rawFile) return
    upload(rawFile)
}

//上传
const upload = (rawFile: any) => {
    uploadInput.value = null
    uploadSectionFile(rawFile)
    // if (!beforeUpload) return

    //检查文件是否满足条件
    // const before = this.beforeUpload(rawFile)
    // if (before) {
    //上传事件
    //     uploadSectionFile(this.uploadParams, rawFile)
    // }
}


// const beforeUpload = (file: any) => {
//     const isLt1M = file.size / 1024 / 1024 < 50

//     if (isLt1M) {
//         return true
//     }
//     console.log('上传文件不超过50M', 'warning')
//     return false
// }

const uploadSectionFile = (file: any, params?: any) => {
    // let data = params
    let fromData = new FormData()// FormData 对象
    let fileObj = file// 相当于input里取得的files
    console.log('file', fileObj);

    fromData.append('file', fileObj)// 文件对象
    console.log(fromData);

    importFile(fromData).then((res: any) => {
        //调用上传接口
        if (res.code === 200) {
            ElMessage({ type: 'success', message: '导入成功！' })
        }

    })
}

// 开启自动同步 
const handleOpen = async () => {
    // if (isDisabled.value === true) return;
    const res: any = await getStart();
    if (res.code === 200) {
        initSRecords()
        isDisabled.value = true
        return ElMessage({ type: "success", message: "自动启动成功" });
    }
};

// 关闭自动同步
const handleClose = async () => {
    // if (isDisabled.value === false) return;
    const res: any = await getOff();
    if (res.code === 200) {
        initSRecords()
        isDisabled.value = false
        return ElMessage({ type: "success", message: "关闭成功" });
    }
};
const handleManual = async () => {
    const res: any = await getManual()
    if (res.code === 200) {
        initSRecords()
        isDisabled.value = true
        ElMessage({ type: 'success', message: '手动同步成功' })
    }
};
// 保存配置
const handleSave = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            const res: any = await putSynchronization(sybchronizationForm.value);
            if (res.code === 200) {
                initSRecords()
                ElMessage({ message: "保存参数成功！", type: "success" });
            }
        } else {
            console.log("校验失败", fields);
            return false;
        }
    });
};


const initSRecords = () => {
    getSRecords().then((res: any) => {
        if (res.data.status === 1) isDisabled.value = true
        else isDisabled.value = false
        flag.value = res.data.status
        getSynchronization().then((res: any) => {
            if (res.code === 200) return sybchronizationForm.value = res.data;
        })
    })
}

initSRecords()
</script>

<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 40px;
}
</style>
