<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-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"  :closable="false">
        <template #label>
          <div style="margin-top: 4px;">
            <el-icon color="#BEA266">
              <Plus/>
            </el-icon>
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>
    <div style="margin-top:10px;margin-bottom: 8px;margin-left: 15px;display: flex">
      <file-upload v-if="activeName!='plus'&&activeName!='all'" @getFile="getFile"/>

      <el-button color="#DED0B2" @click="handleEditTag" v-if="activeName!='all'&&activeName!='plus'&&!isDefault"
                 style="margin-left: 10px;">编辑
      </el-button>
    </div>
    <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"/>
    <el-dialog v-model="tagNameShow" center width="450" top="40vh">
      <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>
  </div>
</template>

<script setup lang="jsx">
import {addTag, delTag, getTagList, getTags, updateTag} from "@/api/project-manage";
import {ElMessageBox, ElNotification} from "element-plus";
import {useTagsView} from '@/stores/tagsview.js'
import {searchImplementationFileList, uploadFileList} from "@/api/project-manage/attachment";
import {computed, nextTick, 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 allFileList = ref([])
const activeName = ref('all')
const tagNameShow = ref(false)
const showInput = ref(false)
const isDefault = 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: 'actualEconomicEstimate',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.actualEconomicEstimate ?
                  <span>{toThousands(baseFormData.value?.actualEconomicEstimate)}</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: 'forecastSpecialFundAmount',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              baseFormData.value?.forecastSpecialFundAmount ?
                  <span>{toThousands(baseFormData.value?.forecastSpecialFundAmount)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      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
      }
    },
    {
      label: '主项目',
      prop: 'masterProjectName',
      colProps: {
        span: 6
      }
    }
  ]
})
const baseForm = ref()
const tagsOption = ref([])
const fileParam = 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>
              {
                row.oldType ? null : <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)
const isEdit = ref(false)
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
    })
    fileParam.value.tagName = ''
    activeName.value = 'all'
  }
  getTagsOption()
  ElNotification({
    title: '提示',
    message: res.msg,
    type: res.code === 1000 ? 'success' : 'error'
  })
  tagNameShow.value = false;
}
const getOldFileList = (tag,flag) => {
  let params = {}
  if (tag == 'all') {
    params = {
      targetId: route.query.projectId,
      targetState: "30",
    }
  } else {
    params = {
      targetId: route.query.projectId,
      targetState: "30",
      tag: getTagName(activeName.value)
    }
  }
  showTable.value = false

  searchImplementationFileList(params).then(res => {
    if (res.code === 1000) {
      if(tag == 'all'){
        res.data.fileList?.forEach(item=>{
          item.oldType=true
          fileList.value.push(item)
        })
      }else{
        res.data.fileList?.forEach(item=>{
          item.oldType=true
          if(getTagName(activeName.value)==item.tag){
            fileList.value.push(item)
          }
        })
        console.log("🚀 ~ file:'fileList.value ",fileList.value)
      }
      if(flag){
        getTagsOption(flag)
      }
      nextTick(() => {
        showTable.value = true
      })
      changeImplementFile()
    }
  })
}
const handleEditTag = () => {
  fileParam.value.tagName = getTagName(activeName.value)
  if(fileList.value&&fileList.value.length>0){
    ElNotification({
      title: '提示',
      message: '该标签下存在文件，不能编辑标签。如需编辑标签，请先删除该标签下的所有文件。',
      type: 'error'
    })
    return;
  }
  tagNameShow.value = true
  isEdit.value = true
}
const tabRemove = async (val) => {
  if(fileList.value&&fileList.value.length>0){
    ElNotification({
      title: '提示',
      message: '该标签下存在文件，不能删除标签。如需删除标签，请先删除该标签下的所有文件。',
      type: 'error'
    })
    return;
  }
  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()
    }
  })
}

const handleTabClick = (item) => {
  activeName.value = item.props.name
  const defaultArray=tagsOption.value.filter(item1=>item1.tagId==item.props.name)
  if(defaultArray&&defaultArray.length>0){
    isDefault.value=defaultArray[0].isDefault==1
  }else{
    isDefault.value=false
  }
  tagNameShow.value = item.props.name == 'plus';
  if (item.props.name == 'plus') {
    isEdit.value = false
    fileParam.value.tagName = ''
  }
  const fileArray=JSON.parse(localStorage.getItem('implementFile'))
  if (item.props.name != 'plus') {
    if (item.props.name == 'all') {
      fileList.value=fileArray
      getOldFileList('all')
    } else {
      fileList.value=fileArray.filter(item1 => item1.tag == getTagName(item.props.name))
      getOldFileList()
      showTable.value = false
      nextTick(() => {
        showTable.value = true
      })
    }
  }
}

if(localStorage.getItem('implementFile')){
  fileList.value=JSON.parse(localStorage.getItem('implementFile'))
  allFileList.value=JSON.parse(localStorage.getItem('implementFile'))
}
const changeImplementFile=()=>{
  localStorage.setItem('implementFile', JSON.stringify(allFileList.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')
  fileParam.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;
  fileParam.value.tagName = '';
}
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 getTagsOption = () => {
  if (!route.query.projectId) return
  getTagList(route.query.projectId).then(res => {
    if (res.code === 1000) {
      tagsOption.value = res.data.rows
      console.log("🚀 ~ file: res.data.rows ",  res.data.rows)

      tagsOption.value?.forEach((tag, index) => {
        tagsOption.value[index].isClose =1
      })
      let defaultArray=[
        {
          tagId: 'd1',
          fileTag: '合同(专项任务书)',
          isDefault: 1,
          isClose: 2
        },
        {
          tagId: 'd2',
          fileTag: '周报',
          isDefault: 1,
          isClose: 2
        },
        {
          tagId: 'd3',
          fileTag: '阶段性验收',
          isDefault: 1,
          isClose: 2
        },
        {
          tagId: 'd4',
          fileTag: '科研成果',
          isDefault: 1,
          isClose: 2
        }
      ]
      tagsOption.value=[...defaultArray,...tagsOption.value]
      console.log("🚀 ~ file:tagsOption.value ", tagsOption.value)
    }else{
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      })
    }
  })
}

const compositeParam = (item) => {
  tagsOption.value?.forEach(item => {
    if (item.value == fileParam.value.tagName) {
      fileParam.value.tagName = item.label
    }
  })
  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)
  showTable.value = false
  let fileObj = compositeParam(val)
  fileList.value.push(fileObj)
  allFileList.value.push(fileObj)
  nextTick(() => {
    showTable.value = true
  })

  changeImplementFile()
}
const handleSubmit = async (instance) => {
    const files=JSON.parse(localStorage.getItem('implementFile'))
    let params = {
      fileList: files,
      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()
getOldFileList('all')
</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;
    }
  }
}
:deep(.el-tabs__item.is-active) {
  color: #BEA266;
}

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

</style>
