<template>
    <el-dialog draggable  v-model="dialogVisible" :title="title" width="450px" top="20vh">
        <el-scrollbar>
            <el-form :inline="false" :model="form" label-width="120px" :rules="rules" ref="formRef">
                <el-form-item label="终端" prop="deviceId">
                    <el-tree-select
                        v-model="form.deviceId"
                        :data="data"
                        filterable
                        :filter-node-method="filterNode"
                        style="width: 100%"
                        @change="changeDevStatus"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="终端当前状态:">
                    <el-select v-model="runFlag" disabled placeholder="请选择终端" clearable class="select" filterable>
                        <el-option
                            v-for="item in devStatusList"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="变更状态:" prop="devStatus">
                    <el-select v-model="form.devStatus" placeholder="请选择终端状态" clearable class="select" filterable>
                        <el-option
                            v-for="item in devStatuData"
                            :key="item.value"
                            :label="item.name"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="变更原因" prop="propertyNo">
                    <el-input
                        type="textarea"
                        clearable
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        placeholder="请输入变更原因"
                        v-model="form.propertyNo"
                    ></el-input>
                </el-form-item>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <!-- <el-button type="primary" @click="submit">确认</el-button> -->
                <el-button type="primary" @click="submit(true)" :loading="loading" >保存</el-button>
                <el-button type="primary" @click="submit(false)" :loading="loading" >提交审批</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { ElMessage } from 'element-plus'
import TableStore from '@/utils/tableStore' // 若不是列表页面弹框可删除
import { getTerminalSelectTree } from '@/api/device-boot/Business'
import { addRunningDevice, quitRunningDeviceUpdate } from '@/api/supervision-boot/device/quitRunningDev'
import { getDeviceDetailData } from '@/api/device-boot/line'
import { defaultProps } from '@/utils/tree'
const devStatusList = ref([
    { name: '运行', value: '0' },
    { name: '检修', value: '1' },
    { name: '退运', value: '4' }
])
//下拉数据源
const sourceData = ref()
const deviceList = ref()
const data = ref()
const title = ref('')
const loading = ref(false)
const tableStore = inject('tableStore') as TableStore
const formRef = ref()
const devStatuData: any = ref([])

const dialogVisible = ref(false)
const runFlag = ref('')
// 注意不要和表单ref的命名冲突
const form = ref({
    id: '',
    deviceId: '',
    deviceType: '1',
    devOriginalStatus: '0',
    devStatus: '',
    propertyNo: '',
    saveOrCheckflag: ''
})

//form表单校验规则
const rules = {
    deviceId: [{ required: true, message: '终端不能为空', trigger: 'change' }],
    devStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
    propertyNo: [{ required: true, message: '请输入退役原因', trigger: 'blur' }]
}
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}
const filterNode = (value: string, data: any, node: any) => {
    if (!value) return true

    if (data.label) {
        return chooseNode(value, data, node)
    }
}

// 过滤父节点 / 子节点 (如果输入的参数是父节点且能匹配，则返回该节点以及其下的所有子节点；如果参数是子节点，则返回该节点的父节点。label是中文字符，enlabel是英文字符.
const chooseNode = (value: string, data: any, node: any) => {
    if (data.label.indexOf(value) !== -1) {
        return true
    }
    const level = node.level
    // 如果传入的节点本身就是一级节点就不用校验了
    if (level === 1) {
        return false
    }
    // 先取当前节点的父节点
    let parentData = node.parent
    // 遍历当前节点的父节点
    let index = 0
    while (index < level - 1) {
        // 如果匹配到直接返回，此处label值是中文字符，enlabel是英文字符。判断匹配中英文过滤
        if (parentData.data.label.indexOf(value) !== -1) {
            return true
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent
        index++
    }
    // 没匹配到返回false
    return false
}

const open = async (text: string, tempData?: any) => {
    title.value = text
    //终端
    await getTerminalSelectTree(4).then(res => {
        deviceList.value = res.data
    })
    sourceData.value = deviceList.value
    data.value = deviceList.value
    if (tempData) {
        // 表单赋值
        for (let key in form.value) {
            form.value[key] = tempData[key]
        }
        form.value.deviceType = form.value.deviceType + ''
        changeDevStatus(form.value.deviceId, true)
        form.value.devStatus = tempData.devStatus != null ? tempData.devStatus + '' : ''
    } else {
        resetForm()
        // 在此处恢复默认表单
        for (let key in form.value) {
            form.value[key] = ''
        }
        runFlag.value = ''
        form.value.deviceType = '1'
    }
    form.value.deviceType = '1'

    // changeType(form.value.deviceType)
    dialogVisible.value = true
}

/**
 * 提交用户表单数据
 */
const submit =async (flag: boolean) => {
    loading.value = true
    if (flag) {
        form.value.saveOrCheckflag = '1'

        await  addRunningDevice(form.value).then(res => {
            ElMessage.success('保存成功!')
            tableStore.index()
            dialogVisible.value = false
        })
    } else {
        formRef.value.validate(async (valid: any) => {
            if (valid) {
                form.value.saveOrCheckflag = '2'
                if (form.value.devOriginalStatus == form.value.devStatus) {
                    if (form.value.devOriginalStatus == '0') {
                        ElMessage.warning('终端当前状态就是运行，无需变更!')
                    } else if (form.value.devOriginalStatus == '1') {
                        ElMessage.warning('终端当前状态就是检修，无需变更!')
                    } else {
                        ElMessage.warning('终端当前状态就是退运，无需变更!')
                    }
                } else {
                    if (form.value.id) {
                        await quitRunningDeviceUpdate(form.value).then(res => {
                            ElMessage.success('重新发起成功')
                            tableStore.index()
                            dialogVisible.value = false
                        })
                    } else {
                        await addRunningDevice(form.value).then(res => {
                            //查询进线数据，避免一直处于loading状态
                            ElMessage.success('申请成功')
                            tableStore.index()
                            dialogVisible.value = false
                        })
                    }
                }
            }
        })
    }
    await setTimeout(() => {
        loading.value = false
    }, 0)
}

/**
 * 终端类型切换
 */

const changeType = (event: any) => {
    sourceData.value = deviceList.value
    form.value.deviceId = ''
    data.value = sourceData.value
}

const changeDevStatus = async (event: any, flag?: boolean) => {
    await getDeviceDetailData(event).then(res => {
        //给当前终端赋值初始运行状态
        runFlag.value = res.data.runFlag + ''
        form.value.devOriginalStatus = runFlag.value
        if (!flag) form.value.devStatus = ''
        devStatuData.value = devStatusList.value.filter(item => item.value != res.data.runFlag)
    })
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.el-upload-list__item {
    transition: none !important;
}

.el-select {
    min-width: 180px;
}
::v-deep .el-tree-node__children > div {
    display: block !important;
}
:deep(.el-select__input) {
    width: 100% !important;
}
</style>
