<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="assemblyForm.filesList" :page.sync="page"
      :permission="permissionList" :before-open="beforeOpen" id="out-table" :header-cell-class-name="headerClassName"
      v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" plain
          :disabled="!assemblyForm.id || detailData.seeDisabled || disabled" @click="addBtnfun">新 增
        </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain :disabled="detailData.seeDisabled || disabled"
          @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menu" slot-scope="{ row, index }">
        <el-button size="small" v-if="row.isImage==0" icon="el-icon-view" type="text" @click="rowDownload(row, index)">下 载
        </el-button>
        <el-button size="small" v-if="row.isImage==1" icon="el-icon-view" type="text" @click="rowPreview(row, index)">预 览
        </el-button>
        <el-button v-if="row.edit" size="small" icon="el-icon-edit" type="text"
          :disabled="detailData.seeDisabled || disabled" @click="rowCell(row, index)">保 存
        </el-button>
        <el-button v-else size="small" icon="el-icon-edit" type="text" :disabled="detailData.seeDisabled || disabled"
          @click="rowEdit(row, index)">修 改
        </el-button>
        <!-- <el-button size="small" icon="el-icon-delete" type="text" :disabled="detailData.seeDisabled || disabled"
          @click="rowDel(row, index)">删 除
        </el-button> -->
      </template>
      <template slot-scope="scope" slot="serialNo">
        <el-input v-if="scope.row.edit" type="age" style="width: 100%;" v-model="scope.row.serialNo" size="small"
          autocomplete="off" :disabled="detailData.seeDisabled || disabled" clearable placeholder="请输入自定义序号"></el-input>
        <span v-else>{{ scope.row.serialNo }}</span>
      </template>
      <template slot="url" slot-scope="scope">
        <el-input v-if="scope.row.edit" v-model="scope.row.url" style="width: 80%;" size="small">
        </el-input>
        <el-button style="width: 20%" size="small" v-if="scope.row.edit" @click="uploadFiles(scope.row, scope.index)">
          附件
        </el-button>
        <span v-else style="color: #1e9fff;" @click="rowDownload(scope.row, scope.index)">
          {{ scope.row.url }}
        </span>
      </template>
      <template slot-scope="scope" slot="isImage">
        <el-select v-if="scope.row.edit" v-model="scope.row.isImage" size="small" placeholder="请选择">
          <el-option v-for="item in isImageData" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <span v-else>{{ scope.row.isImage ? '是' : '否' }}</span>
      </template>
      <template slot-scope="scope" slot="remarks">
        <el-input v-if="scope.row.edit" v-model="scope.row.remarks" size="small">
        </el-input>
        <span v-else>{{ scope.row.remarks }}</span>
      </template>
    </avue-crud>

    <el-dialog title="上传附件" append-to-body :visible.sync="excelBox" width="555px" v-dialog-drag placeholder="请输入">
      <avue-form :option="excelOption" v-model="excelForm" table-loading="excelLoading" :upload-before="uploadBefore"
        :upload-after="uploadAfter">
      </avue-form>
    </el-dialog>

    <!--附近弹窗-->
    <el-dialog width="80%" title="附件" :visible.sync="urlVisible" :close-on-click-modal="false" append-to-body>
      <div style="width: 50%;height: 50%;margin: 0 auto">
        <img :src="imgUrl" alt="" style="width: 100%;height: 100%;" />
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
import { filescenterList, filescenterDetail, filescenterSubmit, filescenterRemove } from "@/api/iosBasicData/filescenter";
import { mapGetters } from "vuex";
import { requiredMessage } from "@/util/messageReminder";
import website from "@/config/website";
import { getToken } from "@/util/auth";

