<template>
  <div class="flex flex-col padding">
    <div class="flex flex-center mt-20">
      <div class="bold font-16 grey flex-child-average text-left" style="margin-left: 50px">
        <span>当前数据（{{ data.total }}）</span>
      </div>
      <div class="flex flex-center flex-child-average flex-justify-end" style="margin-right: 50px">
        <base-button v-if='permissions.permissions.home_folder_authorize' class="mr-5" icon="User" title="授权"
                     type="0" @click='showClick'/>
        <base-button v-if="permissions.permissions.floder_detail_add && isAccess === '2'" icon="Plus" title="添加文件夹"
                     class="mr-5"
                     type="0" @click="addShow = true"/>
        <base-button v-if="isAccess === '2'" icon="Upload" title="上传文件" @click="show = true"/>
      </div>
    </div>
    <files-list :data="data" class="mt-20" @change='changePage'/>
    <el-dialog v-model="show"
               append-to-body
               center
               title="附件上传（可批量）">
      <uploadFile :data='{type:1,toStatus:0}' :max='20'
                  @close='show = false'
                  @success='success'/>
    </el-dialog>

    <el-dialog v-model='authorizeShow' :show-close='false' append-to-body center>
      <template #header="{ close, titleId, titleClass }">
        <div class="flex flex-justify-between">
          <h4 :id="titleId" :class="titleClass">{{ data.folderName }}</h4>
          <el-button text type="danger" @click="close">
            <el-icon class="el-icon--left">
              <CircleCloseFilled/>
            </el-icon>
          </el-button>
        </div>
      </template>
      <authorize :list='data.records' :folder-id='id' :project-id='projectId' @close='authorizeShow = false'/>
    </el-dialog>
    <el-dialog v-model='addShow' append-to-body width='40%'>
      <div class="flex flex-col">
        <el-form ref="ruleFormRef"
                 :model="folderInfo"
                 class="demo-ruleForm"
                 label-width="120px"
                 status-icon>
          <el-form-item label="文件夹名称">
            <el-input
                v-model="folderInfo.title"
                placeholder="填写文件夹名称"
                style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <div class="full-width flex flex-center mt-10">
          <base-button icon="Lock" title="保存" type="1" @click="folderAdd"/>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import filesList from './files_list.vue'
import baseButton from '../../../components/base-button.vue'
import uploadFile from '../../../components/upload-file.vue'
import authorize from '@/views/home/component/authorize.vue'
import permissionStore from '@/store/permission.js'
import { useStore } from '@/store/user.js'

export default {
  name: 'current',
  components: { filesList, baseButton, uploadFile, authorize },
  props: {
    id: String,
    data: Object
  },
  data () {
    return {
      authorizeShow: false,
      addShow: false,
      show: false,
      folderInfo: {
        title: '',
        projectStageId: '',
        projectId: '',
        parentId: '',
        dictKey: ''
      },
      fileList: [],
      saveCount: 0,
      libraryList: [],
      projectId: '',
      sendParams: {
        ids: '',
        ownerId: '',
        projectId: ''
      },
      isAccess: ''
    }
  },
  setup () {
    const permissions = permissionStore()
    const user = useStore()
    return { permissions, user }
  },
  created () {
    this.isAccess = this.$route.query.isAccess
    this.projectId = this.$route.query.projectId
    this.folderInfo.dictKey = this.$route.query.dictKey
    this.folderInfo.projectStageId = this.$route.query.projectStageId
  },
  methods: {
    showClick () {
      this.authorizeShow = true
    },
    success (res) {
      this.fileList = res.fileList.map(res => {
        const item = {}
        item.title = res.response.data.originalFileName
        item.suffix = res.response.data.suffix
        item.volume = res.response.data.volume
        item.fileId = res.response.data.id
        item.url = res.response.data.filePath
        item.fileFolderId = this.id
        item.projectId = this.$route.query.projectId
        return item
      })
      this.fileList.forEach(sub => {
        this.saveCount++
        if (['pdf', 'doc'].includes(sub.suffix)) {
          this.saveLibrary(sub)
        }
        if (this.saveCount === this.fileList.length) {
          this.saveCount = 0
          this.addFile()
        }
      })
    },
    saveLibrary (sub) {
      const data = { category: 4, content: '' }
      this.$api.common.submit(Object.assign(sub, data)).then(res => {
        if (res.code === 200) {
          this.saveCount++
          this.libraryList.push(res.data.id)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    addFile () {
      this.$api.project.fileAdd(this.fileList).then(res => {
        if (res.code === 200) {
          this.show = false
          this.$emit('reFiles')
          this.$message.success(res.msg)
          if (this.user.info.type !== 3) {
            this.$confirm('文件上传成功，是否给业主发送提醒消息？', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.SendMsg()
              })
          }
        } else {
          this.show = false
          this.$message.error(res.msg)
        }
      })
    },
    SendMsg () {
      this.sendParams.ids = this.fileList.map(e => e.fileId).join(',')
      this.sendParams.projectId = this.$route.query.projectId
      this.sendParams.ownerId = this.$route.query.ownerId
      console.log(this.sendParams)
      this.$api.project.send(this.sendParams).then(res => {
        if (res.code === 200) {
          this.$message.success('消息已经发送成功！')
          this.$bus.emit('reFolder')
          this.sendMsg = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    folderAdd () {
      this.folderInfo.projectId = this.projectId
      this.folderInfo.parentId = this.id
      this.$api.project.folderAdd(this.folderInfo).then(res => {
        if (res.code === 200) {
          this.addShow = false
          this.$message.success(res.msg)
          this.$emit('reFiles')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    changePage (page) {
      this.$emit('change', page)
    }
  }
}
</script>

<style scoped>

</style>
