<template>
    <!-- 基础信息弹出框 -->
    <el-dialog :model-value="dialogVisible" :title="dialogTitle" v-bind="dialogSmall" @close="close" align-center>
        <div>
            <el-form :model="formContent" label-position="right" label-width="80" ref="dialogFormRef" :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formContent.name" placeholder="请输入icd名称" maxlength="32" show-word-limit />
                </el-form-item>
                <el-form-item label="存储地址" prop="path">
                    <el-input
                        v-model="formContent.path"
                        placeholder="请输入icd存储地址"
                        maxlength="32"
                        show-word-limit
                    />
                </el-form-item>
                <el-form-item label="映射文件" prop="mappingFile">
                    <el-upload
                        action="#"
                        :limit="1"
                        :on-change='MappingHandleChange'
                        :auto-upload="false"
                        :file-list="mappingFileList"
                        :on-exceed="MappingHandleExceed"
                        :on-remove="MappingHandleRemove"
                        style="width: 100% !important;"
                        accept=".txt"
                        class="upload-container"
                    >
                        <el-button type="primary">选择文件</el-button>
                    </el-upload>
                    仅支持上传大小不超过1MB的.txt文件
                </el-form-item>
                <el-form-item label="是否支持电压相角、电流相角指标" prop="angle" label-width="auto">
                    <el-switch
                        v-model="formContent.angle"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="是"
                        inactive-text="否"
                    />
                </el-form-item>
                <el-form-item label="角型接线时是否使用相别的指标来进行检测" prop="usePhaseIndex" label-width="auto">
                    <el-switch
                        v-model="formContent.usePhaseIndex"
                        :active-value="1"
                        :inactive-value="0"
                        inline-prompt
                        active-text="是"
                        inactive-text="否"
                    />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close()">取消</el-button>
                <el-button type="primary" @click="save()">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage, UploadFile, type FormInstance, type FormItemRule } from 'element-plus'
import { computed, ref, Ref } from 'vue'
import { type ICD } from '@/api/device/interface/icd'
import { dialogSmall } from '@/utils/elementBind'
import { useDictStore } from '@/stores/modules/dict'
import { addICD, updateICD } from '@/api/device/icd'

const dictStore = useDictStore()
// 定义弹出组件元信息
const dialogFormRef = ref()
const mappingFileName = ref('')
const mappingFileUrl = ref('')
let excelFormData = new FormData()


const mappingFileList = computed(() => {
  if (mappingFileName.value && mappingFileUrl.value) {
    return [{name: mappingFileName.value, url: mappingFileUrl.value}];
  }
  return [];
});
function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<ICD.ResICD>({
        id: '',
        name: '',
        path: '',
        state: 1,
        angle: 0,
        usePhaseIndex: 0,
        mappingFile: ''
    })
    return { dialogVisible, titleType, formContent }
}

const { dialogVisible, titleType, formContent } = useMetaInfo()

// 清空formContent
const resetFormContent = () => {
    formContent.value = {
        id: '',
        name: '',
        path: '',
        state: 1,
        angle: 0,
        usePhaseIndex: 0,
        mappingFile: ''
    }
}

let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增ICD' : '编辑ICD'
})

//定义规则
const formRuleRef = ref<FormInstance>()
//定义校验规则
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: 'icd名称必填！', trigger: 'blur' }],
    path: [{ required: true, message: 'icd存储地址必填！', trigger: 'blur' }],
    mappingFile: [{required: true, message: '请上传映射文件', trigger: 'change'}],
})

// 关闭弹窗
const close = () => {
    excelFormData = new FormData()
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
}

// 保存数据
const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                // 清空 excelFormData
                excelFormData.delete('name')
                excelFormData.delete('path')
                excelFormData.delete('angle')
                excelFormData.delete('usePhaseIndex')

                excelFormData.append('name', formContent.value.name)
                excelFormData.append('path', formContent.value.path)
                excelFormData.append('angle', formContent.value.angle)
                excelFormData.append('usePhaseIndex', formContent.value.usePhaseIndex)

                let baseFileFlag = handleFileLimit(excelFormData.get('mappingFile') as File)
                if (!baseFileFlag) {
                    return
                }

                if (formContent.value.id) {
                     excelFormData.append('id', formContent.value.id)
                    await updateICD(excelFormData)
                } else {
                    await addICD(excelFormData)
                }
                ElMessage.success({ message: `${dialogTitle.value}成功！` })
                close()
                // 刷新表格
                await props.refreshTable!()
            }
        })
    } catch (err) {
        //error('验证过程中出现错误', err)
    }
}

// 打开弹窗，可能是新增，也可能是编辑
const open = async (sign: string, data: ICD.ResICD) => {
    // 重置表单
    dialogFormRef.value?.resetFields()
    titleType.value = sign
    dialogVisible.value = true

    if (data.id) {
        formContent.value = { ...data }
        formContent.value.id = data.id
        // 文件信息回显
        if (data.mappingFile) {
            mappingFileName.value = data.mappingFile.name
            mappingFileUrl.value = data.mappingFile.url
            // 模拟文件列表显示
            formContent.value.mappingFile = data.mappingFile.name
        }
      

    } else {
        mappingFileName.value = ''
        mappingFileUrl.value = ''
        resetFormContent()
        // 清空 excelFormData
        excelFormData = new FormData();
    }
}

const MappingHandleChange = async (param: UploadFile) => {
  mappingFileName.value = param.name;
  mappingFileUrl.value = URL.createObjectURL(param.raw as Blob);
  excelFormData.append('mappingFile', param.raw as Blob, param.name);

  formContent.value.mappingFile = param.name;
};

const MappingHandleRemove = () => {
  excelFormData.delete('mappingFile');
  formContent.value.mappingFile = ''
};

const MappingHandleExceed = (files: File[]) => {
  // 移除旧文件
  excelFormData.delete('mappingFile');
  // 添加新文件
  if (files.length > 0) {
    const newFile = files[0] as unknown as UploadFile;
    mappingFileName.value = newFile.name;
    excelFormData.append('mappingFile', newFile as Blob, newFile.name);

    formContent.value.mappingFile = newFile.name
  }

};

const fileSizeLimit = 1 * 1024 * 1024; // 1MB

const handleFileLimit = (file: File) => {
  if (file) {
    if (file.size > fileSizeLimit) {
      ElMessage.error({message: `文件大小不能超过${fileSizeLimit / 1024 / 1024}MB`});
      return false;
    } else {
      return true;
    }
  }
  return true;
}

// 对外映射
defineExpose({ open })
const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined
}>()
</script>