<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入文件名称"
          clearable
          size="small"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传时间" label-width="80px">
         <el-date-picker
          style="margin-top:5px;"
          v-model="dateRange"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button plain size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <br>
      <el-form-item>
        <el-upload
          ref="upload"
          class="upload-demo"
          action="#"
          :limit = 1
          :on-change="handleChange"
          :auto-upload="false"
          accept=".xlsx,.xls"
          style="display:inline-block;vertical-align: top;"
          >
          <el-button size="mini" plain>上传文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="adminList" >
      <el-table-column label="序号" align="center" prop="" show-overflow-tooltip >
        <template slot-scope="scope">
         {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="id" align="center" prop="id"  show-overflow-tooltip />
      <el-table-column label="文件名称" align="center" prop="oriName"  show-overflow-tooltip />
      <el-table-column label="文件大小" align="center" prop="fileSize"  show-overflow-tooltip >
        <template slot-scope="scope">
          {{(scope.row.fileSize / 1024).toFixed(2)}}Kb
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createTime"  show-overflow-tooltip />
      <el-table-column label="文件失效时间" align="center" prop="expriceAt"  show-overflow-tooltip />
      <!-- <el-table-column label="文件是否生效" align="center" prop="activeFlag"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span :class="scope.row.activeFlag == '0' ? 'danger' :  'success'">{{scope.row.activeFlag == '0' ? '未生效' :  '生效'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="文件状态" align="center" prop="delFlag"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span :class="scope.row.delFlag == '0' ? 'success' :  'danger'">{{scope.row.delFlag == '0' ? '未删除' :  '删除'}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"   >
        <template slot-scope="scope">
          <el-button v-if ="scope.row.url && scope.row.delFlag == '0' && scope.row.activeFlag == '1'"
            size="mini"
            type="text"
            icon="el-icon-bottom"
            @click="handleExport(scope.row)"
          >下载</el-button>
          <el-button v-if ="!scope.row.url || scope.row.delFlag != '0' || scope.row.activeFlag != '1'"
            size="mini"
            type="text"
            icon="el-icon-bottom"
            disabled
            @click="handleExport(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { addChannel, updataChannel, delChannel,  fileId, uploadFileApi, fileTakeEffect, getFile, listRecharge } from "@/api/system/product";
export default {
  name: "admin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      dialogFormVisible:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图片显示
      fileList:[{"url":''}],
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
      },


      //  上传图片
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageInfo: {},
      imageList: [],
      formInline: {
          image64: "",
          imageName: "",
      },
      formData:undefined,
      limit:100,
      num:0,
      form:{}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleRemove(file) {
      this.form.logo = undefined
      // this.$nextTick(() => {
      //       this.$refs['form'].clearValidate(['logo']);
      //   })
      this.limit = 100
      document.getElementsByClassName("el-upload-list el-upload-list--picture-card")[0].firstChild.remove()
      document.getElementsByClassName("el-upload--picture-card")[0].style.display="block"
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      if(this.dateRange.length>0){
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      }
      listRecharge(this.queryParams).then(response => {
        this.total = response.data.total;
        this.adminList = response.data.records
        this.loading = false;
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ids: undefined,
        name: undefined,
        aliasName: undefined,
        adminType: "Y",
      };
      this.fileList=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.startTime = undefined
      this.queryParams.endTime = undefined
      this.queryParams.name = undefined
      this.handleQuery();
    },


    handleChange(param){
      this.limit = 1
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        fileId().then(res=>{ //获取文件批号
          this.form.batchNo = res.data
          this.formData = new FormData()// FormData 对象
          this.formData.append('files', param.raw)
          this.form.businessType = "充值表格"
          uploadFileApi(this.form.batchNo,this.form.businessType,this.formData).then(response => {
            if(response.data.length>0){
              let ids = new FormData()
              ids.append('ids[]', response.data[0].id)
              // 上传生效
              fileTakeEffect(response.data[0].batchNo,ids).then(response => {
                if(res.status == "SUCCESS"){
                  this.msgSuccess("上传成功");
                  this.$refs.upload.submit();
                  this.getList()
                }else{
                  this.$message.error(res.msg)
                }
              }).catch(err =>{
              })
            }
          })
          .catch((e) => {
            this.$message.error('上传失败')
            this.getList();
          })
        })
      }
    },
    handSuccess(){
      this.$refs.img.clearValidate();
    },
     //变化设置图片
    onChange(file, fileList) {
      this.form.file = fileList;
    },
    /** 提交按钮 */
    submitForm(row) {
      if(this.form.logo){
      }else{
          this.$refs.img.clearValidate();
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          // 上传图片
          this.form.businessType = "产品logo",
          uploadFileApi(this.form.batchNo,this.form.businessType,this.formData).then(response => {
            if(response.data.length>0){
              let ids = new FormData()
              ids.append('ids[]', response.data[0].id)
              // 上传图片生效
              fileTakeEffect(response.data[0].batchNo,ids).then(response => {
                // this.msgSuccess("上传成功");
                if (this.form.id != undefined) {
                  updataChannel(this.form).then(response => {
                    this.loading = false,
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }).catch(()=>{
                    this.loading = false,
                    this.open = false
                  })
                } else {
                  addChannel(this.form).then(response => {
                    this.loading = false,
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }).catch(()=>{
                    this.loading = false,
                    this.open = false
                  })
                }
              }).catch(err =>{
              })
            }
          })
          .catch((e) => {
            this.$message.error('上传失败')
            this.getList();
          })
          // this.removeImg()
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delChannel(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.msgSuccess("刷新成功");
      });
    },
    /** 导出按钮操作 */
    handleExport(row) {
        var a = document.createElement("a"); //创建一个<a></a>标签
        a.href = row.url; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
        a.download = row.oriName; //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
        a.style.display = "none"; // 障眼法藏起来a标签
        document.body.appendChild(a); // 将a标签追加到文档对象中
        a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
        a.remove();
    },
  }
};
</script>
<style lang="scss" scoped>
.el-upload-list{
  display: none !important;

}
</style>

