<template>
  <el-table
    :data="tableData"
    style="width: 100%;height: 681px;overflow: auto;"
    @expand-change="handleExpand"
  >
    <el-table-column type="expand">
      <template v-slot:default="scope">
        <el-table
          class="down"
          :data="scope.row.childrenList"
          stripe
          style="width: 100%;margin-top: 20px;"
          :show-header="false"
          ref="table"
        >
          <el-table-column prop="name" align="left" label="文件名称">
            <template slot-scope="scope">
              <el-link style="margin-right: auto;" :href="`${baseUrl}${scope.row.url}`" :underline="false" target="_blank">
                <span class="el-icon-document"> {{ getFileName(scope.row.fileName) }} </span>
              </el-link>
            </template>
          </el-table-column>
          <el-table-column v-if="isShowUploadButton">

          </el-table-column>
          <el-table-column label="审核状态" align="center" >
            <template slot-scope="scope" class="button-cell" >
              {{ scope.row.state === 1 ? '通过' : scope.row.state === 2 ? '不通过' : '未审核'}}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" >
            <template slot-scope="scope" v-if="isShowButton">
              <el-button size="small" type="text" @click="downloadFile(scope.row.fileId,scope.row.name)">下载</el-button>
              <el-button size="small" type="text" @click="filePassMethod(scope.row,'pass')" v-if="templateType==='aduit'">通过</el-button>
              <el-button size="small" type="text" @click="filePassMethod(scope.row,'nopass')" v-if="templateType==='aduit'">不通过</el-button>
              <el-button size="small" type="text" @click="deleteHandle(scope.row.fileId,scope)" v-if="templateType==='apply'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>
    <el-table-column label="文件名称" prop="name"></el-table-column>
    <el-table-column label="上传文件" v-if="isShowUploadButton">
      <template v-slot:default="scope" v-if="isShowUploadButton">
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="uploadUrl + '?applyId=' + applyId + '&fileCode=' + scope.row.fileCode"
          :headers="header"
          :file-list="scope.row.childrenList"
          :show-file-list="false"
          :on-error="handleUploadError"
          :on-success="uploadSuccess(scope.row)"
        >
          <el-button  size="small" type="primary">上传文件</el-button>
        </el-upload>
      </template>
    </el-table-column>
    <el-table-column label="上传状态" prop="status">
      <template v-slot:default="scope">
        {{ scope.row.childrenList.length === 0 ? '未上传' : '已上传' }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template v-slot:default="scope">
        {{ scope.row.expanded ? '已展开' : '已收起' }}
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import {getToken} from "@/utils/auth";
import {Loading, Message} from "element-ui";
import {blobValidate, tansParams} from "@/utils/ruoyi";
import errorCode from "@/utils/errorCode";
import service from "@/utils/request";
import {delFile, listFile} from "@/api/reward/apply";
import {approved, filePass} from "@/api/reward/aduit";

export default {
  props:{
    applyId:{
      type:String,
      default:'',
      require:true,
    },
    dialogType:{
      type:String,
      default: '',
    },
    tableData:{
      type:Array,
      default:()=>[],
      require:true,
    },
    isShowButton:{
      type:Boolean,
    },
    templateType:{
      type:String,
    },
    isShowUploadButton:{
      type:Boolean,
    },
  },
  data() {
    return {
      header:{ Authorization: "Bearer " + getToken() },
      uploadUrl:process.env.VUE_APP_BASE_API + "/reward/file/upload",
      baseUrl: process.env.VUE_APP_BASE_API,
    }
  },
  mounted() {
    console.log(this.templateType)
  },
  methods:{
    filePassMethod(row,status){
      if (status === 'pass'){
        filePass(row.fileId,'1').then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "审核通过",
              type: "success",
            });
            this.$set(row, 'state', 1);
          } else {
            this.$message.error(res.msg);
          }
        });
      }else if (status === 'nopass'){
        filePass(row.fileId,'2').then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "审核不通过",
              type: "warning",
            });
            this.$set(row, 'state', 2);
          }else {
            this.$message.error(res.msg);
          }
        })
      }
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    uploadSuccess(row) {
      return (response, file) => {
        if (response.code === 200) {
          row.childrenList.push({
            name: file.raw.name,
            fileName:item.realName,
            url: response.data.filePath,
            state:response.data.fileState,
            fileId:response.data.fileId,
            fileCode:response.data.fileCode,
          });
        }
      };
    },
    handleExpand(row, expandedRows) {
      row.expanded = !!expandedRows.includes(row);
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
    downloadFile(fileId, fileName) {
      let downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
      // 构建请求URL，将参数作为查询字符串附加在URL中
      const url = `/reward/file/download?fileId=${fileId}`;
      return service.get(url, {
        responseType: 'blob',
      }).then(async (data) => {
        const isBlob = blobValidate(data);
        if (isBlob) {
          const blob = new Blob([data])
          saveAs(blob, fileName)
        } else {
          const resText = await data.text();
          const rspObj = JSON.parse(resText);
          const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
          Message.error(errMsg);
        }
        downloadLoadingInstance.close();
      }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
      })
    },
    deleteHandle(fileId,scope) {
      let index = this.tableData.findIndex(item => item.fileCode === scope.row.fileCode);
      let findIndex = this.tableData[index].childrenList.findIndex(item => item.fileId === fileId)
      this.$confirm(`确定删除该文件吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delFile(fileId).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            if (findIndex !== -1) {
              this.tableData[index].childrenList.splice(findIndex, 1);
            }
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep .el-dialog--center .el-dialog__body{
  padding-bottom: 0;
}
::v-deep .cell{
  text-align: center;
}
.el\-upload\-list__item{
  display: flex;
  justify-content: space-around;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
  ::v-deep .el-form-item__content{
    width: 100%;
    display: flex;
    justify-content: space-around;
    .action{
      width: 45%;
      text-align: center;
      box-sizing: border-box;
      padding-left: 123px;
    }
  }
}
</style>
