<template>
  <div style="padding: 0 30px">
    <baseTitle title="项目基本信息"></baseTitle>
    <fvForm :schema="schema" @getInstance="(e)=>baseForm = e" label-position="left" label-width="left"
            style="margin-left: 15px"></fvForm>
    <el-form :model="attachment" inline style="margin-left: 15px">
      <el-form-item label="标签" prop="tag">
        <el-select v-model="attachment.tag" placeholder="请选择标签" clearable filterable style="width: 300px">
          <el-option
              v-for="item in tagsOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch" color="#DED0B2">搜索</el-button>
        <el-button v-if="uploadState" color="#DED0B2" @click="handleUpload">上传附件</el-button>
      </el-form-item>
    </el-form>
    <fvTable style="width: 100%;max-height: 274px" v-if="showTable" height="274" :tableConfig="implementationAttachmentTableConfig"
             :data="otherFileList" :isSettingCol="false" :pagination="false">
      <template #empty>
        <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
      </template>
    </fvTable>
    <file-preview ref="filePreviewRef" v-if="filePreviewShow" :fileName="filePreviewParam.fileName" :fileUrl="filePreviewParam.fileUrl"
                  :fileType="filePreviewParam.fileType"/>
  </div>
</template>

<script setup lang="jsx">
import {downloadFile} from "@/api/project-demand";
import {getTags} from "@/api/project-manage";
import {ElNotification} from "element-plus";
import {getBaseInfoApi} from "@/components/steps/api";
import {searchImplementationFileList} from "@/api/project-manage/attachment";
import {useCacheStore} from '@/stores/cache.js'

import {toThousands} from '@/utils/changePrice.js'
import {computed, ref} from "vue";

const cacheStore = useCacheStore()
const route = useRoute()
const router = useRouter()
const uploadState = ref(false)
const attachment = reactive({
  tag: ''
})
const baseFormData = ref([])
const schema = computed(() => {
  return [
    {
      label: '承办单位',
      prop: 'affiliatedCompany',
      colProps: {
        span: 6
      }
    },
    {
      label: '项目名称',
      prop: 'projectName',
      colProps: {
        span: 6
      }
    },

    {
      label: '开始时间',
      prop: 'startTime',
      colProps: {
        span: 6
      }
    },
    {
      label: '结束时间',
      prop: 'endTime',
      colProps: {
        span: 6
      }
    },
    {
      label: '项目类型',
      prop: 'projectType',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectType ?
                  <span>{filterDict(cacheStore.getDict('project_type'), baseFormData.value?.projectType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '研发主体',
      prop: 'rdSubject',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.rdSubject ?
                  <span>{filterDict(cacheStore.getDict('rd_subject'), baseFormData.value?.rdSubject)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '出资类型',
      prop: 'investmentType',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.investmentType ?
                  <span>{filterDict(cacheStore.getDict('invest_type'), baseFormData.value?.investmentType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '所属业务板块',
      prop: 'businessSegment',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.businessSegment ?
                  <span>{filterDict(cacheStore.getDict('business_segment'), baseFormData.value?.businessSegment)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '标准制定',
      prop: 'technicalStandard',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.technicalStandard ?
                  <span>{filterDict(cacheStore.getDict('technical_standard'), baseFormData.value?.technicalStandard)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '项目影响',
      prop: 'projectImpact',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.projectImpact ?
                  <span>{filterDict(cacheStore.getDict('project_impact'), baseFormData.value?.projectImpact)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '预估经费预算',
      prop: 'economicEstimate',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.economicEstimate ?
                  <span>{toThousands(baseFormData.value?.economicEstimate)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '产学研联合',
      prop: 'industryUniversityResearch',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.industryUniversityResearch ?
                  <span>{filterDict(cacheStore.getDict('industry_university'), baseFormData.value?.industryUniversityResearch)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '开展政府申报',
      prop: 'governmentDeclaration',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.governmentDeclaration ?
                  <span>{filterDict(cacheStore.getDict('government_declaration'), baseFormData.value?.governmentDeclaration)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '所属专项资金项目',
      prop: 'specialFund',
      colProps: {
        span: 6
      }
    },
    {
      label: '预估专项资金(元)',
      prop: 'specialFundAmount',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.specialFundAmount ?
                  <span>{toThousands(baseFormData.value?.specialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '是否在预算内',
      prop: 'isWithinBudget',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.isWithinBudget!=null ? baseFormData.value?.isWithinBudget?
                  <span>{'预算内'}</span>
                  : <span>{'预算外'}</span>:'--'
            }
          </div>
      )
    },
    {
      label: '部门分管领导',
      prop: 'optionalChargeLeadership',
      colProps: {
        span: 6
      }
    }
  ]
})

const baseForm = ref()
const tagsOption = ref([])
const implementationAttachmentTableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width: '80',
    },
    {
      prop: 'originalFileName',
      label: '文件名',
      align: 'center',
      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>
            </div>
        )
      }
    }
  ]
})
const showTable = ref(true)
const otherFileList = ref([])
const filePreviewParam = ref({
  fileUrl: '',
  fileName: '',
  fileType: 'pdf'
})
const filePreviewShow = ref(false)
const clickToPreview=(row)=>{
  filePreviewShow.value = false
  filePreviewParam.value = {
    fileUrl: row.url,
    fileName: row.originalFileName,
    fileType: row.fileType
  }
  nextTick(()=>{
    filePreviewShow.value = true
  })
}
//匹配字典值,返回对应值的字典标签
const filterDict = (data, value) => {
  if (data === undefined || value === undefined) return;
  let label = ''
  let result = []
  if (value instanceof Array) {
    value.forEach(item1 => {
      data.find(item => {
        if (item.value == item1) {
          result.push(item.label)
        }
      })
    })
    label = result.map(item => item).join('，')
  } else {
    if (data instanceof Array) {
      data.find(item => {
        if (item.value == value) {
          label = item.label
        }
      })
    }
  }
  return label
}

const getBaseInfo = async () => {
  try {
    const {code, data} = await getBaseInfoApi(route.query.id)
    baseForm.value.setValues(data)
    baseFormData.value = data
  } catch {
  }
}

getBaseInfo()

const getTagsOption = () => {
  if (!route.query.id) return
  getTags(route.query.id).then(res => {
    if (res.code === 1000) {
      tagsOption.value = res.data
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
const handleSearch = () => {
  let params = {
    targetId: route.query.id,
    targetState: "40"
  }
  if (attachment.tag) {
    tagsOption.value.forEach(item => {
      if (item.value === attachment.tag) {
        attachment.tag = item.label
      }
    })
    params.tag = attachment.tag
  }
  searchImplementationFileList(params).then(res => {
    showTable.value = false
    if (res.code === 1000) {
      otherFileList.value = res.data.fileList
      uploadState.value = res.data.upload
      nextTick(() => {
        showTable.value = true
      })
    } else {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}
const handleUpload = () => {
  router.push({
    name: 'Implementation/upload',
    query: {
      projectId: route.query.id,
      type: 'list'
    }
  })
}
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()
  })
}

onActivated(() => {
  handleSearch()
  getTagsOption()
})
handleSearch()
getTagsOption()
</script>

<style scoped lang="scss">

:deep(.el-table__header) {
  .is-leaf:first-child {
    .cell {
      margin-left: -25px !important;
    }
  }
}

:deep(.el-table__body) {
  .el-table__cell:first-child {
    .cell {
      margin-left: -13px !important;
    }
  }
}
</style>