export default {
  props: {
    detailData: {
      type: Boolean
    },
    assemblyForm: {
      type: Object
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 上传附件弹窗
      excelBox: false,
      selectIndex: null,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "附件上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            dataType: "string",
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
              url: "link"
            },
            action: "/api/blade-resource/oss/endpoint/put-file"
          }
        ]
      },
      // 是否图片
      isImageData: [{
        label: '否',
        value: 0
      }, {
        label: '是',
        value: 1
      }],
      urlVisible: false, // 附件的上传
      imgUrl: '', // 弹窗展示的图片地址

      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        cellBtn: true, // 行编辑
        column: [
          // {
          //   label: "业务类型",
          //   prop: "businessType",
          //   cell: true,
          // },
          // {
          //   label: "主表 Id",
          //   prop: "pid",
          //   rules: [{
          //     required: true,
          //     message: "请输入主表 Id",
          //     trigger: "blur"
          //   }]
          // },
          // {
          //   label: "明细 Id",
          //   prop: "itemId",
          //   rules: [{
          //     required: true,
          //     message: "请输入明细 Id",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "自定义序号",
            prop: "serialNo",
            width: "100"
          },
          // {
          //   label: "业务编号",
          //   prop: "billNo",
          // },
          // {
          //   label: "MB/L NO",
          //   prop: "mblno",
          // },
          // {
          //   label: "HB/L NO",
          //   prop: "hblno",
          // },
          {
            label: "文件名",
            prop: "fileName",
            width: "120",

          },
          {
            label: "文件扩展名",
            prop: "fileExt",
            width: "120",
          },
          {
            label: "文件地址",
            prop: "url",
            width: "500"
          },
          {
            label: "是否图片",
            prop: "isImage",
          },
          {
            label: "文件接收日期",
            prop: "receivedData",
            width: "160",
          },
          // {
          //   label: "排序",
          //   prop: "sort",
          // },
          {
            label: "备注",
            prop: "remarks",
          },

        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.filescenter_add, false),
        viewBtn: this.vaildData(this.permission.filescenter_view, false),
        delBtn: this.vaildData(this.permission.filescenter_delete, false),
        editBtn: this.vaildData(this.permission.filescenter_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 新增
    addBtnfun() {
      this.assemblyForm.filesList.push({
        pid:this.assemblyForm.id,
        edit: true
      })
      // this.$refs.crud.rowAdd()
    },
    // 点击附件按钮
    uploadFiles(row, index) {
      this.selectIndex = index
      this.excelBox = true
    },
    uploadBefore(file, done, loading) {
      done();
      loading = true;
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.$message.success("上传成功!");
      this.$set(this.assemblyForm.filesList[this.selectIndex], 'url', res.link)
      this.$set(this.assemblyForm.filesList[this.selectIndex], 'fileName', res.originalName)
      this.$set(this.assemblyForm.filesList[this.selectIndex], 'fileExt', res.originalName)
      this.$set(this.assemblyForm.filesList[this.selectIndex], 'serialNo',this.selectIndex+1)
      this.$set(this.assemblyForm.filesList[this.selectIndex], 'isImage',0)
      loading = false;
      done();
    },
    // 下载
    rowDownload(row) {
      console.log(row, 340)
      // window.open(row.url)
      window.open(`${row.url}?${this.website.tokenHeader}=${getToken()}`);
      // this.$axios.get(row.url,{
      //     responseType:'blob',
      // }).then((response)=>{
      //     console.log(response,346)
      //     const blob = new Blob([response.data],{type:'application/;charset=utf-8'})
      //     const a = document.createElement("a");
      //     a.href = URL.createObjectURL(blob)
      //     a.download = 'fileName123132123'
      //     document.body.appendChild(a)
      //     a.click()
      //     document.body.removeChild(a)
      // })
    },
    // 预览
    rowPreview(row, index) {
      this.imgUrl = row.url
      this.urlVisible = true
    },
    // 编辑
    rowEdit(row, index) {
      this.$set(row, 'edit', true)
    },
    // 保存
    rowCell(row, index) {
      // 需要加判断是否必填的数据
      const messageData = [
        {
          name: '自定义序号',
          value: 'serialNo',
        },
        {
          name: '文件地址',
          value: 'url',
        },
      ]
      // 保存
      if (!requiredMessage(row, messageData)) {
        return
      }
      if (!row.isImage && row.isImage != 0) {
        this.$message({
          message: '请选择是否是图片',
          type: 'warning'
        });
        return;
      }
      row.sort = index
      row.businessType = 'SE'
      row.pid = this.assemblyForm.id
      row.hblno = this.assemblyForm.hblno
      row.mblno = this.assemblyForm.mblno
      row.serialNo = row.serialNo
      // 保存接口
      this.filescenterSubmitfun(row)
    },
    // 保存接口
    filescenterSubmitfun(row) {
      console.log(row, 337)
      filescenterSubmit(row).then(res => {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        // 编辑
        this.$set(row, 'edit', !row.edit)
        this.$emit('billsDetailfun')
      })
    },

    rowSave(row, done, loading) {
      filescenterSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      filescenterSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row,index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          if (row.id) {
            this.assemblyForm.filesList.splice(index, 1)
            return filescenterRemove(row.id);
          } else {
            this.assemblyForm.filesList.splice(index, 1)
          }
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      // this.$confirm("确定将选择数据删除?", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // })
      //   .then(() => {
      //     return filescenterRemove(this.ids);
      //   })
      //   .then(() => {
      //     this.onLoad(this.page);
      //     this.$message({
      //       type: "success",
      //       message: "操作成功!"
      //     });
      //     this.$refs.crud.toggleSelection();
      //   });
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let multiList = []
        let arr = []
        multiList = this.selectionList
        arr = this.assemblyForm.filesList
        // 获取有id 的数据
        const itemsWithId = multiList.filter(item =>item.id!=null);
        let arrIds = itemsWithId.map(item => item.id) // 获取id 数据
        // 把选中的删除掉
        multiList.forEach((item) => {
          for (let index in arr) {
            if (JSON.stringify(item) == JSON.stringify(arr[index])) {
              arr.splice(Number(index), 1)
            }
          }
        })
        if (itemsWithId.length != 0) {
          filescenterRemove(arrIds.join(',')).then(res => {
            this.$message.success("删除成功");
          })
        }
      })
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        filescenterDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    getData(form) {
      this.assemblyForm = form
      this.onLoad(this.page, form);
    },
    onLoad(page, params = {}) {
      if (this.assemblyForm.id) {
        this.loading = true;
        filescenterList(page.currentPage, page.pageSize, Object.assign({ pid: this.assemblyForm.id }, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }

    },

    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = ""
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one"
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two"
        }
      }
      return back;
    },

  }
};
</script>

<style scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
  text-align: center;
  padding: 4px 0;
}
</style>
