<template>
    <div>
        <TableSearch :query="query" :options="searchOpt" :search="handleSearch" :refresh="getData" />
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                :delFunc="handleDelete" :changePage="changePage" :currentPage="page.index" :editFunc="handleEdit" :genOperate="handleGenOperate" :refresh="getData" :genOperateV2="handleGenOperateV2">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="visible_add = true">上传文件</el-button>
                </template>
            </TableCustom>

        </div>
        <el-dialog :title="isEdit ? '编辑': '编辑'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options_edit" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog :title="isAdd ? '上传' : '上传'" v-model="visible_add" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
           <UploadFile></UploadFile>
        </el-dialog>
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData"></TableDetail>
        </el-dialog>
        <div  v-if="code_edit">
            <transition name="fade">
                <div 
                    v-if="code_edit"
                    class="mask"
                    @click.self="code_edit = false"
                ></div>
                </transition>
                <slideCodeEdit v-model:content="code_edit_content" :fileID="edit_file_id"  :show="code_edit"  :fileName="edit_file_name" @close="closeFileEdit" @update="updateFileContent($event)"/>
        </div>
        
    </div>

    <el-dialog
        v-model="downloadFileVisible"
        title="下载文件"
        width="20%"
      > 
      <!-- 下载链接 -->
       <a :href="downloadFileUrl">点击下载</a>
    </el-dialog>

</template>

<script setup lang="ts" name="system-user">
import { ref, reactive } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { Session } from '@/types/session';
import {FindUserFileService} from "@/api/file";
import {UpdateUserFileService} from "@/api/file";
import {DelUserFileService, FindFileContentService} from "@/api/file";
import { File,fileUrl,fileUrl2 } from '@/types/file';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import UploadFile from '@/components/upload-file.vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import slideCodeEdit from './slide-code-edit.vue';


const page = reactive({
    index: 1,
    size: 10,
    total: 122,
})
const tableData = ref<File[]>([]);
const allData = ref<File[]>([]);
const downloadFileVisible = ref(false);
const downloadFileUrl = ref('');
const code_edit = ref(false);
const code_edit_content = ref('');
const edit_file_name = ref('');
const edit_file_id = ref(0);

// 查询相关
const query = reactive({
    name: '',
});
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '文件名：', prop: 'name' }
])
const handleSearch = async () => {
    // if (isFinite(query.name) == false){
    //     ElMessage.error("请输入正确的会话ID");
    //     return;
    // }
    let req={
        token: localStorage.getItem('token'),
        type: "search",
        file_name: query.name,
    }
    if (!req.file_name) {
        ElMessage.error("请求参数不能为空");
        return;
    }
    let result = await FindUserFileService(req);
    page.total = result.data.length;
    page.index = 1;
    allData.value = result.data;
    // 分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = result.data.slice(start, end);
};

// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'ID', label: '文件ID', width: 50 },
    { prop: 'UserFileName', label: '文件名' ,width: 300},
    { prop: "UploadType", label: "上传类型",width: 100},
    { prop: 'CreatedAt', label: '创建时间',type: 'date',width: 220 },
    { prop: 'UpdatedAt', label: '更新时间',type: 'date',width: 220 },
    { prop: 'operator', label: '操作' , operate: { view: false, edit: true, delete: true,push: {link: false,label:"继续该会话"} ,gen: {show: true,label:"下载文件"}, genv2:{type:"file_edit", label:"编辑文件内容", show:true}},align: 'center', fixed: 'right' },
])

const getData = async () => {
    let req={
        token: localStorage.getItem('token'),
        type: "all"
    }
    let result = await FindUserFileService(req);
    page.total = result.data.length;
    page.index = 1;
        allData.value = result.data;
    // 分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = result.data.slice(start, end);
};
getData();

const changePage = (val: number) => {
    page.index = val;
    //分页
    let start = (page.index - 1) * page.size;
    let end = start + page.size;
    if (end > page.total) {
        end = page.total;
    }
    if (start > page.total) {
        start = page.total;
    }
    tableData.value = allData.value.slice(start, end);
};

// 新增弹窗
let options = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '文件名称', prop: 'UserFileName', required: true },
    ]
})

//编辑弹窗
let options_edit = ref<FormOption>({
    labelWidth: '100px',
    span: 12,
    list: [
        { type: 'input', label: '文件名称', prop: 'UserFileName', required: true },
    ]
})

