<template>
  <el-dialog :title="titleValue" width="800px" :model-value="modelValue" append-to-body @close="closed">
    <el-form ref="historyForm" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="过激行为" prop="gjxw">
        <el-input v-model="ruleForm.gjxw" :autosize="{ minRows: 4, maxRows: 10 }" type="textarea" placeholder="请输入研判记录"
          class="background-info-input" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="活动时间" prop="kssj">
        <el-date-picker v-model="ruleForm.kssj" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
          range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item>
      <el-form-item label="活动场所" prop="hdcs">
        <el-input v-model="ruleForm.hdcs" placeholder="请输入活动场所" />
      </el-form-item>
    </el-form>

    <div style="padding: 5px;">
      <div class="butHandle">
        <h3>涉事人员</h3>
        <div> <el-button type="primary" @click="showDialog = true">选择</el-button></div>
      </div>
      <el-table :data="ruleForm.ssry" :height="200">
        <el-table-column prop="ryXm" label="姓名" />
        <el-table-column prop="rySfzh" label="身份证号码" />
        <el-table-column label="管控级别">
          <template #default="{ row }">
            <DictTag :tag="false" :value="row.zdrRyjb" :options="D_GS_ZDR_RYJB" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 文件列表区域 -->
    <div class="file-attachment-section">
      <div class="section-title">相关附件</div>
      <div class="file-list-container">
        <div v-if="ruleForm?.fileList.length == 0" class="empty-file-list">暂无附件</div>
        <div v-else class="file-list">
          <div v-for="(file, index) in ruleForm?.fileList" :key="index" class="file-item">
            <div class="file-info">
              <span class="file-name">{{ file.originalName }}</span>
              <span class="file-time">{{ file.uploadTime }}</span>
            </div>
            <div class="file-actions">
              <el-button type="text" size="small" @click="downloadFile(file)" title="下载文件" :disabled="disabled">
                <el-icon>
                  <Download />
                </el-icon>
              </el-button>
              <el-button type="text" size="small" @click="deleteFile(index)" title="删除文件" class="delete-btn"
                :disabled="disabled">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 上传按钮区域 -->
      <div class="upload-btn-container">
        <el-upload v-model:file-list="ruleForm.fileList" class="upload-demo" :show-file-list="false" multiple
          :http-request="handleUploadRequest" :on-remove="handleRemove" :limit="3" :on-exceed="handleExceed">
          <el-button type="primary" :disabled="disabled">上传文件</el-button>
        </el-upload>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">取消</el-button>
        <el-button type="primary" @click="onComfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <GroupStaff v-model="showDialog" @choosed="addMarks" :roleIds="roleIds" />
</template>

<script setup>
import { ref, onMounted, reactive, watch, getCurrentInstance } from "vue";
import { generateRandom10Digits } from '@/utils/tools'
import GroupStaff from './groupStaff.vue'
import { uploadMultipleFiles } from '../model/fileUp'
import { ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance()
const { D_GS_ZDR_RYJB } = proxy.$dict("D_GS_ZDR_RYJB"); //获取字典数据

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  titleValue: {
    type: String,
    default: "集会记录"
  },
  data: {
    type: Object,
    default: () => { }
  }
});
const emits = defineEmits(["update:modelValue", "comfirm"]);
const historyForm = ref(null)
const showDialog = ref(false)
const roleIds = ref([])
const ruleForm = ref({
  gjxw: "",
  hdcs: "",
  kssj: "",
  ssry: [],
  fileList: []
})
const rules = reactive({
  gjxw: [
    { required: true, message: '请输入过激行为', trigger: 'blur' },
  ],
  hdcs: [
    { required: true, message: '请输入活动场所', trigger: 'blur' },
  ],
  kssj: [
    { required: true, message: '请选择时间', trigger: 'blur' },
  ]
});

