<!--
 * @desc 项目管理
 * @author linyuanjie
 * @date 2021/6/22
-->

<template>
  <div>
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange">
        <template slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="addBtn"
          >新 增</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="editViewFn(scope.row, 'view')"
          >查 看</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="editViewFn(scope.row, 'edit')"
          >编 辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="delFn(scope.row)"
          >删 除</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
      :title="dialogType === 'add' ? '新增' : dialogType === 'edit' ? '编辑' : '查看'"
      :visible.sync="dialogShow"
      v-if="dialogShow"
      width="60%"
      class="dialog-form"
      :before-close="handleClose"
    >
      <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogForm" label-width="140px" :disabled="dialogType === 'view'">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目编号：" prop="projectNumber">
              <el-input v-model="dialogForm.projectNumber" placeholder="请输入项目编号" :disabled="dialogForm.readOnlyFlag === 1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称：" prop="projectName">
              <el-input v-model="dialogForm.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="委托方：" prop="delegate">
              <el-input v-model="dialogForm.delegate" placeholder="请输入委托方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目签约时间：" prop="signTime">
              <el-date-picker
                class="w100"
                v-model="dialogForm.signTime"
                type="datetime"
                placeholder="选择项目签约时间"
                :value-format="'yyyy-MM-dd HH:mm:ss'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归档时间：">
              <el-date-picker
                class="w100"
                v-model="dialogForm.updateTime"
                type="datetime"
                placeholder="无需输入，系统自动生成"
                disabled
                :value-format="'yyyy-MM-dd HH:mm:ss'">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="静态证据：" prop="evidenceList">
              <el-upload
                v-if="dialogType !== 'view'"
                action="/admin/sys-file/upload"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-remove="handleRemove"
                :before-upload="handleBeforeUpload"
                multiple
                :show-file-list="false"
                accept=".bmp,.png,.jpeg,.jpg,.gif,.doc,.docx,.pdf,.txt,.xlsx,.xls"
                :file-list="fileList">
                <el-button v-if="dialogType !== 'view'" size="small" type="primary">点击上传</el-button>
                <div v-if="dialogType !== 'view'" slot="tip" class="el-upload__tip">上传文件同步至服务器(*.bmp;*.png;*.jpeg;*.jpg;*.gif;*.xlsx;*.xls;*.doc;*.docx;*.pdf;*.txt)</div>
              </el-upload>
              <div v-if="this.fileList.length" class="file-show-list">
                <div
                  v-for="(file, index) in fileList"
                  :key="file.url"
                  class="file-item mb8 df_sb">
                  <div class="file-name"><i class="el-icon-document mr7" style="color: #909399;"></i>{{ file.name }}</div>
                  <div class="operate-btn f12">
                    <span v-if="dialogType !== 'view'" class="del-btn fr" @click="handleRemove(file)">删除</span>
                    <span v-if="dialogType !== 'add'" class="down-btn mr7 fr" @click="downFile(file)">下载</span>
                    <span v-if="['bmp', 'png', 'jpeg', 'jpg', 'gif'].includes(file.type)" class="view-btn mr7 fr" @click="imgView(file, index)">查看</span>
                  </div>
                  <!-- el-image预览小图通过css隐藏了, 这里通过showViewer API进行大图预览 -->
                  <el-image
                    :ref="'imgViewer' + index"
                    class="imgViewer"
                    :src="file.url"
                    :preview-src-list="[file.url]">
                  </el-image>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注：">
              <el-input v-model="dialogForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">关 闭</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" :loading="buttonLoading" @click="submitBtn('dialogForm')">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import {fetchList, addObj, putObj, delObj} from '@/api/archivesManagement/project'
import {tableOption} from '@/const/crud/archivesManagement/project'
import store from '@/store'

