<template>
  <baseTitle title="基础信息"></baseTitle>
  <fvForm :schema="schema" @getInstance="(e)=>baseForm = e"></fvForm>
  <baseTitle title="项目实施-上传附件"></baseTitle>
  <el-form :model="formData" ref="tagForm" label-width="auto" :rules="rules">
    <el-form-item label="标签名称" prop="tagName">
      <el-input v-model="formData.tagName" placeholder="请输入标签名称" style="width: 300px" v-if="showInput"/>
      <el-select v-model="formData.tagName" placeholder="请选择标签名称" clearable filterable style="width: 300px" v-else>
        <el-option
            v-for="item in tagsOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-button type="primary" link @click="changeInput">{{ showInput ? '选择' : '输入' }}</el-button>
    </el-form-item>
  </el-form>
  <baseTitle title="其他文件"></baseTitle>
  <el-card style="width: 100%;margin: 15px 0">
    <file-upload @getFile="getFile" :disabled="!formData.tagName" :title="!formData.tagName?'请先选择/输入标签！':''"/>
    <fvTable style="width: 100%;max-height: 300px;" v-if="showTable" :tableConfig="tableConfig"
             :data="fileList" :isSettingCol="false" :pagination="false">
      <template #empty>
        <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
      </template>
    </fvTable>
  </el-card>
  <div class="oper-page-btn">
    <el-button color="#DED0B2" @click="handleSubmit(tagForm)">提交</el-button>
  </div>
</template>

<script setup lang="jsx">
import {getTags} from "@/api/project-manage";
import {ElNotification} from "element-plus";
import {useTagsView} from '@/stores/tagsview.js'
import {uploadFileList} from "@/api/project-manage/attachment";
import {computed, ref} from "vue";
import {getBaseInfoApi} from "@/components/steps/api";
import {downloadFile,deleteFile} from "@/api/project-demand";

const tagsViewStore = useTagsView()
const route = useRoute()
const router = useRouter()
const fileList = ref([])
const showInput = ref(false)
const schema = computed(() => {
  return [
    {
      label: '项目名称',
      prop: 'projectName',
      colProps: {
        span: 8
      }
    },
    {
      label: '征集公司',
      prop: 'affiliatedCompany',
      colProps: {
        span: 8
      }
    },
    {
      label: '征集名称',
      prop: 'requirementName',
      colProps: {
        span: 8
      }
    },
    {
      label: '征集描述',
      prop: 'collectExplain',
      colProps: {
        span: 24
      }
    },
  ]
})
const baseForm = ref()
const tagsOption = ref([])
const formData = ref({
  tagName: ''
})
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: '80',
    },
    {
      prop: 'originalFileName',
      label: '附件名称',
      align: 'center',
    },
    {
      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>
              <popover-delete name={row.originalFileName} type={'文件'} btnType={'danger'}
                              perm={['mosr:requirement:del']}
                              onDelete={() => handleDelete(row)}/>
            </div>
        )
      }
    }
  ]
})
const showTable = ref(true)
const tagForm = ref()
const name = ref(router.currentRoute.value.name)
const rules = reactive({
  tagName: [{required: true, message: '请输入标签名称', trigger: ['blur', 'change']}],
})
const handleDelete = (row) => {
  deleteFile(row.fileId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      fileList.value.splice(fileList.value.findIndex((item) => item.fileId === row.fileId), 1);
    }
  });
}

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 getBaseInfo = async () => {
  try {
    const {code, data} = await getBaseInfoApi(route.query.id)
    baseForm.value.setValues(data)
  } catch {
  }
}

getBaseInfo()
const changeInput = () => {
  showInput.value = !showInput.value;
  formData.value.tagName = '';
}
const getTagsOption = () => {
  if (!route.query.id) return
  getTags(route.query.id).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      showInput.value = res.data.length === 0;
      tagsOption.value = res.data
    }
  })
}

const compositeParam = (item) => {
  tagsOption.value.forEach(item => {
    if (item.value == formData.value.tagName) {
      formData.value.tagName = item.label
    }
  })
  return {
    fileId: item.id,
    size: item.size,
    originalFileName: item.originalFilename,
    fileType: item.fileType,
    url: item.url,
    newFile: true,
    tag: formData.value.tagName,
  }
}
const getFile = (val) => {
  console.log('上传文件', val)
  showTable.value = false
  let fileObj = compositeParam(val)
  fileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })
}
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) {
      ElNotification({
        title: '提示',
        message: '请完善数据,再提交!',
        type: 'error'
      })
      return;
    }
    let params = {
      fileList: fileList.value,
      projectId: route.query.id,
      targetState: "40"
    }
    let res = await uploadFileList(params)
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    if (res.code === 1000) {
      tagsViewStore.delVisitedViews(router.currentRoute.value.path)
      if (route.query.type === '40') {
        await router.push({
          name: 'Filing/attachment',
          query: {
            id: route.query.id
          }
        })
      } else {
        await router.push({
          name: 'Implementation/attachment',
          query: {
            id: route.query.id
          }
        })
      }
    }
  })
}
getTagsOption()
</script>

<style scoped>
:deep(.el-table--fit ) {
  height: 300px !important;
}
</style>
