/*
 * @Author: Anmin 
 * @Email:changanmin1@crc.com.hk 
 * @Date: 2018-12-20 15:10:57 
 * @Last Modified by: Anmin
 * @Last Modified time: 2019-01-09 10:08:20
 * @description:  上传附件
 */ 
<template>
  <div>
    <!-- 已上传的文件table -->
    <div>
      <Row>
        <Col>
          <Table
            :loading="loading"
            no-data-text="请上传关联的附件"
            :columns="columns"
            :data="tableData"
            :highlight-row="false"
            @on-selection-change="handle_sel_table"
          ></Table>
        </Col>
      </Row>
      <Row class="footer-tools" style="margin-top:6px;">
        <Col>
          <Upload
            ref="upload"
            style="display: inline-block;"
            :action="uploadUrl"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
            :on-error="onError"
            :show-upload-list="false"
            v-if="uploadBtn"
          >
            <Button type="info" icon="ios-cloud-upload-outline">选择附件</Button>
          </Upload>
          <!-- <Button
          :disabled="selections.length <= 0"
          type="warning"
          icon="android-download"
          @click="batchDown"
          >批量下载</Button>-->
          <!-- TEST -->
          <Button
            :disabled="selections.length <= 0"
            type="warning"
            icon="android-download"
            @click="GETbatchDown"
          >批量下载</Button>
          <!-- TEST -->
          <Button type="success" @click="save" v-if="closeBtn">提交</Button>
          <Button type="error" @click="close" v-if="closeBtn">关闭</Button>
        </Col>
      </Row>
    </div>
    <!-- 上传文件进度条控制 -->
    <div style="margin-top:20px;" v-for="item in uploadList">
      <Progress v-if="item.showProgress" :percent="item.percentage" status="active"></Progress>
    </div>
  </div>

  <!-- <EMSTable ref="listTable" :server="server" :isPage="false" action="findFileInfo" :columnsFn="getColumnsFun" :params="params" @on-selection-change="handle_sel_table">
      <div slot="table-bar">
        <Button type="info"  @click="exportItem">选择附件</Button>
        <Button :disabled="selections.length <= 0" type="warning" icon="android-download" @click="go_back">批量下载</Button>
        <Button type="success"  @click="exportItem">提交</Button>
        <Button type="error"  @click="close">关闭</Button>
      </div>
  </EMSTable>-->
</template>

