<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="请输入资料名称"
          maxlength="60"
          show-word-limit
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label-width="60px" label="提交人" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入提交人姓名"
          maxlength="20"
          show-word-limit
          clearable
          v-no-whitespace
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label-width="100px" label="提交时间范围">
        <el-date-picker
          v-model="createTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          :editable="false"
          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-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:proList:export']"-->
      <!--        >导出数据-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5" v-for="dict in dict.type.sys_pro_material_type" :key="dict.value">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleUpload(dict)">
          上传{{ dict.label }}
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange" border>
      <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="materialSize" />
      <el-table-column label="资料类型" align="center" prop="materialType" />
      <el-table-column label="提交人" align="center" prop="createName" />
      <el-table-column label="提交时间" align="center" prop="commitTime" />
      <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-picture-outline"
            @click="preview(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']"
          >
            删除
          </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="title" :visible.sync="open" width="560px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="fileList">
          <el-upload
            multiple
            drag
            accept=" .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf "
            :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"
            ref="upload"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__text">只能上传 word/excel/ppt/pdf 文件，且不超过10MB</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>

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

<script>
import {
  delMaterials,
  engineeringMaterialUpload,
  specificProMaterial,
} from '@/api/proMaterialStatistics/proMaterialManagement'
import F from '@/components/pro-tabs/bns-kkFile-preview.vue'
import { downloadFile } from '@/api/tool/select'
import { indexContinuous } from '@/utils/bonus'
import bnsKkFilePreview from '@/components/pro-tabs/bns-kkFile-preview.vue'

export default {
  name: 'Post',
  dicts: ['sys_pro_material_type'],
  components: {
    'bns-kkFile-preview': bnsKkFilePreview,
  },

  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pdf'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 具体资料列表数据
      materialList: [],
      materialPath: undefined,
      viewOpen: false,
      filePreview: {
        filePreviewUrl: '',
        fileName: '',
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      createTime: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: undefined,
        createName: undefined,
        startDate: undefined,
        endDate: undefined,
      },
      // 表单参数
      form: {
        fileList: [],
        proId: undefined,
        uploadType: undefined,
      },
      // 表单校验
      rules: {
        fileList: [{ required: true, message: '请上传工程资料', trigger: 'blur' }],
      },

      // 上传的文件列表
      fileList: [],
    }
  },
  created() {
    this.getList()
  },
  methods: {
    indexContinuous,
    //判断是否选择工程创建时间
    judgeTime() {
      if (this.createTime !== undefined) {
        this.queryParams.startDate = this.createTime[0]
        this.queryParams.endDate = this.createTime[1]
      }
    },
    /** 查询具体工程资料列表 */
    getList() {
      this.loading = true
      this.judgeTime()
      this.queryParams.proId = this.$route.params.proId
      specificProMaterial(this.queryParams).then(response => {
        this.materialList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        proId: undefined,
        materialName: undefined,
        createName: undefined,
        proType: undefined,
        proStatus: undefined,
        startDate: undefined,
        endDate: undefined,
        fileList: undefined,
        postSort: 0,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.judgeTime()
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.startDate = undefined
      this.queryParams.endDate = undefined
      this.createTime = undefined
      this.queryParams.proId = this.$route.params.proId
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.proId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 预览按钮操作 */
    preview(row) {
      console.log(row)
      this.filePreview = {
        filePreviewUrl: row.materialPath,
        fileName: row.materialName,
      }
      this.viewOpen = true
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      // 假设 scope.row 中有一个 fileUrl 属性，代表要下载的文件的URL
      const fileUrl = row.materialPath
      const materialName = row.materialName
      console.log(row)
      downloadFile(fileUrl, materialName)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      const materialName = row.materialName
      this.$modal
        .confirm('是否确认删除资料名称为 "' + materialName + '" 的数据项？')
        .then(function () {
          return delMaterials(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 上传日常资料按钮操作跳转弹窗 */
    handleUpload(item) {
      console.log(item)
      //打印dict.type.sys_pro_material_type
      console.log(this.dict.type.sys_pro_material_type)
      this.open = true
      this.title = '上传' + item.label
      this.form.uploadType = item.value
    },
    /** 上传交底资料按钮操作跳转弹窗 */
    handleUploadJdMaterialDialog() {
      this.open = true
      this.title = '上传交底资料'
      this.form.uploadType = 1
    },

    /** 提交确定按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        console.log(this.form.fileList)
        const reqData = new FormData()
        reqData.append('proId', this.$route.params.proId)
        reqData.append('uploadType', this.form.uploadType)
        Promise.all([this.getFileData(this.form.fileList)]).then(([fileList]) => {
          fileList.forEach(item => reqData.append('fileList', item))
          engineeringMaterialUpload(reqData).then(response => {
            this.open = false
            this.$modal.msgSuccess('新增成功')
            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(fileList)
      if (file.size > 1024 * 1024 * 10) {
        this.$message.warning('文件大小不能超过10Mb')
        fileList = fileList.filter(item => {
          return item.uid !== file.uid
        })
      }
      this.form.fileList = fileList
    },
    //移除文件
    handleRemove(file) {
      this.form.fileList.splice(this.form.fileList.indexOf(file), 1)
      this.$emit('input', this.listToString(this.form.fileList))
    },
    // 对象转成指定字符串分隔
    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) : ''
    },
    /** 文件超出个数限制时的钩子 */
    handleExceed(files, fileList) {
      this.$message.warning(
        `单次上传限制 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    /** 导出按钮操作 */
    handleExport() {
      this.derive(
        'project/pro/export',
        {
          ...this.queryParams,
        },
        `工程信息.xlsx`
      )
    },
  },
}
</script>