const visible = ref(false);
const visible_add = ref(false);
const isEdit = ref(false);
const isAdd = ref(false);
const rowData = ref({});
const handleEdit = async (row: Session) => {
    let data = row;
    rowData.value = data;
    console.log("edit_row_data:", rowData.value);
    isEdit.value = true;
    visible.value = true;
};
const updateData = async (data) => {
    let result ={}
      try{
        let req={
            token:localStorage.getItem("token"),
            file_id: data.ID,
            file_name: data.UserFileName,
        };
        console.log("update row data:", req);
        //检查请求参数
        if (!req.file_name) {
            ElMessage.error("请求参数错误");
            return;
        }
        result = await UpdateUserFileService(req)
        if (result["code"] === 0) {
          ElMessage.success("更新成功");
        } else {
          ElMessage.error("更新失败");
        }

      }catch(e){
        console.log(e);
      }
      closeDialog();
    getData();
};

const addData = async (data) => {
    let result ={}
      try{
        let req={
            token:localStorage.getItem("token"),
            name: data.Name
        };
        //result = await AddSessionService(req)
        if (result["code"] === 0) {
          ElMessage.success("新增成功");
        } else {
          ElMessage.error("新增失败");
        }

      }catch(e){
        console.log(e);
      }
    closeDialog();
    handleSearch();
};


const closeDialog = () => {
    visible.value = false;
    visible_add.value = false;
    isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: []
});
const handleView =async (row: File) => {
    viewData.value.row = row;
    viewData.value.list = [
        
    ]
    visible1.value = true;
};

const handleGenOperate = async (row: File) => {
    console.log("gen row:", row);
    //弹出提示框
    downloadFile(row);
    
}

const editFileType= {'txt':true,'json':true,'md':true,'py':true,'java':true,'cpp':true,'go':true,'js':true,'html':true,'css':true, 'sql':true, 'xml':true,'yaml':true,'yml':true,'sh':true,'bat':true};

const handleGenOperateV2 = async (row: File, content: any) => {
    if (content.type == 'download'){
        console.log("gen row:", row);
        //弹出提示框
        downloadFile(row);
    }else if (content.type == 'file_edit'){
        //文件类型是否支持
        let fileName = row.UserFileName;
        //按.分割
        let fileType = fileName.split(".")[1];
        console.log("fileType:", fileType);
        if(editFileType[fileType] == undefined){
            ElMessage.error("不支持的文件类型："+fileType+"，该文件类型不支持在线编辑，请下载后编辑");
            return;
        }
        //获取文本内容
        await FindFileContent(row);
        code_edit.value = true;

    }else{
        ElMessage.error("操作类型错误");
    }
}


const downloadFile = async (row: File) => {
    const fileUrl_ = fileUrl2+row.file_store_name +"?token=" + localStorage.getItem('token');
    //对话框，加入<a>标签
    downloadFileVisible.value = true;
    downloadFileUrl.value = fileUrl_;

    // const response = await fetch(fileUrl_)
    // const blob = await response.blob()
    
    // const url = window.URL.createObjectURL(blob)
    // const link = document.createElement('a')
    // link.href = url
    // link.download = row.UserFileName // 设置下载的文件名
    
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
    // // 释放内存
    // window.URL.revokeObjectURL(url)
    // ElMessage.success('文件下载成功')
};
// 删除相关
const handleDelete = async (row: File) => {
    let req={
        token: localStorage.getItem('token'),
        file_id: row.ID,
    }
    try{
        let result = await DelUserFileService(req);
        if(result["code"] === 0){
            ElMessage.success("删除成功");
            getData();
        }else{
            ElMessage.error("删除失败");
        }
    }catch(e){
        console.log(e);
    }
}

const FindFileContent = async (row: File) => {
    let req={
        token: localStorage.getItem('token'),
        user_file_id: row.ID,
    };
    edit_file_name.value = row.UserFileName;
    edit_file_id.value = row.ID;
    try{
        let result = await FindFileContentService(req);
        if(result["code"] === 0){
            //console.log("file content:", result["data"][0]);
            code_edit_content.value = result["data"][0]["FileContent"];
            console.log("code_edit_content:", code_edit_content.value);
        }else{
            ElMessage.error("删除失败");
        }
    }catch(e){
        console.log(e);
    }
}

const closeFileEdit = () => {
    code_edit.value = false;
    code_edit_content.value = '';
} 

const updateFileContent = async (value) => {
    console.log("file content:", value);
}
</script>

<style scoped>

.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>