<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="材料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入材料名称"
          show-word-limit v-no-whitespace
          maxlength="20"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人姓名" prop="createUser" label-width="85px">
        <el-input
          v-model="queryParams.createUser"
          placeholder="请输入创建人姓名"
          show-word-limit v-no-whitespace
          maxlength="20"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :editable="false"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="isSelectable"/>
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="indexContinuous(queryParams.pageNum, queryParams.pageSize)"
      />
      <el-table-column label="材料名称" align="center" prop="materialName" />
      <el-table-column label="材料模板" align="center" prop="materialTemplate" >
        <template slot-scope="scope">
          <span @click="preview(scope.row)" style="cursor: pointer">预览</span>
        </template>
      </el-table-column>
      <el-table-column label="大小（KB）" align="center" prop="materialSize" />
      <el-table-column label="状态" align="center" key="materialType">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.materialType" active-value="1" inactive-value="0"
                     @change="handleStatusMaterial(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUser" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['system:post:edit']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
            v-if="scope.row.status == '0'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="文件预览" :visible.sync="previewOpen" width="90%" append-to-body>
      <div style="width: 100%;height:720px">
        <bns-kkFile-preview :items="filePreview"></bns-kkFile-preview>
      </div>
    </el-dialog>

    <!-- 添加或修改材料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-input v-model="form.addressId" v-show="false" max="100"/>-->
        <el-form-item label="请输入" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入材料名称" maxlength="20" show-word-limit v-no-whitespace/>
        </el-form-item>
        <el-form-item prop="fileList">
          <el-upload
            multiple
            :show-file-list="true"
            class="upload-demo"
            action="#"
            :limit="limit"
            :file-list="form.fileList"
            :on-change="fileChange"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :auto-upload="false"
            :accept="`.xlsx, .xls, .doc, .docx, .pdf`"
            ref="upload"
            >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传excel/word/pdf文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-preventReClick="5000">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMaterial,
  changeMaterialStatus,
  delMaterial,
  getMaterial,
  listMaterials,
  updateMaterial
} from "@/api/basics/materials";
import { encryptCBC } from '@/utils/aescbc'
import bnsKkFilePreview from "@/components/pro-tabs/bns-kkFile-preview.vue";
import { downloadFile } from '@/api/tool/select'
import { indexContinuous } from '@/utils/bonus'

export default {
  name: "Post",
  components: {
    'bns-kkFile-preview': bnsKkFilePreview,
  },
  dicts: ['sys_normal_disable'],
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc","docx", "xls", "xlsx", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      materialNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      previewOpen: false,
      // 地图是否显示弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        fileList: [],
      },
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "上传材料名称不能为空", trigger: "blur" }
        ],
        fileList: [
          { required: true, message: '上传文件不能为空', trigger: 'blur' }
        ],
      },
      // 上传的文件列表
      number: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    indexContinuous,
    isSelectable(row) {
      return row.status == "0";
    },
    preview(row){
      this.filePreview = {
        filePreviewUrl: row.materialPath,
        fileName: row.materialName,
      }
      this.previewOpen = true;
    },

    //移除文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.form.fileList.splice(this.form.fileList.indexOf(file), 1);
      this.$emit("input", this.listToString(this.form.fileList));
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },

    // 对象转成指定字符串分隔
    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) : '';
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listMaterials(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        console.log('response:', response.rows)
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 状态修改
    handleStatusMaterial(row) {
      let text = row.materialType === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.materialName + '"模板吗？').then(function () {
        return changeMaterialStatus(row.materialId, row.materialType);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.materialType = row.materialType === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: undefined,
        materialName: undefined,
        fileList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.materialNames = selection.map(item => item.materialName)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增材料模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        console.log('response:', response.data)
        this.form = response.data;
        this.form.fileList = [{
          name: response.data.materialName,
          size: response.data.materialSize,
          url: response.data.materialPath
        }];
        this.open = true;
        this.title = "编辑材料模板";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        let fileSize = this.form.fileList[0].size
        //转换成Mb
        fileSize = fileSize / 1024
        let reqData = new FormData()
        this.form.size = fileSize
        reqData.append('materialName', encryptCBC(this.form.materialName))
        reqData.append('size', encryptCBC(this.form.size))
        Promise.all([
          this.getFileData(this.form.fileList)
        ]).then(([fileList]) => {
          if (!fileList || fileList.length === 0) {
            reqData.append('file', new Blob())
          } else {
            fileList.forEach(item => reqData.append('file', item))
          }
          if (this.form.materialId !== undefined) {
            reqData.append('materialId', encryptCBC(this.form.materialId))
            updateMaterial(reqData).then(response => {
              // this.$modal.closeLoading();
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.form.fileList = [];
              this.getList();
            });
          } else {
            addMaterial(reqData).then(response => {
              // this.$modal.closeLoading();
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.form.fileList = [];
              this.getList();
            });
          }
        })

          // this.$refs.upload.submit();
      });
    },

    async imgUpload (info) {
      console.log('info:', info)
      const { file } = info
      this.file = file
      if (!file) {
        return
      }
      console.log(jakldsjalsk)
      //获取文件大小
      let fileSize = file.size
      //转换成Mb
      fileSize = fileSize / 1024
      let formData = new FormData()
      formData.append('file', file)
      this.$refs["form"].validate(valid => {
        if (valid) {
          //把fileSize添加到from里
          this.form.size = fileSize
          formData.append('materialName', encryptCBC(this.form.materialName))
          formData.append('size', encryptCBC(this.form.size))
          if (this.form.materialId !== undefined) {
            formData.append('materialId', encryptCBC(this.form.materialId))
            updateMaterial(formData).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.form.fileList = [];
              this.getList();
            });
          } else {
            addMaterial(formData).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.form.fileList = [];
              this.getList();
            });
          }
        }
      });
    },
    // 提取公共方法，获取fileList中具有raw属性的文件
    getFileData(fileList) {
      return Promise.all(fileList.filter(item => item?.hasOwnProperty('raw')).map(item => item.raw))
    },
    /** 获取文件数据 */
    fileChange(file, fileList){
      console.log("w2e")
      if(file.size > 1024 * 1024 * 10){
        this.$message.warning('文件大小不能超过10Mb')
        fileList = fileList.filter(item => {
          return item.uid !== file.uid
        })
       return
      }
      this.form.fileList = fileList;
      console.log('file:', this.form.fileList )

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialId = row.materialId || this.ids;
      const materialName = row.materialName || this.materialNames;
      this.$modal.confirm('是否确认删除材料名称为"' + materialName + '"的数据项？').then(function() {
        return delMaterial(materialId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    // 下载
    handleDownload(row) {
      console.log(row)
      console.log(JSON.stringify(row))
      // 假设 scope.row 中有一个 fileUrl 属性，代表要下载的文件的URL
      const fileUrl = row.materialPath;

      downloadFile( fileUrl,'');
    }
  }
};
</script>
