<template>
    <div style="width: 98%;display: flex;align-items: center;justify-content: space-between;padding-top: 1%;margin-left: 1%;">
        <div style="font-size: 20px;"> 
            模型应用
        </div>
        <div style="display: flex;">
            <el-input size="mini" v-model="dcName" style="width: 100%;margin-left: 1%;" placeholder="搜索项目"/>
            <el-button type="primary" @click="showAdd" size="mini" style="margin-left:5%;" :icon="Plus">新增 </el-button>
        </div>
    </div>
    <div style="width: 98%;display: flex;align-items: center;justify-content: space-between;padding-top: 1%;margin-left: 1%;">
        <el-select
        v-model="formJi"
        class="noBorSel"
        placeholder="全部"
        style="width: 10%;margin-left: 0%;"
        >
            <el-option label="全部" :value="1" />
            <el-option label="已发布" :value="2" />
        </el-select>
    </div>
    <div style="height: 70vh;width: 98%;margin-left:1%;background-color: transparent;margin-top: 1%;display: flex;flex-wrap: wrap;justify-content: flex-start;gap: 0.65%">
        <div  v-for="(item,index) in modelList">
            <div class="coz-card" @mouseenter="setHoverIndex(index)" @click="goFlow(item)" style="cursor: pointer;"  @mouseleave="resetHoverIndex">
                <div style="display: flex;width: 100%;">
                    <div style="margin-left: 8%;margin-top: 5%;width: 60%;">
                        {{ item.appTitle }}
                    </div>
                    <img style="width: 90px;height: 90px;margin-left: 0%;margin-top: 8%;border-radius: 12px;" :src="item.appIcon" alt="">
                </div>
                <div>
                    <el-tag style="margin-left: 8%;margin-top: -1%;">应用</el-tag>
                </div>
                <div style="display: flex;align-items: center;margin-left: 8%;margin-top: 3%;line-height: 1.5;width: 85%;">
                    <img style="width: 4%;height: 4%;border-radius: 12px;" src="@/assets/images/touxiang.png" alt="">
                    <div style="margin-left: 3%;font-size: 12px;">
                        创建人：{{ item.createBy }} 更新时间：{{item.createTime}}
                    </div>
                    <el-icon style="color: #79bbff;margin-left: auto;cursor: pointer;" @click.stop="editModel(item)" v-if="hoverIndex === index"><Edit /></el-icon>
                    <el-icon style="color: red;margin-left: 2%;cursor: pointer;" @click.stop="delModel(item)" v-if="hoverIndex === index"><Delete /></el-icon>
                </div>
            </div>
        </div>
    </div>
    <el-pagination
    v-if="total>12"
    small
    background
    style="margin-top: 0.8%;float: right;margin-right: 1%;"
    layout="prev, pager, next"
    :total="total"
    v-model="pageNum"
    @change="changePage"
    class="mt-4"
  />
    <el-dialog
        :title="title"
        v-model="isContentVisible"
        width="30%"
    >
        <div>
            <el-form ref="formAddref" :model="formAdd" label-width="100px" class="coz-mg-card" :rules="rulesAdd">
                <el-form-item label="模型名称:" prop="appTitle">
                    <el-input v-model="formAdd.appTitle" placeholder="请输入应用名称"></el-input>
                </el-form-item>
                <el-form-item label="模型描述:" prop="appNote">
                    <el-input type="textarea" v-model="formAdd.appNote" placeholder="请输入应用描述"></el-input>
                </el-form-item>
                <el-form-item label="图标:">
                    <div style="display: flex;width: 100%;">
                        <img v-if="!previewUrl" style="width: 80px;height:80px;margin-left: 0%;margin-top: 0%;border-radius: 12px;" src="@/assets/images/defaultModel.png" alt="">
                        <img v-if="previewUrl" style="width: 80px;height:80px;margin-left: 0%;margin-top: 0%;border-radius: 12px;" :src="previewUrl" alt="">
                    </div>
                    <el-upload
                            ref="uploadRef"
                            style="margin-top: 3%;"
                            :limit="1"
                            :show-file-list="false"
                            :file-list="fileList"
                            :headers="upload.headers"
                            :on-progress="handlepro"
                            :on-success="handleFileSuccess"
                            :on-change="handleChange"
                            :action="upload.url + '?file=' + upload.updateSupport"
                            :auto-upload="false"
                        >
                        <el-button @click="clearDefault" plain type="primary" size="mini" style="margin-left:auto;width: 80px;" :icon="Upload">上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <el-button @click="isContentVisible = false">取消</el-button>
            <el-button v-if="isAdd" type="primary" @click="submitAdd">确定</el-button>
            <el-button v-if="!isAdd" type="primary" @click="subEdit">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup>

import { onMounted, ref } from 'vue'
import { Search,RefreshRight,Plus,Download,Upload,Delete,Setting,Minus} from '@element-plus/icons-vue'
import { getModellist,addModeling,delModeling,editModeling,getModelingDe } from '@/api/standardization/modeling'
import { getToken } from '@/utils/auth'
import imagePath from '@/assets/images/defaultModel.png';
import { useStore } from 'vuex';
import { computed } from 'vue';
const { proxy } = getCurrentInstance();
const title = ref()
const heightAll = window.innerHeight
const isContentVisible = ref(false)
const isAdd = ref(true)
const pageNum = ref(1)
const modelList = ref([])
const total = ref(0)
const hoverIndex = ref(-1)
const uploadRef = ref()
const fileList = ref([
]);
const formAdd = ref({
    appTitle: '',
    appNote: '',
});
const formAddref = ref()

