<template>
  <div>
    <el-card style="min-height: calc(100vh - 190px);">
      <avue-crud
        :option="option"
        :data="tableData"
        :page="page"
        :table-loading="loading"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <!-- 工具栏按钮 -->
        <template #menu-left>
          <el-button plain type="primary" icon="Plus" v-hasPermi="['file:manage:add']"
                     @click="handleAdd" :disabled="addBtnIsShow" v-if="fileStatus === '0'">
            新增
          </el-button>
          <!-- 整改清单按钮（跳转页面） -->
          <el-button
            plain
            type="warning"
            icon="List"
            @click="goToRectificationList"
          >
            整改清单
          </el-button>
        </template>

        <template #fileName="{ row }">
          <span class="file-name-link" @click="viewFile(row)">{{ row.fileName }}</span>
        </template>

        <!-- 操作栏 -->
        <template #menu="{ row, size }">
          <el-button
            :size="size"
            type="primary"
            link
            icon="View"
            @click="handleDetail(row)"
            v-hasPermi="['file:manage:query']"
          >详情</el-button>
          <el-button
            :size="size"
            type="primary"
            link
            icon="Edit"
            @click="handleUpdate(row)"
            v-hasPermi="['file:manage:update']"
          >修改</el-button>
          <el-button
            v-if="row.isRectification === '0'"
            :size="size"
            type="primary"
            link
            icon="Plus"
            @click="handleRect(row)"
          >加入整改</el-button>
          <el-button
            :size="size"
            type="danger"
            link
            icon="Delete"
            @click="handleDelete(row)"
            v-hasPermi="['file:manage:del']"
          >删除</el-button>
        </template>
      </avue-crud>

      <!-- 新增/编辑 -->
      <AddTableData v-if="isflag" :isAdd="isAdd" :rowData="row" @handleQuery="handleQuery" :title="title"
                    @closeDialog="closeDialog" @showColose="showColose" :dataForm="row" :width="600" :projectId="projectId" />
      <!-- 整改 -->
      <RectTableData v-if="isflagRect" :isRect="isRect" :rowData="row" @handleQuery="handleQuery" :title="title"
                     @closeDialog="closeDialog" @showColose="showColose" :dataForm="row" :width="600" :projectId="projectId" />

      <!-- 预览文件 -->
      <ViewFile v-if="isViewflag" :rowData="row" :title="title" :isAdd="isAdd" @closeDialog="closeDialog"
                @showColose="showColose" :width="600" />
    </el-card>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
import { ref, reactive, watch, nextTick } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import {
  delFileManageApi,
  getFileManageApi,
} from '@/api/archivesManagement/fileManager/fileManager.js'
import AddTableData from './addTableData.vue'
import RectTableData from './rectTableData.vue'
import ViewFile from '@/views/viewFile/viewFile.vue'

const props = defineProps({
  projectId: {
    type: String,
    default: ''
  },
  selectedNode: {
    type: Object,
    default: null
  },
  fileStatus: {
    type: String,
    default: ''
  }
})

const goToRectificationList = () => {
  if (!props.projectId) {
    ElMessage.warning('项目异常，请联系管理员')
    return
  }
  // 跳转到整改清单页面，携带 projectId
  router.push({
    name: 'RectificationList', // 路由名称，需与路由配置一致
    query: {
      projectId: props.projectId
    }
  })
}

// 响应式数据
const title = ref("")
const isflag = ref(false)
const isflagRect = ref(false)
const isViewflag = ref(false)
const isAdd = ref('')
const isRect = ref('')
const row = ref({})
const loading = ref(false)
const addBtnIsShow = ref(true)
const defaultParams = ref({})

// 表格数据
const tableData = ref([])
const page = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const query = reactive({})

// Avue 配置
const option = reactive({
  height: 'auto',
  calcHeight: 32,
  tip: false,
  searchShow: true,
  searchMenuSpan: 6,
  border: true,
  index: true,
  menu: props.fileStatus === '0', // 根据 fileStatus 动态控制操作列显示
  viewBtn: false,
  selection: false,
  addBtn: false,
  editBtn: false,
  delBtn: false,
  dialogClickModal: false,
  column: [
    {
      label: '档案名称',
      prop: 'contentName',
      width: 200,
      search: true
    },
    {
      label: '档案文件',
      prop: 'fileName',
      width: 140,
      slot: true
    },
    {
      label: '上传人',
      prop: 'createUserName'
    },
    {
      label: '保管期限',
      prop: 'term'
    },
    {
      label: '来源',
      prop: 'dataSource',
      slot: true
    },
    {
      label: '责任单位',
      prop: 'unitName'
    },
    {
      label: '上传时间',
      prop: 'createTime',
      width: 160
    }
  ]
})

