<template>
  <div v-if="this.attachmentList.length !== 0">
    <p class="main_title">当前节点所需上传文件</p>
    <van-steps direction="vertical" :active="active">
      <van-step
        v-for="(item, index) in attachmentList"
        :key="index">
        <van-collapse :accordion="true" v-model="item.collapse">
          <van-collapse-item :title="item.fileTypeName + '(' + item.fileList.length + ')'" :name="0">
            <van-uploader
              v-model="item.fileList"
              :after-read="(file, detail) => { handleUploadSuccess(file, detail, item); }"
              :readonly="disabled || !item.current"
              :show-upload="!disabled && item.current"
              :before-delete="handleRemove"
              :deletable="!disabled && item.current"
              accept=".jpg,.png,.gif,.pdf,.doc,.docx,.xlsx,.xls"
              :before-read="checkFile"
            >
              <!-- accept=".jpg,.png,.gif,.pdf,.doc,.docx,.xlsx,.xls" 设置了无法拉起相机/下载
              :disabled="disabled || !item.current"
              -->
            </van-uploader>
          </van-collapse-item>
        </van-collapse>
      </van-step>
    </van-steps>

  </div>
</template>

<script>
import { treeSingleProcessView  , attach , removeFile , getAttachmentConfigTree, attachmentFind } from "@/api/sunVillage_info/homestead/application";
import {getToken} from "@/utils/auth";
import request from '@/utils/request'
import {Notify} from "vant";
/** 导入JS方法 */