<script>
import { EMSTable } from "ems-components";
import Server from "./serverChild.js";
import extend from "extend";
import { exportFile } from "./downloadFile.js";
const server = new Server();
export default {
  name: "UploadFile",
  components: { EMSTable },
  props: {
    ids: {
      type: String,
      default: ""
    },
    fileNum: {
      type: String,
      default: ""
    },
    closeBtn: {
      type: Boolean,
      default: true
    },
    uploadBtn: {
      type: Boolean,
      default: true
    }
  },
  data() {
    let ids = this.ids || "";
    const uploadUrl = `${process.env.API.emsReceivable}/claim/file/upload`;
    const crctoken = sessionStorage.crctoken; //$axios.defaults.headers.crctoken
    return {
      loading: false,
      server: server,
      tableData: [],
      selections: [],
      uploadUrl: uploadUrl,
      headers: {
        crctoken: crctoken
      },
      uploadList: [],
      params: {
        fileIds: ids
      },
      columns: [
        {
          type: "selection",
          width: 45,
          fixed: "left",
          align: "center"
        },
        {
          title: "操作",
          key: "action",
          width: 120,
          align: "center",
          fixed: "left",
          render: (h, params) => {
            if (this.uploadBtn) {
              return h("RowTools", {
                props: {
                  data: [
                    {
                      text: "下载",
                      handle: () => {
                        this.down(params.row.fileId);
                      }
                    },
                    {
                      text: "删除",
                      handle: () => {
                        this.del(params.row.fileId);
                      }
                    }
                  ]
                }
              });
            } else {
              return h("RowTools", {
                props: {
                  data: [
                    {
                      text: "下载",
                      handle: () => {
                        this.down(params.row.fileId);
                      }
                    }
                  ]
                }
              });
            }
          }
        },
        {
          title: "附件名称",
          align: "center",
          key: "fileName",
          minWidth: 240,
          render: (h, params) => {
            let val = params.row.fileName;
            return h(
              "div",
              {
                attrs: {
                  class: "ivu-table-cell ivu-table-cell-ellipsis",
                  title: val
                }
              },
              val
            );
          }
        },
        {
          title: "创建人",
          align: "center",
          key: "createdByName",
          minWidth: 240,
          render: (h, params) => {
            let val = params.row.createdByName;
            return h(
              "div",
              {
                attrs: {
                  class: "ivu-table-cell ivu-table-cell-ellipsis",
                  title: val
                }
              },
              val
            );
          }
        },
        {
          title: "上传时间",
          align: "center",
          key: "createdByTime",
          minWidth: 240,
          render: (h, params) => {
            let val = params.row.createdByTime;
            return h(
              "div",
              {
                attrs: {
                  class: "ivu-table-cell ivu-table-cell-ellipsis",
                  title: val
                }
              },
              val
            );
          }
        }
      ]
    };
  },
  created: function() {
    //设置弹窗 操作
    this.$emit("SetTitle", "上传附件");
    // let buttons = [
    //   {
    //     text: "确定",
    //     theme: "primary",
    //     action: "save",
    //     handle: () => {
    //       this.saveInfo();
    //     }
    //   }
    // ];
    // this.$emit("SetPageActions", buttons);
    this.ids && this.fetchData();
    this.fileNum && this.fetchData(true);
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
  methods: {
    async fetchData(firstEdit) {
      this.loading = true;
      let params = {
        page: {
          currentPage: 1,
          pageNum: 0,
          pageSize: 100000
        },
        params: firstEdit ? { fileNum: this.fileNum } : this.params,
        sortDTO: {
          fieldName: "string",
          orderBy: "string"
        }
      };
      let data = await this.server.findFileInfo(params);
      if (data.statusCode === "-1") {
        this.$Message.error(data.msg);
      } else {
        this.selections = [];
        this.tableData = (data.data && data.data.list) || [];

        if (firstEdit) {
          const fids = [];
          this.tableData.map(item => {
            fids.push(item.fileId);
          });
          this.params.fileIds = fids.join(",");
        }
      }
      this.loading = false;
    },
    handle_sel_table(selection) {
      this.selections = selection;
    },
    beforeUpload(file) {
      this.loading = true;
      //任何格式  最大60M
      const isLt2M = file.size <= 60 * 1024 * 1024;
      if (!isLt2M) {
        this.loading = false;
        this.$Message.error("上传附件大小不能超过60MB!");
      }
      return isLt2M;
    },
    onSuccess(response, file, fileList) {
      if (response.statusCode === "-1") {
        this.$Message.error(response.msg || "上传附件失败");
      } else {
        this.params.fileIds += this.params.fileIds ? `,${response.data}` : `${response.data}`;
        this.$emit("inputData", this.params.fileIds);
        this.fetchData();
      }
    },
    onError(error, file, fileList) {
      this.$Message.error(error.message || "上传附件失败");
    },
    //删除附件
    async del(id) {
      let res = await this.server.fileDel({ fileId: id });
      if (res.statusCode === "-1") {
        this.$Message.error(res.msg || "删除附件失败");
      } else {
        let arrs = this.params.fileIds.split(",");
        arrs.splice(arrs.indexOf("" + id), 1);
        this.params.fileIds = arrs.join(",");
        this.$emit("inputData", this.params.fileIds);
        this.$Message.success(res.msg || "删除附件成功");
      }
      if (this.params.fileIds.length == 0) {
        this.tableData = [];
      } else if (this.params.fileIds.length > 0) {
        this.fetchData();
      }
    },
    //下载附件
    async down(id) {
      let res = await this.server.fileDown({ fileId: id });
      if (res.statusCode === "-1") {
        this.$Message.error(res.msg || "下载附件失败");
      } else {
        exportFile(res);
      }
    },
    //批量下载
    async batchDown() {
      let ids = this.selections.map(item => item.fileId);
      let res = await this.server.fileBatchDown({ fileIds: ids && ids.join(",") });
      if (res.statusCode === "-1") {
        this.$Message.error(res.msg || "批量下载附件失败");
      } else {
        exportFile(res);
      }
    },
    async GETbatchDown() {
      let ids = this.selections.map(item => item.fileId);
      let res = await this.server.GETfileBatchDown(ids.join(","));
      if (res.statusCode === "-1") {
        this.$Message.error(res.msg || "批量下载附件失败");
      } else {
        exportFile(res);
      }
    },
    //关闭
    close() {
      this.$emit("Close", this.params.fileIds);
      return;
      // if (this.ids.length !== this.params.fileIds.length) {
      //   this.$Modal.confirm({
      //     title: "关闭提示",
      //     content: "<p>你上传的文件还未提交；确定要关闭么？</p>",
      //     "ok-text": "确定",
      //     "cancel-text": "取消",
      //     loading: true,
      //     onOk: async () => {
      //       let ids = this.params.fileIds && this.params.fileIds.split(',');
      //       let oldIds = this.ids && this.ids.split(',');
      //       ids.forEach(item=>{
      //         if(!oldIds.includes(item)){
      //           //循环删除文件
      //           this.server.fileDel({ fileId: item });
      //         }
      //       });
      //       this.$Modal.remove();
      //       this.$emit("Close",this.ids);
      //     },
      //     onCancel: () => {}
      //   });
      // }else{
      //   this.$emit("Close");
      // }
    },
    //提交
    save() {
      this.$emit("Close", this.params.fileIds);
    }
  }
};
</script>

