<template>
  <el-row>
    <el-col :span="24">
      <baseTitle :title="'项目附件'"></baseTitle>
    </el-col>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick" @tab-remove="tabRemove"
             style="margin-left: 15px;margin-top: -10px">
      <el-tab-pane name="all" :closable="false" label="全部">
      </el-tab-pane>
      <el-tab-pane v-for="item in tagsOption" :closable="item.isClose==1"
                   :key="item.tagId"
                   :label="item.fileTag"
                   :name="item.tagId">
        <div class="tag-title">
          <div></div>
          {{ item.fileTag }}
        </div>
      </el-tab-pane>

      <el-tab-pane name="plus" v-if="uploadState" :closable="false">
        <template #label>
          <div style="margin-top: 4px;">
            <el-icon color="#BEA266">
              <Plus/>
            </el-icon>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
  </el-row>
  <div style="margin-top:10px;margin-bottom: 8px;margin-left: 15px;display: flex">
    <!--      <el-button   color="#DED0B2" @click="handleUpload">上传附件</el-button>-->
    <file-upload v-if="!isLineBtn&&uploadState" @getFile="getFile"/>

    <el-button color="#DED0B2" @click="handleEditTag" v-if="activeName!='all'&&activeName!='plus'&&uploadState"
               style="margin-left: 10px;">编辑
    </el-button>
  </div>
  <fvTable style="width: 100%;min-height:311px;max-height: 311px" v-if="showAttachmentTable" height="311"
           :tableConfig="executeTableConfig" class="execute-apply-table"
           :data="otherAttachmentList" :isSettingCol="false" :pagination="false">
    <template #empty>
      <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
    </template>
  </fvTable>
  <file-preview ref="filePreviewRef" :fullscreen="false" v-if="filePreviewShow" :fileName="filePreviewParam.fileName"
                :fileUrl="filePreviewParam.fileUrl"
                :fileType="filePreviewParam.fileType"/>
  <el-dialog v-model="tagNameShow" center width="450" top="450px">
    <div style="display: flex;align-items: center">标签：
      <el-input v-model="fileParam.tagName" placeholder="请输入标签名称" style="width: 335px;" clearable/>
    </div>

    <div class="oper" style="display: flex;justify-content: flex-end;margin-top: 10px">
      <el-button color="#DED0B2" @click="changeTag()">确定</el-button>
      <el-button @click="tagNameShow=false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="jsx">
import {addTag, delTag, getTagList, getTags, updateTag} from "@/api/project-manage";
import {ElLoading, ElMessageBox, ElNotification} from "element-plus";
import {searchImplementationFileList, uploadFileList} from "@/api/project-manage/attachment";
import {deleteFile, downloadFile} from "@/api/project-demand";

const router = useRouter()
const route = useRoute()
const attachmentParam = reactive({
  tag: ''
})
const fileParam = ref({
  tagName: ''
})
const uploadState = ref(false)
const tagNameShow = ref(false)
const tagsOption = ref([])
const fileList = ref([])
const allFiles = ref([])
const showAttachmentTable = ref(true)
const activeName = ref('all')

const props = defineProps({
  fileNameTableWidth: {
    type: String,
    default: '400'
  },
  isLineBtn: {
    type: Boolean,
    default: false
  },
})
const executeTableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: 85,
    },
    {
      prop: 'originalFileName',
      label: '文件名',
      align: 'center',
      width: props.fileNameTableWidth,
      currentRender: ({row, index}) => (
          <div style="color: #2a99ff;cursor: pointer;" onClick={() => clickToPreview(row)}>{row.originalFileName}</div>)
    },
    {
      prop: 'tag',
      label: '标签',
      align: 'center',
    },
    {
      prop: 'size',
      label: '文件大小',
      align: 'center',
      currentRender: ({row, index}) => (parseInt(row.size / 1024) + 'KB')
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        return (
            <div>
              <el-button type="primary" link onClick={() => handleDownload(row)}>下载</el-button>
              {
                uploadState.value ?
                    <popover-delete name={row.originalFileName} type={'文件'} btnType={'danger'}
                                    onDelete={() => deleteSingleFile(row)}/> : ''
              }
            </div>
        )
      }
    }
  ]
})
// row.newFile ?: ''
const otherAttachmentList = ref([])

const filePreviewParam = ref({
  fileUrl: '',
  fileName: '',
  fileType: 'pdf'
})
const filePreviewShow = ref(false)
const isEdit = ref(false)
const isCloseByList = (index) => {
  // otherAttachmentList.length>0?false:true
  return otherAttachmentList.value.length == 0;
}
const handleDownload = (row) => {
  downloadFile(row.fileId).then(res => {
    const blob = new Blob([res])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = row.originalFileName
    a.click()
  })
}
const deleteSingleFile = (row) => {
  deleteFile(row.fileId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      otherAttachmentList.value.splice(otherAttachmentList.value.findIndex((item) => item.fileId === row.fileId), 1);
      getAttachmentList()
      activeName.value = 'all'
    }
  });
}