const onComfirm = () => {
  if (!ruleForm.value.ssry.length) {
    proxy.$message.error('请选择涉事人员')
    return
  }
  const promes = {
    ...ruleForm.value,
    id: ruleForm.value.id ? ruleForm.value.id : generateRandom10Digits(),
    kssj: ruleForm.value.kssj[0],
    jssj: ruleForm.value.kssj[1],
  }
  emits("comfirm", { ...promes });
  emits("update:modelValue", false);
}
watch(() => props.data, (val) => {
  if (val) {
    ruleForm.value = {
      ...val,
      kssj: [val.kssj, val.jssj],
      fileList:val.fj
    }
  }
},{deep: true})

const addMarks = (val) => {
  ruleForm.value.ssry = val
  roleIds.value = val.map(item => item.id)
}
// 下载文件
const downloadFile = (file) => {
  // 实际项目中，这里应该调用下载API
  console.log('下载文件:', file.name)
  // 示例：window.open(file.url)
}
// 删除文件
const deleteFile = (index) => {
  // 实际项目中，这里应该先调用删除API，成功后再从列表中移除
  ruleForm.value.fileList.splice(index, 1)
  ElMessage.success('文件已删除')
}

// 上传相关方法
const handleUploadRequest = async (options) => {
  try {
    // 调用uploadMultipleFiles进行文件上传
    const result = await uploadMultipleFiles(options.file, {
      uploadedFiles: ruleForm.value.fileList,
      fjIds: [], // 如果需要保存文件ID列表，可以在这里传递
      compressImage: null // 可选的图片压缩函数
    });
    // 更新文件列表，添加上传时间信息
    const index = ruleForm.value.fileList.findIndex(f => f.originalName === options.file.name);
    if (index !== -1) {
      ruleForm.value.fileList[index].uploadTime = new Date().toLocaleString('zh-CN');
    }
    // 调用成功回调
    if (options.onSuccess) {
      options.onSuccess(result);
    }
  } catch (error) {
    console.error('文件上传失败:', error);
    // 调用失败回调
    if (options.onError) {
      options.onError(error);
    }
  }
}

const handleRemove = (uploadFile, uploadFiles) => {
  // 实际项目中，这里应该先调用删除API，成功后再从列表中移除
  const index = ruleForm.value.fileList.findIndex(f => f.name === uploadFile.name);
  if (index !== -1) {
    ruleForm.value.fileList.splice(index, 1);
  }
}
const closed = () => {
  ruleForm.value = {
    gjxw: "",
    hdcs: "",
    kssj: "",
    ssry: [],
    fj: []
  }
  emits("update:modelValue", false);
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";

.tabBoxRadio .el-checkbox__inner {
  border-radius: 50% !important;
}

.tabBoxRadio .el-table__header-wrapper .el-checkbox {
  display: none;
}

.file-attachment-section {
  margin-top: 15px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.file-list-container {
  max-height: 100px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #ffffff;
  margin-bottom: 10px;
}

/* 自定义滚动条样式 */
.file-list-container::-webkit-scrollbar {
  width: 6px;
}

.file-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.file-list-container::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.file-list-container::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.empty-file-list {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.file-list {
  padding: 5px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 10px;
  margin-bottom: 2px;
  background-color: #f8f9fa;
  border-radius: 4px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.file-item:hover {
  background-color: #e6f7ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.file-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 15px;
  min-width: 0;
}

.file-name {
  flex: 1;
  font-size: 12px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 11px;
  color: #909399;
  min-width: 60px;
}

.file-time {
  font-size: 11px;
  color: #909399;
}

.file-actions {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: 10px;
}

.file-actions .el-button {
  padding: 0 5px;
  margin: 0;
  color: #606266;
  transition: color 0.3s ease;
}

.file-actions .el-button:hover {
  color: #409eff;
}

.delete-btn:hover {
  color: #f56c6c !important;
}

.upload-btn-container {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.butHandle {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

::v-deep .el-range-input {
  color: #000 !important;
}
</style>