export default {
  name: "houseApplyUploadComp",
  components: {},
  props: ["businessType", "proposerId", "houseApplyStatus", "processKey", "tableName", "readonly", 'full',"userName"],
  data() {
    return {
      disabled: this.readonly,
      loading: false,
      attachmentList: [],
      uploadImg: {
        //上传图片配置
        uploadImgUrl: "/open/home/mobile/common/attach",
      },
      newAttachments: [],
      active: -1,
      has: false,
    }
  },
  watch: {
    proposerId: function (newVal, oldVal) {
      this.showAttachmentComp(this.businessType, newVal, this.houseApplyStatus, this.processKey, this.tableName, this.full);
    },
    readonly: function (newVal, oldVal) {
      this.disabled = newVal;
    },
  },
  created() {
    if (this.businessType !== null && this.proposerId == -1) {
      this.showAttachmentComp(this.businessType, this.proposerId, this.houseApplyStatus, this.processKey, this.tableName, this.full)
    }
  },
  methods: {
    handleUploadSuccess(file, detail, item) {
      this.setFileStatus(file, 'uploading', '文件上传中...');
      let formData = new FormData;
      formData.set('file', file.file);
      this.$set(item.postData, 'userName', this.userName);
      request({
        url: this.uploadImg.uploadImgUrl,
        method: "post",
        params: item.postData,
        data: formData,
      }).then((resp) => {
        if(resp.code == 200)
        {
          file.response = resp;
          console.log(resp);
          file.fileList = item.fileList;
          this.onFileListChanged("ADD", resp.id);
          this.setFileStatus(file, 'done', '文件上传成功');
          this.$emit('onUploadSuccess', file);
        }
        else
          this.setFileStatus(file, 'fail', '文件上传失败!');
      }).catch((e) => {
        this.setFileStatus(file, 'fail', '文件上传失败!');
      });
      return true;
    },
    handleRemove(file, detail) {
      console.log(file, detail);
      this.setFileStatus(file, 'uploading', '文件删除中...');
      let id = file.id || file.response.id;
      removeFile(id).then(resp => {
        if(this.proposerId != -1 && false) // 不刷新
          this.showAttachmentComp(this.businessType, this.proposerId, this.houseApplyStatus, this.processKey, this.tableName, this.full)
/*        else // 新增时
        {
          let fileList = file.fileList;
          //console.log(fileList);
          fileList.splice(fileList.indexOf(file), 1);
        }*/
        this.setFileStatus(file, 'done', '文件删除成功');
        this.onFileListChanged("REMOVE", id);
      }).catch((e) => {
        this.setFileStatus(file, 'fail', '文件删除失败!');
      }).finally(() => {
        //loading.close();
      });
      return true;
    },
    showAttachmentComp(businessType, proposerId, houseApplyStatus, processKey, tableName, full) {
      this.attachmentList = [];
      this.active = -1;
      this.has = false;
      if(!full && 0)
      {
        this.getCurrentFiles(businessType, proposerId, houseApplyStatus, processKey, tableName);
      }
      else
      {
        this.getHistoryFiles(businessType, proposerId, houseApplyStatus, processKey, tableName);
      }
    },
    formatFile(list) {
      if (list !== null && list !== undefined) {
        const baseImgUrl = this.$store.getters.baseRoutingUrl;
        let UfileList = []; //上传图片列表
        list.forEach((value, index) => {
          UfileList.push({
            name: value.fileName,
            fileUrl: value.fileUrl,
            url: baseImgUrl + value.fileUrl,
            id: value.id,
            fileList: UfileList,
          });
        });
        return UfileList;
      }
    },
    onFileListChanged(type, id) {
      if(this.proposerId != -1) return;
      if(type === "ADD")
      {
        this.newAttachments.push(id);
      }
      else if(type === "REMOVE")
      {
        let index = this.newAttachments.indexOf(id);
        if(index !== -1)
          this.newAttachments.splice(index, 1);
      }
      console.log(this.newAttachments);
      this.$emit('uploadFinished', this.newAttachments);
    },
    getCurrentFiles(businessType, proposerId, houseApplyStatus, processKey, tableName) {
      this.loading = true;
      treeSingleProcessView({
        businessType: businessType,
        houseApplyStatus: houseApplyStatus,
        processKey: processKey,
        tableName: tableName,
      }).then(res => {
        this.handleResponse(res.rows, proposerId, houseApplyStatus, tableName);
        if(this.attachmentList.length === 0)
        {
          this.disabled = true;
          this.getHistoryFiles(businessType, proposerId, houseApplyStatus, processKey, tableName);
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    getHistoryFiles(businessType, proposerId, houseApplyStatus, processKey, tableName) {
      this.loading = true;
      getAttachmentConfigTree({
        businessType: businessType,
        nodeStatus: houseApplyStatus,
        processKey: processKey,
        dictTypeSort: 'home_stage_status',
        nodeStatusSort: '',
      }).then(resp => {
        //console.log(resp);
        try {
          if(!resp.data || resp.data.length === 0)
            return;
          let rows = resp.data[0].children;
          rows.forEach((value, index) => {
            if (!value.children)
              return;
            this.handleResponse(value.children, proposerId, houseApplyStatus, tableName);
          });
        }
        catch (e)
        {
          console.error(e);
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    handleResponse(rows, proposerId, houseApplyStatus, tableName) {
      rows.forEach((value, index) => {
          let obj = {
            fileTypeName: value.fileTypeName,
            tableId: proposerId,
            tableName: tableName,
            fileList: [],
            fileType: value.fileType,
            postData: {
              tableId: proposerId,
              tableName: tableName,
              bizPath: tableName,
              fileType: value.fileType,
            },
            current: value.nodeStatus == houseApplyStatus,
            collapse: this.disabled || value.nodeStatus == houseApplyStatus ? 0 : '',
          };
          if(value.nodeStatus != houseApplyStatus && !this.has)
            this.active++;
          if(value.nodeStatus == houseApplyStatus)
          {
            if(!this.has)
              this.active++;
            this.has = true;
          }
          this.attachmentList.push(obj);

      });
      if (proposerId !== -1) {
        this.attachmentList.forEach((value, index) => {
          attachmentFind(value).then(resp => {
            let list = this.formatFile(resp.data);
            this.$set(this.attachmentList[index], "fileList", list);
          });
        });
      }
      console.info(this.attachmentList);
    },
    setFileStatus(file, status, message) {
      file.status = status;
      file.message = message;
    },
    checkFile(file) {
      let mime = file.type;
      if([
        "image/png",
        "image/jpeg",
        "image/gif",
        "image/bmp",
      ].indexOf(mime) === -1)
      {
        this.notify('请上传jpg/png/gif/bmp等格式图片!', 'danger');
        return false;
      }
      return true;
    },
    notify(message, type) {
      Notify.clear();
      Notify({ type: type || 'primary', message: message });
    },
  }
};
</script>
<style scoped>
.my_class >>> .el-upload--picture-card {
  width: 72px;
  height: 72px;
  line-height: 78px;
}

.my_class >>> .el-upload-list__item {
  width: 72px;
  height: 72px;
}

.my_class >>> .el-upload-list__item-preview {
  width: 20px;
}

.my_class >>> .el-upload-list__item-delete {
  width: 20px;
}

.main_title{
  font-size: 0.4rem;
  color: #1D6FE9;
  margin: 0.2rem 6%;
  position: relative;
}
</style>