const changeTag = async () => {
  let res = null
  if (isEdit.value) {
    res = await updateTag({
      tagId: activeName.value,
      fileTag: fileParam.value.tagName,
      projectId: route.query.projectId,
    })
  } else {
    res = await addTag({
      projectId: route.query.projectId,
      fileTag: fileParam.value.tagName
    })
    getAttachmentList()
    fileParam.value.tagName = ''
    activeName.value = 'all'
  }
  ElNotification({
    title: '提示',
    message: res.msg,
    type: res.code === 1000 ? 'success' : 'error'
  })
  getTagsOption()
  // tagsOption.value.push({
  //   value: fileParam.value.tagName,
  //   label: fileParam.value.tagName
  // })
  tagNameShow.value = false;
}
const tabRemove = async (val) => {
  ElMessageBox.confirm(`确认删除名称为${getTagName(val)}的标签吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await delTag(val)
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      getTagsOption()
      otherAttachmentList.value = allFiles.value
    }
  })
}
const handleEditTag = () => {
  tagNameShow.value = true
  fileParam.value.tagName = getTagName(activeName.value)
  isEdit.value = true
}
const getTagName = (name) => {
  const tagArray = tagsOption.value.filter((item1) => item1.tagId == name)
  let tagName = ''
  if (tagArray && tagArray.length > 0) {
    tagName = tagArray[0].fileTag
  }
  return tagName
}
const handleTabClick = (item) => {
  tagNameShow.value = item.props.name == 'plus';
  if (item.props.name == 'plus') {
    isEdit.value = false
  }
  if (item.props.name != 'plus') {
    if (item.props.name == 'all') {
      changeFileList('all')
    } else {
      changeFileList(getTagName(item.props.name))
    }
    // if (item.props.name == 'all') {
    //   otherAttachmentList.value = allFiles.value
    // } else {
    //   otherAttachmentList.value = allFiles.value.filter(item1 => item1.tag == getTagName(item.props.name))
    // }
  }
  // showAttachmentTable.value = false
  // nextTick(() => {
  //   showAttachmentTable.value = true
  // })
}
const compositeParam = (item) => {
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: getTagName(activeName.value) || '项目实施',
  }
}
const getFile = (val) => {
  console.log('上传文件', val)
  let fileObj = compositeParam(val)
  fileList.value.push(fileObj)
  handleSubmit([fileObj])
}

const handleSubmit = async (list) => {
  let params = {
    fileList: list,
    projectId: route.query.projectId,
    targetState: "30"
  }
  let res = await uploadFileList(params)
  if (res.code !== 1000) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    })
    fileList.value=[]
  }else{
    list.forEach(item => {
      otherAttachmentList.value.push(item)
    })
  }
  getTagsOption()
}
const clickToPreview = (row) => {
  filePreviewShow.value = false
  filePreviewParam.value = {
    fileUrl: row.url,
    fileName: row.originalFileName,
    fileType: row.fileType
  }
  nextTick(() => {
    filePreviewShow.value = true
  })
}
const changeFileList = (tag) => {
  let params = {}
  if (tag == 'all') {
    params = {
      targetId: route.query.projectId,
      targetState: "30",
    }
  } else {
    params = {
      targetId: route.query.projectId,
      targetState: "30",
      tag: tag
    }
  }
  showAttachmentTable.value = false

  searchImplementationFileList(params).then(res => {
    if (res.code === 1000) {
      otherAttachmentList.value = res.data.fileList
      nextTick(() => {
        showAttachmentTable.value = true
      })
    }
  })
}
const getAttachmentList = () => {
  const loading = ElLoading.service({fullscreen: true})
  let params = {
    targetId: route.query.projectId,
    targetState: "30"
  }
  showAttachmentTable.value = false
  if (attachmentParam.tag) {
    tagsOption.value.forEach(item => {
      if (item.value === attachmentParam.tag) {
        attachmentParam.tag = item.label
      }
    })
    params.tag = attachmentParam.tag
  }
  searchImplementationFileList(params).then(res => {
    if (res.code === 1000) {
      // otherAttachmentList.value = res.data.fileList
      otherAttachmentList.value = res.data.fileList
      allFiles.value = res.data.fileList
      uploadState.value = res.data.upload

      getTagsOption()
      nextTick(() => {
        showAttachmentTable.value = true
      })
      loading.close()
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
      loading.close()
    }
  })
}
const getTagsOption = () => {
  if (!route.query.projectId) return
  getTagList(route.query.projectId).then(res => {
    if (res.code === 1000) {
      tagsOption.value = res.data.rows
      tagsOption.value.forEach((tag, index) => {
        const filterArray = otherAttachmentList.value.filter(item => tag.fileTag == item.tag)
        tagsOption.value[index].isClose = filterArray.length > 0 ? 0 : 1
      })
      // if (!res.data.rows || res.data.rows.length == 0) return;
      // activeName.value=res.data.rows[0].tagId
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
const handleUpload = () => {
  router.push({
    name: 'Implementation/upload',
    query: {
      id: route.query.id,
      projectId: route.query.projectId,
      state: route.query.state,
      step: '30'
    }
  })
}
getAttachmentList()
onActivated(() => {
  getAttachmentList()
})
</script>
<style lang="scss">
.execute-apply-table {
  //.el-table__header {
  //  .el-table__cell:last-child {
  //    .cell {
  //      margin-left: -108px !important;
  //    }
  //  }
  //}

  //.el-table__body {
  //  .el-table__cell:last-child {
  //    .cell {
  //      margin-left: -108px !important;
  //    }
  //  }
  //}
  .is-leaf:first-child {
    .cell {
      margin-left: -25px !important;
    }
  }

  .el-table__body {
    .el-table__cell:first-child {
      .cell {
        margin-left: -13px !important;
      }
    }
  }
}
</style>
<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 0 !important;
}

.tag-title {
  display: flex;
  align-items: center;
  margin-top: 15px;

  > div {
    margin-right: 5px;
    width: 4px;
    height: 20px;
    background-color: #BEA266;
  }
}

:deep(.el-table--fit ) {
  height: 311px !important;
}

:deep(.el-tabs__nav) {
  //width: 75vw;
}

:deep(.el-tabs__item) {
  flex: none !important;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__item.is-active) {
  color: #BEA266;
}

:deep(.el-tabs__active-bar) {
  background-color: #BEA266;
}

.file-tag {
  width: 100%;
  display: flex;
  border-bottom: 2px solid #f6f6f6;
  /*align-items: center;*/
}
</style>