export default {
  name: 'project',
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      dialogType: 'add',
      dialogForm: {
        evidenceList:  []
      },
      dialogFormRules:{
        projectNumber:[
          { required: true, message: '请输入项目编号', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1-100 个字符', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
          { min: 1, max: 100, message: '长度在 1-100 个字符', trigger: 'blur' }
        ],
        delegate: [
          { required: true, message: "请输入委托方", trigger: "blur" },
          { min: 1, max: 100, message: '长度在 1-100 个字符', trigger: 'blur' }
        ],
        signTime: [
          { required: true, message: "请输入项目签约时间", trigger: "blur" }
        ],
        evidenceList: [
          { required: true, message: "请上传静态证据", trigger: "change" }
        ]
      },
      dialogShow: false,
      buttonLoading: false,
      headers: { Authorization: 'Bearer ' + store.getters.access_token },
      fileList: []
    }
  },
  methods: {
    getList(page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm )).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading=false
      })
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize
    },
    currentChange(current){
      this.page.currentPage = current
    },
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange() {
      this.getList(this.page)
    },
    // 弹窗打开前
    beforeOpen(show, type) {
      this.$nextTick(() => {
        const rowData = this.$refs.crud.$refs.dialogForm.value
        // 当项目关联积分包时, 不允许修改projectNumber
        for (let i = 0; i < this.tableOption.column.length; i++) {
          if (this.tableOption.column[i].prop === 'projectNumber') {
            this.tableOption.column[i].disabled = rowData.readOnlyFlag === 1 // 0：可以修改，1：只读
            break
          }
        }
      })
      show()
    },
    addBtn() {
      this.dialogType = 'add'
      this.dialogShow = true
    },
    editViewFn(row, type) {
      this.dialogType = type
      this.dialogForm = row
      if (row.evidenceList.length) {
        row.evidenceList.forEach(ele => {
          this.fileList.push({ name: ele.filename, url: ele.url, type: ele.type })
        })
      }
      this.dialogShow = true
    },
    delFn(row) {
      if (row.readOnlyFlag === 1) { // 0：可以修改，1：只读，即不可删除
        return this.$message.warning('此项目有关联的积分包，不能删除')
      }
      this.$confirm('确定删除？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleClose() {
      this.dialogShow = false
      this.dialogForm = this.$options.data().dialogForm
      this.fileList = []
    },
    submitBtn(formName) {
      this.dialogForm.evidenceList = []
      this.fileList.forEach(ele => {
        this.dialogForm.evidenceList.push({ url: ele.url, filename: ele.name, type: ele.type })
      })
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if(!(this.dialogForm.evidenceList && this.dialogForm.evidenceList.length > 0)) this.dialogForm.evidenceList=null
          if(this.dialogType === 'add'){
            addObj(this.dialogForm).then(res => {
              this.$message.success('新增成功')
              this.getList(this.page)
              this.buttonLoading = false
              this.handleClose()
            }).catch(() => {
              // this.$message.error('新增失败')
              this.buttonLoading = false
            })
          }else{
            putObj(this.dialogForm).then(data => {
              this.$message.success('编辑成功')
              this.getList(this.page)
              this.buttonLoading = false
              this.handleClose()
            }).catch(() => {
              // this.$message.error('编辑失败')
              this.buttonLoading = false
            });
          }
        } else {
          console.log('error submit!!')
          return false
        }
      });
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        // 上传成功
        const { url } = response.data
        const type = file.name && file.name.split('.')[file.name.split('.').length - 1]
        this.fileList.push({ name: file.name, url, type })
      } else {
        this.$message.error('上传出错：' + response.msg)
      }
    },
    handleUploadError(err, file, fileList) {
      if (err && JSON.parse(JSON.stringify(err)).status === 401) {
        this.$message.error('用户凭证已过期')
      } else {
        this.$message.error('上传失败，请重试')
      }
    },
    // 删除
    handleRemove(file) {
      this.$confirm(`确定删除 ${file.name} ？`,{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i]['url'] === file['url']) {
            this.fileList.splice(i, 1)
            break
          }
        }
      }).catch(() => {})
    },
    // 下载
    downFile(file) {
      let link = document.createElement("a")
      link.style.display = 'none'
      link.href = file.url
      link.setAttribute('download', file.name)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    // 查看
    imgView(file, index) {
      this.$refs['imgViewer' + index][0].showViewer = true
    },
    // 上传前, 判断支持的文件格式
    handleBeforeUpload(file) {
      const limitedType = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/bmp',
        'image/jpg',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // docx
        'application/msword', // doc
        'application/pdf',
        'text/plain', // txt
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // xlsx
        'application/vnd.ms-excel' // xls
      ]
      const isType = limitedType.includes(file.type)
      if (!isType) {
        this.$message.error('支持bmp/png/jpeg/jpg/gif/doc/docx/wps/pdf/txt/xlsx/xls格式!');
      }
      return isType
    }
  }
}
</script>
<style lang="scss" scoped>
.dialog-form {
  ::v-deep .el-dialog {
    min-width: 800px;
  }
  .file-show-list {
    .file-item {
      padding-left: 4px;
      //height: 25px;
      line-height: 20px;
      border-radius: 4px;
      cursor: pointer;
      &:hover {
        background-color: #f5f7fa;
        .file-name {
          color: #1E90FF;
        }
      }
      .file-name {
        width: calc(100% - 98px);
      }
      .operate-btn {
        width: 98px;
      }
      .view-btn,.down-btn {
        &:hover {
          color: #1E90FF;
        }
      }
      .del-btn {
        &:hover {
          color: #F56C6C;
        }
      }
      // 隐藏el-image预览小图, 通过showViewer API进行大图预览
      .imgViewer {
        ::v-deep .el-image__inner {
          display: none;
        }
        ::v-deep .el-image__error {
          display: none;
        }
      }
    }
  }
}
</style>
