<template>
  <slot>
    <el-button @click="uploadAnnex"> <SvgIcon name="ele-Upload" /> {{props.name}} </el-button>
    <span class="color-info ml10" v-if="state.tableData.length">当前已上传 <span class="color-primary">{{ state.tableData.length }}</span> 个附件</span>
  </slot>
	<el-dialog v-model="dialogVisible" draggable title="附件列表" ref="dialogRef" width="60%" append-to-body destroy-on-close>
		<div class="mb20" v-if="!props.readonly">
			<el-button type="primary" @click="handleAdd"><SvgIcon name="ele-Plus" class="mr3" v-auth="'file:add'"/> 添加附件</el-button>
			<el-button type="primary" @click="handleDelete" :disabled="!multipleSelection.length" v-auth="'file:delete'"
				><SvgIcon name="ele-Delete" class="mr3" />删除附件</el-button
			>
		</div>
		<!-- 表格 -->
		<el-table :data="state.tableData" v-loading="loading" row-key="id" ref="multipleTableRef" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" :reserve-selection="true" v-if="!props.readonly"/>
			<el-table-column prop="name" label="附件名称" show-overflow-tooltip width="240"></el-table-column>
			<el-table-column prop="type" label="文件类型" show-overflow-tooltip width="100"></el-table-column>
			<el-table-column prop="creationTime" label="上传时间" show-overflow-tooltip width="170">
				<template #default="{ row }">
					<span>{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="orgName" label="上传部门" show-overflow-tooltip width="200"></el-table-column>
			<el-table-column prop="userName" label="上传人" show-overflow-tooltip></el-table-column>
			<el-table-column prop="publicity" label="是否公开给市民" show-overflow-tooltip width="140">
        <template #default="{ row }">
          {{ row.publicity == 1 ? '是' : '否'}}
        </template>
      </el-table-column>
			<el-table-column prop="classify" label="附件分类" show-overflow-tooltip width="100"></el-table-column>
			<el-table-column label="操作" width="80" fixed="right" align="center">
				<template #default="{ row }">
					<el-button link type="primary" @click="download(row)" title="下载附件" v-auth="'file:download'" v-if="row.url"> 下载 </el-button>
				</template>
			</el-table-column>
			<template #empty>
				<Empty />
			</template>
		</el-table>
		<!-- 分页 -->
		<pagination :total="total" v-model:page="queryParams.PageIndex" v-model:limit="queryParams.PageSize" @pagination="queryList" v-if="props.businessId"/>
		<!--  上传  -->
		<el-dialog v-model="dialogVisibleUpload" draggable title="上传附件" @close="close" ref="dialogRef" width="600px" append-to-body destroy-on-close>
			<el-form :model="ruleForm" ref="ruleFormRef" @submit.native.prevent class="mt15" label-width="120px">
				<el-form-item label="是否公开给市民" prop="publicity" :rules="[{ required: true, message: '请选择是否公开', trigger: 'change' }]">
					<el-radio-group v-model="ruleForm.publicity">
						<el-radio :label="1">公开</el-radio>
						<el-radio :label="0">不公开</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="附件" prop="fileList" :rules="[{ required: true, message: '请选择附件文件', trigger: 'change' }]">
          <el-upload
              class="upload-demo w100"
              v-model:file-list="ruleForm.fileList"
              action="#"
              :auto-upload="false"
              :multiple="true"
              accept="*"
              :on-exceed="handleExceed"
              :http-request="httpRequest"
              :on-change="handleChange"
              ref="uploadListRef"
          >
            <el-button> <SvgIcon name="ele-Upload" /> 上传附件 </el-button>
            <slot> </slot>
            <template #file="{ file }">
              <div class="el-upload-list__item-info">
                <a class="el-upload-list__item-name">
                  <SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="14px" />
                  <span class="el-upload-list__item-file-name" :title="file.name">{{ file.name }}</span>
                </a>
              </div>
              <SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" />
            </template>
          </el-upload>
        </el-form-item>
			</el-form>
      <template #footer>
          <el-button class="default-button" @click="dialogVisibleUpload = false"> 取 消</el-button>
          <el-button type="primary"  @click="submit(ruleFormRef)"> 确 定 </el-button>
      </template>
		</el-dialog>
    <template #footer>
      <el-button class="default-button" @click="dialogVisible = false">关 闭</el-button>
    </template>
	</el-dialog>
</template>
<script setup lang="ts" name="AnnexList">
import {reactive, ref} from 'vue';
import { formatDate } from '/@/utils/formatTime';
import {checkFile, fileType} from '/@/utils/tools';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { guid } from '/@/utils/tools';
import {ElButton, ElMessage, ElMessageBox, FormInstance} from 'element-plus';
import {fileList, fileAdd, fileDelete} from "/@/api/public/file";

const dialogVisible = ref(false); // 弹窗显示隐藏
const dialogVisibleUpload = ref(false); // 上传弹窗显示隐藏
const loading = ref(false); // 表格加载状态
const total = ref(0); // 表格总数
const uploadListRef = ref<RefType>(); // 上传附件ref
const ruleFormRef = ref<RefType>(); // 上传附件表单ref
const queryParams = ref({
	// 查询参数
	PageIndex: 1, // 当前页
	PageSize: 10, // 每页条数
});
const ruleForm = reactive({
	// 上传附件表单
  publicity: 0,
  fileList:<EmptyArrayType>[]
});
const state = reactive<any>({
  tableData: <EmptyArrayType>[], //表格数据
})
const emit = defineEmits(['uploadAnnex'])
const props = defineProps({
  name: {
    type: String,
    default: '上传附件'
  },
  fileLimit:{ // 限制上传数量
    type: Number,
    default: 5
  },
  fileSize:{ // 限制上传大小(M)
    type: Number,
    default: 10
  },
  businessId:{ // 业务id
    type: String,
    default: ''
  },
  classify:{ // 附件分类
    type: String,
    required: true,
    default: ''
  },
  readonly:{ // 只读（详情查看）
    type: Boolean,
    default: false
  },
})
const uploadAnnex = ()=>{
  openDialog();
  emit('uploadAnnex')
}
// 查询附件列表
const queryList = () => {
	loading.value = true;
  fileList({Key:props.businessId}).then((res: any) => {
    state.tableData = res.result?.items ?? [];
    total.value = res.result?.total ?? 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

// 表格多选
const multipleTableRef = ref<RefType>();
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
// 下载附件
const download = (row:any) => {
  const link = document.createElement('a') // 创建一个 a 标签用来模拟点击事件
  link.style.display = 'none'
  link.href = row.url;
  link.setAttribute('download', '文件名')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
};
// 打开弹窗
const openDialog = () => {
	loading.value = false;
  if(props.businessId){
    queryList();
  }
  multipleSelection.value = [];
	dialogVisible.value = true;
};
// 关闭弹窗
const closeDialog = () => {
	dialogVisible.value = false;
};
// 上传附件
const handleAdd = () => {
	dialogVisibleUpload.value = true;
};
// 删除附件
const handleDelete = () => {
  const names:string = multipleSelection.value.map((item: any) => item.name).join(',');
  ElMessageBox.confirm(`确定要删除【${names}】的附件？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    cancelButtonClass: 'default-button',
  })
      .then(() => {
        if(props.businessId){
          fileDelete({ids:multipleSelection.value.map((v: any) => v.id)}).then(() => {
            queryList();
            for(let item of multipleSelection.value) {
              state.tableData.forEach((v: any, i: any) => {
                if (v.id == item.id) {
                  state.tableData.splice(i, 1);
                  multipleTableRef.value!.toggleRowSelection(v, false);
                  ElMessage.success('操作成功');
                }
              });
            }
          });
        }else{
          for(let item of multipleSelection.value) {
            state.tableData.forEach((v: any, i: any) => {
              if (v.id == item.id) {
                state.tableData.splice(i, 1);
                multipleTableRef.value!.toggleRowSelection(v, false);
                ElMessage.success('操作成功');
              }
            });
          }
        }
      })
      .catch(() => {});
};
// 上传
const httpRequest = async (params: any) => {
  const file = params.file;
  // 文件名(8位随机数)：
  const fileName = Math.random().toString(36).substring(-8) + file.name.substring(file.name.lastIndexOf('.'));

  // 目录加文件名【上线前修改目录名】
  const fileSrc = `test20220824/${fileName}`;
  console.log(fileSrc);
  try {
    params.onProgress({ percent: 0 });
    //上传的自定义逻辑都在这里

    ruleForm.fileList = [
      ...ruleForm.fileList

    ];
    // console.log(`上传成功 ${res.key}`)
    console.log(ruleForm.fileList)
    params.onSuccess();
  } catch (err) {
    console.log(err, 'err');

    ElMessage.error('网络错误，请稍后重试');
    params.onError();
  }
};
//文件限制
const handleExceed = (files: any, fileList: any) => {
  ElMessage.warning(`当前限制选择 ${props.fileLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};
//上传前的校验
const handleChange = (rawFile: any) => {
  const isLt = rawFile.size / 1024 / 1024 < props.fileSize;
  if (!isLt) {
    ElMessage.warning(`文件超过了最大限度 ${props.fileSize} MB!`);
    ruleForm.fileList = ruleForm.fileList.slice(0, ruleForm.fileList.length - 1);
    return;
  }
};
// 删除
const handleRemove = (uploadFile: any) => {
  ElMessageBox.confirm(`确定要删除？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    cancelButtonClass: 'default-button',
  })
      .then(() => {
        // infoList.value.forEach((v: any, i: any) => {
        // 	if (v.uid == uploadFile.uid) {
        // 		infoList.value.splice(i, 1);
        // 	}
        // });
        uploadListRef.value.handleRemove(uploadFile);
      })
      .catch(() => {});
};
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
// 提交
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    if(!valid) return;
    if(props.businessId){// 业务id存在，上传附件
      const uploadTable =  ruleForm.fileList.map((v: any) => {
        return {
          ...v,
          name: v.name.substring(0, v.name.lastIndexOf(".")),
          type: v.name.split(".").pop(),
          publicity: ruleForm.publicity,
          classify: props.classify,
          key: props.businessId,
          additions:'测试附件上传内容',
        };
      })
      fileAdd(uploadTable).then(() => {
        ElMessage.success('操作成功');
        queryList();
      });
    }else{
      const uploadTable =  ruleForm.fileList.map((v: any) => {
        return {
          id: guid(),
          name: v.name.substring(0, v.name.lastIndexOf(".")),
          type: v.name.split(".").pop(),
          orgName: userInfos.value.orgName,
          userName:userInfos.value.name,
          creationTime: new Date(),
          publicity: ruleForm.publicity,
          classify: props.classify,
          key: props.businessId,
          additions:'测试附件上传内容',
        };
      })
      state.tableData.push(...uploadTable)
      ElMessage.success('操作成功');
    }
    ruleForm.fileList = [];
    formEl.clearValidate();
    formEl.resetFields();
    dialogVisibleUpload.value = false;
  });
};
const close = ()=>{
  ruleForm.fileList = [];
  ruleFormRef.value!.clearValidate();
  ruleFormRef.value!.resetFields();
}
defineExpose({
	openDialog,
	closeDialog,
  fileList:state.tableData
});
</script>

