<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文档标题" prop="documentTitle">
        <el-input v-model="queryParams.documentTitle" placeholder="请输入文档标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px;">
          <el-option label="正常" :value="1" />
          <el-option label="关闭" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['system:workingDocument:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:workDocu:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:workingDocument:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="docList" @selection-change="handleSelectionChange" :row-key="getRowKey">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="80" />
      <el-table-column label="文档标题" align="center" prop="documentTitle" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:workingDocument:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:workingDocument:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改工作文档对话框 -->
    <el-dialog :title="title" v-model="open" width="600" append-to-body destroy-on-close>
      <el-form ref="docRef" :model="form" :rules="rules" label-width="9em">
        <el-form-item label="文档标题" prop="documentTitle">
          <el-input v-model="form.documentTitle" placeholder="请输入文档标题" maxlength="49" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="'1'">正常</el-radio>
            <el-radio :label="'0'">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文档文件" prop="documentUrl">
          <el-upload ref="uploadRef" :limit="1" accept=".pdf" :headers="upload.headers" :action="upload.url"
            :file-list="upload.fileList" :disabled="false" :on-success="handleFileSuccess" :on-remove="handleFileRemove"
            :auto-upload="true" drag style="width:300px">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip text-center">
                <span>仅允许导入pdf格式文件，且文件大小不超过10MB。</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="WorkDocu">
import { onMounted, ref, reactive, toRefs, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import RightToolbar from '@/components/RightToolbar/index.vue'
import { parseTime } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'
import { listWorkDocu, getWorkDocu, deleteWorkDocu, addWorkDocu, updateWorkDocu } from '@/api/system/workDocu'
const { proxy } = getCurrentInstance()

// 使用真实API接口，已从@/api/system/workDocu导入
const sys_normal_disable = [
  { label: '正常', value: '1' },
  { label: '关闭', value: '0', elTagType: 'danger' }
]

const getRowKey = (row) => {
  return row.documentId
}

// 表格数据
const docList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

// 上传相关
const uploadRef = ref(null)

const upload = reactive({
  fileList: [],
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
})

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {

  if (response.code === 200) {
    
    form.value.documentFileName =  response.fileName;
    form.value.documentNewFileName = response.newFileName;
    form.value.documentOriginalFileName = response.originalFilename;
    form.value.documentUrl = response.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 文件移除处理
const handleFileRemove = (file, fileList) => {
  // form.value.documentTitle = '';
  form.value.documentFileName = '';
  form.value.documentUrl = '';
}

// 表单数据
const data = reactive({
  form: {
    id: null,
    documentTitle: '',
    status: '1',
    documentUrl: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    documentTitle: '',
    createBy: '',
    status: null
  },
  rules: {
    documentTitle: [
      { required: true, message: '文档标题不能为空', trigger: 'blur' }
    ],
    documentUrl: [
      { required: true, message: '文档文件不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询文档列表 */
const getList = () => {
  loading.value = true
  listWorkDocu(queryParams.value).then(response => {
    docList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    documentTitle: '',
    status: '1',
    documentUrl: ''
  }
  // 清空文件列表
  upload.fileList = []
  if (proxy?.$refs?.docRef) {
    proxy.$refs.docRef.resetFields()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if (proxy?.$refs?.queryRef) {
    proxy.$refs.queryRef.resetFields()
  }
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.documentId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加工作文档'
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()

  const _id = row?.documentId || ids.value
  getWorkDocu(_id).then(response => {
    form.value = response.data;
    upload.fileList = [{
      name: response.data.documentOriginalFileName,
      url: response.data.documentUrl
    }]
    open.value = true
    title.value = '修改工作文档'
  })
}

/** 提交按钮 */
const submitForm = () => {
  if (proxy?.$refs?.docRef) {
    proxy.$refs.docRef.validate((valid) => {
      if (valid) {
        if (form.value.documentId != null) {

          updateWorkDocu(form.value).then(response => {
            ElMessage.success('修改成功')
            open.value = false
            getList()
          })
        } else {
          addWorkDocu(form.value).then(response => {
            ElMessage.success('新增成功')
            open.value = false
            getList()
          })
        }
      }
    })
  }
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const _ids = row?.documentId || ids.value;

  if (proxy?.$modal) {
    proxy.$modal.confirm('是否确认删除数据项？').then(() => {
      // 如果是数组就join，如果不是就直接传
      const deleteIds = Array.isArray(_ids) ? _ids.join(',') : _ids;
      return deleteWorkDocu(deleteIds)
    }).then(() => {
      getList()
      ElMessage.success('删除成功')
    }).catch(() => { })
  }
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.fixed-width {
  width: 140px;
}

.small-padding .cell {
  padding: 10px 5px;
}

.dialog-footer {
  text-align: right;
}
</style>