<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;margin-bottom: -18px"></fvForm>
    <baseTitle title="项目实施-上传附件" ></baseTitle>
    <el-form :model="formData" ref="tagForm" label-width="auto">
      <el-form-item label="标签名称" prop="tagName" style="margin-left: 15px;">
        <el-input v-model="formData.tagName" placeholder="请输入标签名称" style="width: 300px;margin-right: 10px" v-if="showInput" clearable/>
        <el-select v-model="formData.tagName" placeholder="请选择标签名称" clearable filterable style="width: 300px;margin-right: 10px" 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>-->
    <file-upload @getFile="getFile" :disabled="!formData.tagName" :title="!formData.tagName?'请先选择/输入标签！':''" style="margin-left: 15px"/>
    <fvTable style="width: 100%;max-height: 318px;" v-if="showTable" height="318" :tableConfig="tableConfig"
             :data="fileList" :isSettingCol="false" :pagination="false">
      <template #empty>
        <el-empty :image-size="90" description="暂无数据" style="padding: 0"/>
      </template>
    </fvTable>
    <div class="oper-page-btn">
      <el-button color="#DED0B2" @click="handleSubmit(tagForm)">提交</el-button>
    </div>
    <file-preview ref="filePreviewRef" v-if="filePreviewShow" :fileName="filePreviewParam.fileName" :fileUrl="filePreviewParam.fileUrl"
                  :fileType="filePreviewParam.fileType"/>
  </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 {deleteFile, downloadFile} from "@/api/project-demand";

import {useCacheStore} from '@/stores/cache.js'

import {toThousands} from '@/utils/changePrice.js'

const cacheStore = useCacheStore()
const tagsViewStore = useTagsView()
const route = useRoute()
const router = useRouter()
const fileList = ref([])
const showInput = ref(false)
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 formData = ref({
  tagName: ''
})
const tableConfig = 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>
              <popover-delete name={row.originalFileName} type={'文件'} btnType={'danger'}
                              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 filePreviewParam = ref({
  fileUrl: '',
  fileName: '',
  fileType: 'pdf'
})
const filePreviewShow = ref(false)
if(localStorage.getItem('implementFile')){
  fileList.value=JSON.parse(localStorage.getItem('implementFile'))
}
const changeImplementFile=()=>{
  localStorage.setItem('implementFile', JSON.stringify(fileList.value))
}

const clickToPreview=(row)=>{
  filePreviewShow.value = false
  filePreviewParam.value = {
    fileUrl: row.url,
    fileName: row.originalFileName,
    fileType: row.fileType
  }
  nextTick(()=>{
    filePreviewShow.value = true
  })
}
onActivated(() => {
  console.log('onActivated')
  formData.value.tagName = '';
  showTable.value = false
  nextTick(() => {
    showTable.value = true
  })
  fileList.value = []
})
//匹配字典值,返回对应值的字典标签
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 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);
      changeImplementFile()
    }
  });
}

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.projectId)
    baseForm.value.setValues(data)
    baseFormData.value = data
  } catch {
  }
}

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

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
  })
  changeImplementFile()
}
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.projectId,
      targetState: "30"
    }
    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 === '30') {
        console.log('归档实施')
        await router.push({
          name: 'Filing/attachment',
          query: {
            id: route.query.projectId,
            name:route.query.type,
            requirementId: route.query.requirementId
          }
        })
      } else {
        if (route.query.type === 'list') {
          router.push({
            name: 'Implementation/attachment',
            query: {
              id: route.query.projectId
            }
          })
        } else {
          await router.push({
            name: 'Implementation/detail',
            query: {
              id: route.query.id,
              projectId: route.query.projectId,
              state: route.query.state,
              step: '30'
            }
          })
        }
      }
      localStorage.removeItem('implementFile')
    }
  })
}
getTagsOption()
</script>

<style scoped lang="scss">
:deep(.el-table--fit ) {
  height: 318px !important;
}

: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>