// 方法
const closeDialog = () => {
  isflag.value = false
  isflagRect.value = false
  isViewflag.value = false
}

const showColose = () => {
  isflag.value = false
  isViewflag.value = false
}

/** 详情操作 */
const handleDetail = (rowData) => {
  title.value = "详情"
  isAdd.value = 'detail'
  row.value = rowData
  isflag.value = true
}

/** 新增按钮操作 */
const handleAdd = () => {
  title.value = "新增"
  isAdd.value = 'add'
  isflag.value = true
  row.value = props.selectedNode
  row.value.detailStatus = false
  row.value.belongName = props.selectedNode.parentName + '/' + props.selectedNode.label
}

/** 修改操作 */
const handleUpdate = (rowData) => {
  title.value = "修改"
  isAdd.value = 'edit'
  row.value = rowData
  row.value.belongName = props.selectedNode.parentName + '/' + props.selectedNode.label
  row.value.detailStatus = false
  isflag.value = true
}
const handleRect = (rowData) => {
  title.value = "加入整改清单"
  isRect.value = 'rect'
  row.value = rowData
  row.value.belongName = props.selectedNode.parentName + '/' + props.selectedNode.label + '/' + row.value.fileName
  row.value.detailStatus = false
  isflagRect.value = true
}

// 预览文件
const viewFile = (rowData) => {
  title.value = "预览"
  isAdd.value = 'view'
  row.value = rowData
  isViewflag.value = true
}

/* 搜索操作 */
const handleQuery = () => {
  onLoad(page, query)
}

/** 删除操作 */
const handleDelete = (rowData) => {
  let loading = null;
  ElMessageBox.confirm(`是否确认删除文件名称为"${rowData.contentName}"的数据项？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 用户确认删除，直接执行删除操作
    loading = ElLoading.service({
      lock: true,
      text: '正在删除，请稍候...',
      background: 'rgba(0,0,0,0.5)'
    });
    delFileManageApi({ id: rowData.id }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success("删除成功")
        handleQuery()
      } else {
        ElMessage.error(res.data.msg)
      }
    }).catch(error => {
      ElMessage.error(error)
    })
  }).catch(() => {
    // 用户取消删除
  }).finally (() =>{
    // 无论成功还是失败，都会执行这里
    if (loading) {
      loading.close();
    }
  });
}

// 表格相关方法
const searchChange = (params, done) => {
  Object.assign(query, params)
  page.currentPage = 1
  onLoad(page, params)
  done()
}

const searchReset = () => {
  Object.keys(query).forEach(key => delete query[key])
  onLoad(page)
}

const currentChange = (currentPage) => {
  page.currentPage = currentPage
}

const sizeChange = (pageSize) => {
  page.pageSize = pageSize
}

const refreshChange = () => {
  onLoad(page, query)
}

const onLoad = async (pageParam, params = {}) => {
  loading.value = true
  try {
    const requestData = {
      ...params,
      ...defaultParams.value,
      pageNum: pageParam.currentPage,
      pageSize: pageParam.pageSize
    }
    const res = await getFileManageApi(requestData)
    if (res.data.code === 200) {
      tableData.value = res.data.rows
      page.total = res.data.total
    }
  } catch (error) {

  } finally {
    loading.value = false
  }
}

// 监听选中的节点
watch(() => props.selectedNode, (newVal) => {
  addBtnIsShow.value = !(newVal && Number(newVal.level) === 4)

  const parentId = newVal && newVal.id ? newVal.id : 0
  const proId = props.projectId
  defaultParams.value = { parentId, proId }

  onLoad(page, { parentId, proId })
}, { immediate: true })

// 监听 fileStatus 变化，更新 option.menu
watch(() => props.fileStatus, (newVal) => {
  option.menu = newVal === '0'
}, { immediate: true })
</script>

<style scoped>
.file-name-link {
  color: #409EFF;
  cursor: pointer;
}
.file-name-link:hover {
  text-decoration: underline;
}
</style>
