<template>
  <com-dialog
    title="火调档案管理"
    enterText="上传附件"
    :hideFloor="user.info.departmentId != organizerDeptId"
    :show="show"
    @submit="oper.readyInsert"
    @update:show="val => $emit('update:show', val)"
  >
    <div class="body-layer" style="padding: 0">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%;min-height:540px;max-height:540px"
        :span-method="arraySpanMethod"
      >
        <el-table-column label="附件标题" v-slot:default="{row}">
          <span :class="{title: row._title}">{{row._title ? row._title : row.fileName}}</span>
        </el-table-column>
        <el-table-column label="创建人" prop="creatorName"></el-table-column>
        <el-table-column label="创建日期" prop="updateTime" width="200" v-slot:default="{row}">
          {{row.updateTime ? row.updateTime.toString() : ''}}
        </el-table-column>
        <el-table-column label="操作" v-slot:default="{ row }" width="150">
          <a class="oper-span" :href="row.fileOssUrl" target="_blank">查看</a>
          <span class="oper-span" @click="downloadFile(row.fileOssUrl, row.fileName)">下载</span>
          <span class="oper-span" 
            :class="{disable: user.info.departmentId != organizerDeptId}" 
            @click="user.info.departmentId == organizerDeptId && deleteItem(row)" 
            style="color: var(--primaryColor)">
          删除
          </span>
        </el-table-column>
      </el-table>
    </div>
  </com-dialog>

  
  <com-dialog
    title="上传附件"
    v-model:show="oper.state.show"
    width="540"
    enterText="确 定"
    @submit="submit"
  >
    <el-form ref="form" :model="form" label-width="90px" class="camera-from dispatch-file-from">
      <el-form-item label="附件标题：" class="mandatory">
        <el-input v-model="oper.state.fileName" class="arch-name" placeholder="请输入最多不能超过50字" maxlength="50" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="附件类型：" class="mandatory">
        <el-select v-model="oper.state.attachmentType" placeholder="请选择">
            <el-option
              v-for="item in types"
              :key="item.name"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="附件：" class="mandatory">
        <el-upload
          class="upload-demo"
          :http-request="uploadFile"
          :multiple="false"
          :limit="1"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :file-list="oper.state.fileList"
          >
          <el-button size="medium" type="primary"  :disabled="!!oper.state.fileOssUrl" @click="ev => oper.state.fileOssUrl && ev.stopPropagation()"><i class="el-icon-upload2 el-icon--left"></i>上传</el-button>
          <template v-slot:tip>
            <div class="el-upload__tip">注：可上传100M以内的pdf、jpg、word文件</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </com-dialog>

</template>

<script>
import getTableState from "@/state/tableRef";
import {
  getAttachList,
  unbindCamera,
  insertAttach,
  uploadAttachFile,
  uploadAttachImage,
  deleteAttachFile
} from '@/request/config'
import comDialog from "@/components/dialog";
import user from '@/state/user'
import axios from 'axios';
import { watch } from 'vue';
import { downloadFile } from '@/util'
const fileTypes = ['pdf', 'word']
const imgTypes = ['jpeg', 'jpg']
import { types } from '@/constant'


export default {
  name: 'archives',
  props: ['show', 'data', 'organizerDeptId'],
  setup(props) {
    const state = getTableState({
      getUrl: getAttachList,
      insertUrl: insertAttach,
      delUrl: deleteAttachFile,
      delAttr: {ids: 'ids'},
      pagAttr: {list: ''},
      searchAttr: {pageSize: 12, projectId: props.data},
      operAttr: {
        attachmentType: '',
        fileOssUrl: '',
        fileName: '',
        projectId: '',
        type: '0'
      },
    });

    watch(props, () => {
      if (props.data === state.search.value.state.projectId) return
      state.search.value.state.projectId = props.data
      state.dataList.value.refer()
    })

    
    return { ...state, types, user };
  },
  methods: {
    async deleteItem(row) {
      await this.dataList.delete({ids: row.id})
      this.$emit('referList')
    },
    async unbindCamrea(data) {
      if (data.departmentId && (await this.$confirm('解绑相机，该相机拍摄的场景也将一并解绑（场景在云端存储，不会删除）确定要解绑吗？', '提示'))) {
        await axios.post(unbindCamera, data)
        data.departmentName = data.departmentId = null
      }

      this.dataList.refer()
    },
    arraySpanMethod({ row, columnIndex  }) {
      if (row._title ) {
        return columnIndex === 0 ? [1, 4] : [0, 0]
      }
    },
    async uploadFile(data) {
      let url;

      if (imgTypes.some(type => ~data.file.type.indexOf(type))) {
        url = uploadAttachImage
        this.oper.state.type = 1
      } else {
        url = uploadAttachFile
        this.oper.state.type = 2
      } 
      try {
        let res = await axios.post(url, {file: data.file})
        this.oper.state.fileOssUrl = res.data.ossUrl
        data.onSuccess()
        console.log('chengg');
      } catch {
        data.onError()
        console.log('shib');
      }
    },
    beforeUpload(file) {
      let successTypes = [...imgTypes, ...fileTypes]
      let maxSize = 100 * 1024 * 1024
      console.log('oper.state.fileList',this.oper.state.fileList)
      if (!successTypes.some(type => ~file.type.indexOf(type))) {
        this.$message.error(`请上传${successTypes.join('、')}等格式的文件`, '提示')
        return false
      } else if (file.size > maxSize) {
        this.$message.error('请上传100M以内的文件', '提示')
        return false
      } else {
        return true
      }
    },
    beforeRemove() {
      this.oper.state.fileOssUrl = void 0
    },
    submit() {
      this.oper.state.projectId = this.search.state.projectId
      if (!this.oper.state.attachmentType) {
        return this.$message.error('附件类型不能为空！', '提示')
      } else if (!this.oper.state.fileOssUrl || !this.oper.state.fileOssUrl.trim()) {
        return this.$message.error('请上传附件!', '提示')
      } else if (!this.oper.state.fileName || !this.oper.state.fileName.trim()) {
        return this.$message.error('附件标题不能为空！', '提示')
      }
      console.log('this.oper.state.id ',this.oper.state.id )
      this.oper.state.id ? this.oper.update() : this.oper.insert()

      this.$emit('referList')
    },
    downloadFile
  },
  computed: {
    tableData() {
      let dataList = this.dataList.state || []
      let data = this.types.reduce((t, c) => 
        t.concat(
          {_title: c.name},
          dataList.filter(item => c.name === item.attachmentType)
        )
      , [])

      
      data = data.concat(dataList.filter(item => !data.includes(item)))
      return data
    }
  },
  components: {
    "com-dialog": comDialog,
  }
};
</script>

<style lang="scss" scoped>
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}


.title {
  font-weight: bold;
  color: #26559B;
  line-height: 19px;
  font-size: 14px;
}
</style>

<style>
.upload-demo .el-upload {
  line-height: initial;
}

.upload-demo .el-upload-list .el-icon-close-tip {
  display: none !important;
}
.arch-name .el-input__inner{
  padding-right: 50px;
}
</style>