const rulesAdd = reactive({
  appTitle: [{ required: true, message: '必填', trigger: 'blur' }], 
  appNote: [{ required: true, message: '必填', trigger: 'blur' }], 
});
const parModel = ref({})
const parFile = ref({})
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: '',
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
});
const previewUrl = ref()

const store = useStore();
const setHoverIndex = (index) => {
  hoverIndex.value = index;
};

const resetHoverIndex = () => {
  hoverIndex.value = -1;
};
function goFlow(item){
    store.commit('setId', item.appId);
    proxy.$router.push({ path: '/standardization/modeling' });
}
function editModel(item){
    parModel.value = item
    isAdd.value = false
    isContentVisible.value = true
    title.value = '修改模型应用'
    getModelingDe(item.appId).then(res => {
        if(res.code === 200){
            formAdd.value.appTitle = res.data.appTitle
            formAdd.value.appNote = res.data.appNote
            formAdd.value.appId = res.data.appId
            previewUrl.value = res.data.appIcon ? res.data.appIcon : imagePath;
        } else {
            proxy.$message.error('获取模型详情失败');
        }
    }).catch(() => {
        proxy.$message.error('获取模型详情失败');
    });
}
function subEdit(){
    if(!parFile.value){
        formAddref.value.validate(async (valid) => {
        if(valid){
                formAdd.value.appIcon = '/profile/upload/2025/08/20/defaultModel_20250820173415A032.png'
                    editModeling(formAdd.value).then(res => {
                    if(res.code === 200){
                        proxy.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                        isContentVisible.value = false;
                        getList();
                    }
                })
            }
        })
    }
    else{
        formAddref.value.validate(async (valid) => {
            if(valid){
                nextTick(() => {
                    uploadRef.value.submit();
                });
            }
        })
    }
}
function delModel(item){
    proxy.$confirm('是否删除该模型应用？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delModeling(item.appId).then(res => {
            if(res.code === 200){
                proxy.$message({
                    message: '删除成功',
                    type: 'success'
                });
                getList();
            } else {
                proxy.$message.error('删除失败');
            }
        })
      }).catch(() => {
        
      });
}
function submitAdd(){
    if(!parFile.value){
        formAddref.value.validate(async (valid) => {
        if(valid){
                formAdd.value.appIcon = '/profile/upload/2025/08/20/defaultModel_20250820173415A032.png'
                    addModeling(formAdd.value).then(res => {
                    if(res.code === 200){
                        proxy.$message({
                            message: '新增成功',
                            type: 'success'
                        });
                        isContentVisible.value = false;
                        getList();
                    } else {
                        proxy.$message.error('新增失败');
                    }
                })
            }
        })
        
    }
    else{
        formAddref.value.validate(async (valid) => {
            if(valid){
                nextTick(() => {
                    uploadRef.value.submit();
                });
            }
        })
    }
    
}
function handleFileSuccess(response, file, fileList){
    console.log("上传成功的响应:", response);
    if(response.code===200){
        if(isAdd.value===true){
            formAdd.value.appIcon = response.fileName
            addModeling(formAdd.value).then(res => {
                if(res.code === 200){
                    proxy.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    isContentVisible.value = false;
                    getList();
                } else {
                    proxy.$message.error('新增失败');
                }
            }).catch(() => {
                proxy.$message.error('新增失败');
            }); 
        }
        else{
            formAdd.value.appIcon = response.fileName
            editModeling(formAdd.value).then(res => {
                if(res.code === 200){
                    proxy.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    isContentVisible.value = false;
                    getList();
                } else {
                    proxy.$message.error('修改失败');
                }
            }).catch(() => {
                proxy.$message.error('修改失败');
            });
        }
    }
};
function clearDefault(){
    uploadRef.value.clearFiles(); 
}
function handleChange(file, fileList){
    console.log(file, fileList)
    parFile.value = file
    const rawFile = file.raw;
    previewUrl.value = URL.createObjectURL(rawFile);
}
function showAdd(){
    isAdd.value = true
    isContentVisible.value = true
    title.value = '新增模型应用'
}
function changePage(val) {
    console.log(val)
    pageNum.value = val,
    getList()
}
function getList() {
    var par = {
        pageSize: 12, 
        pageNum: pageNum.value,
    }
    getModellist(par).then(response => {
        modelList.value = response.rows
        total.value = response.total
    })
}
onMounted(() => {
    getList()
})
</script>

<style scoped>
:deep(.el-upload .el-upload--picture-card) {
  height: 100px !important;
  width: 100px !important;
}
.coz-card {
  margin-top: 5%;
  height: 20vh;
  width: 24vw;
  border-radius: 6px;
  border: 1px solid;
  border-style: solid;
  overflow: hidden;
  border-color: #e9e9eb;
  transition: all 150ms ease-out;
}
.coz-card:hover {
  box-shadow: 0 10px 12px 0 rgba(28, 31, 35, 0.06);
}
/* 自定义类名需保留 */
.coz-stroke-primary {
  stroke: var(--primary-color); /* 需替换为实际颜色值 */
}
.coz-mg-card {
  margin: 10px; /* 根据实际需求调整 */
}

</style>