<template>
  <view style="overflow-y: scroll;">
    <baseTitle title="项目基本信息"></baseTitle>
    <fvForm :schema="schema" @getInstance="(e)=>baseForm = e" label-position="left" label-width="left" style="margin-left: 15px"></fvForm>
    <baseTitle title="研发台账明细" style="margin-top: -10px"></baseTitle>
    <fvForm :schema="tableUpdateData" @getInstance="(e)=>tableUpdateFormData = e" style="margin-left: 15px"></fvForm>
    <fvSearchForm :searchConfig="searchConfig" @search="search"></fvSearchForm>
    <div style="display: flex;margin-left: 15px" >
      <el-button color="#DED0B2" @click="exportExcelHandler">导出</el-button>
      <import-excel :projectId="projectId" v-if="buttonShow" @success="importTheExpenseLedger"/>
      <el-button color="#DED0B2" v-if="buttonShow" @click="handleImportTemplateDownload">模板下载</el-button>
      <el-button color="#DED0B2" v-if="buttonShow" @click="handleUploadFee">上传费用</el-button>
      <el-button color="#DED0B2" v-if="buttonShow" @click="handleUpdateTable">表格更新</el-button>
    </div>
    <fvTable ref="tableIns" :tableConfig="tableConfig" @selectionChange="selectionChange">
      <template #empty>
        <el-empty description="暂无数据"/>
      </template>
    </fvTable>
  </view>

</template>

<script setup lang="jsx">
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import {toThousands} from '@/utils/changePrice.js'
import {getBaseInfoApi} from "@/components/steps/api";
import {searchUpdateLedgerData, exportExcel,ledgerTemplateDownload} from "@/api/project-manage";
import {useCacheStore} from '@/stores/cache.js'

const cacheStore = useCacheStore()
const router = useRouter()
const route = useRoute()
const projectId = ref(route.query.id)
const basicData = ref({})
const tableData = ref({})
const buttonShow = ref(false)
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>
            {
              basicData.value?.projectType ?
                  <span>{filterDict(cacheStore.getDict('project_type'), basicData.value?.projectType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '研发主体',
      prop: 'rdSubject',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.rdSubject ?
                  <span>{filterDict(cacheStore.getDict('rd_subject'), basicData.value?.rdSubject)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '出资类型',
      prop: 'investmentType',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.investmentType ?
                  <span>{filterDict(cacheStore.getDict('invest_type'), basicData.value?.investmentType)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '所属业务板块',
      prop: 'businessSegment',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.businessSegment ?
                  <span>{filterDict(cacheStore.getDict('business_segment'), basicData.value?.businessSegment)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '标准制定',
      prop: 'technicalStandard',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.technicalStandard ?
                  <span>{filterDict(cacheStore.getDict('technical_standard'), basicData.value?.technicalStandard)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '项目影响',
      prop: 'projectImpact',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.projectImpact ?
                  <span>{filterDict(cacheStore.getDict('project_impact'), basicData.value?.projectImpact)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '经费预算(元)',
      prop: 'economicEstimate',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.economicEstimate ?
                  <span>{ toThousands(basicData.value?.economicEstimate )}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '产学研联合',
      prop: 'industryUniversityResearch',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.industryUniversityResearch ?
                  <span>{filterDict(cacheStore.getDict('industry_university'), basicData.value?.industryUniversityResearch)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '开展政府申报',
      prop: 'governmentDeclaration',
      colProps: {
        span: 6
      },
      component: () => (
          <div>
            {
              basicData.value?.governmentDeclaration ?
                  <span>{filterDict(cacheStore.getDict('government_declaration'), basicData.value?.governmentDeclaration)}</span>
                  : <span>{'--'}</span>
            }
          </div>
      )
    },
    {
      label: '所属专项资金项目',
      prop: 'specialFund',
      colProps: {
        span: 6
      }
    },
    {
      label: '申请总部专项资金(元)',
      prop: 'specialFundAmount',
      colProps: {
        span: 6
      }
    },
    {
      label: '部门分管领导',
      prop: 'optionalChargeLeadership',
      colProps: {
        span: 6
      }
    }
  ]
})

const tableUpdateData = computed(() => {
  return [
    {
      label: '项目负责人',
      prop: 'projectChargePersonName',
      colProps: {
        span: 6
      },
      labelWidth:'left'
    },
    // {
    //   label: '项目开始时间',
    //   prop: 'startTime',
    //   colProps: {
    //     span: 6
    //   },
    //   labelWidth:'left'
    // },
    // {
    //   label: '项目预计持续时间',
    //   prop: 'endTime',
    //   colProps: {
    //     span: 6
    //   },
    //   labelWidth:'left'
    // },
    {
      label: '项目开展方式',
      prop: 'projectDevelopmentWay',
      colProps: {
        span: 24
      },
      labelWidth:'left'
    },
    // {
    //   label: '项目预算',
    //   prop: 'projectBudgetDescription',
    //   colProps: {
    //     span: 24
    //   },
    //   labelWidth:'left'
    // },
    {
      label: '项目总体完成率',
      prop: 'projectCompletionRate',
      colProps: {
        span: 6
      },
      labelWidth:'left',
      component: () => <span>{tableData.value.projectCompletionRate}%</span>
    },
    {
      label: '已完成工作量',
      prop: 'completeWork',
      colProps: {
        span: 18
      },
      labelWidth:'left'
    }
  ]
})
const baseForm = ref()
const tableUpdateFormData = ref()
const tableIns = ref()
const btns = ref([
  {name: '导出', key: 'export', color: '#DED0B2', auth: ''}
])
const searchConfig = reactive([
  {
    label: '时间',
    prop: 'time',
    component: 'el-date-picker',
    props: {
      type: 'month',
      placeholder: '请选择月份',
      clearable: true,
      format: 'YYYY-MM',
      valueFormat: 'YYYY-MM',
    },
    colProps: {}
  },
  {
    label: '项目费用',
    prop: 'projectCost',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择项目费用查询',
      clearable: true,
      filterable: true,
      cacheKey: 'project_cost',
      remote: true
    }
  },
  {
    label: '研发阶段',
    prop: 'researchStage',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择研发阶段查询',
      clearable: true,
      filterable: true,
      checkStrictly: true,
      cacheKey: 'fee_stage',
      remote: true
    }
  },
  {
    label: '税后余额',
    prop: 'afterTax',
    component: 'el-input',
    props: {
      placeholder: '请输入税后余额查询',
      clearable: true,
      filterable: true,
      checkStrictly: true
    }
  },
  {
    label: '摘要',
    prop: 'digest',
    component: 'el-input',
    props: {
      placeholder: '请输入摘要查询',
      clearable: true,
      filterable: true,
      checkStrictly: true
    }
  },
])
const tableConfig = reactive({
  columns: [
    // {
    //   type: 'selection',
    //   prop: 'selection'
    // },
    {
      prop: 'name',
      type: 'index',
      label: '序号',
      width: '80',
      align: 'center',
      index: index => {
        return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
      }
    },
    {
      prop: 'time',
      label: '时间',
      align: 'center'
    },
    {
      prop: 'projectCost',
      label: '项目费用',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.projectCost !== null && row.projectCost !== null && row.projectCost !== undefined) {
          return (<Tag dictType={'project_cost'} value={row.projectCost}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'researchStage',
      label: '研发阶段',
      align: 'center',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.researchStage && row.researchStage !== null && row.researchStage !== undefined) {
          return (<Tag dictType={'fee_stage'} value={row.researchStage}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'digest',
      label: '摘要',
      align: 'center'
    },
    {
      prop: 'afterTax',
      label: '税后余额(元)',
      align: 'center',
      currentRender: ({row}) => {
        return <span>{toThousands(row.afterTax)}</span>
      }
    },
  ],
  api: '/workflow/mosr/expense/ledger',
  params: {
    projectId: route.query.id
  },
  // btns: btns.value
})
// const exportIds=ref([])
//匹配字典值,返回对应值的字典标签
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 selectionChange = (data) => {
  console.log('data', data)
  console.log(' data.forEach(item=>item.id)', data.forEach(item => item.id))
}
const handleUpdateTable = () => {
  router.push({
    name: 'Implementation/update',
    query: {
      id: route.query.id
    }
  })
}
const getBaseInfo = async () => {
  try {
    const {code, data} = await getBaseInfoApi(route.query.id)
    baseForm.value.setValues(data)
    basicData.value = data
  } catch {
  }
}
const init = async () => {
  buttonShow.value = false
  const {code, msg, data} = await searchUpdateLedgerData(route.query.id)
  if (code === 1000) {
    tableData.value = data
    nextTick(() => {
      buttonShow.value = !data.view
    })
    tableUpdateFormData.value.setValues(data)
  }
}
getBaseInfo()
init()
const importTheExpenseLedger = () => {
  tableIns.value.refresh()
}
//导入模板下载
const handleImportTemplateDownload=()=>{
  ledgerTemplateDownload().then(res => {
    let link = document.createElement('a')
    try {
      let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
      let _fileName = "台账模板.xlsx"//文件名，中文无法解析的时候会显示 _(下划线),生产环境获取不到
      link.style.display='none';
      // 兼容不同浏览器的URL对象
      const url = window.URL || window.webkitURL || window.moxURL;
      link.href=url.createObjectURL(blob);
      link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_')+1))
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      url.revokeObjectURL(link.href);//销毁url对象
    }catch (e) {
      console.log('下载的文件出错',e)
    }
  })
}
const handleUploadFee = () => {
  router.push({
    name: 'Implementation/uploadFee',
    query: {
      id: route.query.id
    }
  })
}

const exportExcelHandler = () => {
  // console.log('exportIds.value',exportIds.value)
  let data = {
    projectId: route.query.id
  }
  exportExcel(data).then(res => {
    console.log(res)
    let fileName = `科技创新项目研发费用台账-${basicData.value.projectName}.xlsx`
    const blob = new Blob([res.data])
    let a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = fileName
    a.click()
  })
}

const search = (val) => {
  tableConfig.params = {...val, projectId: route.query.id}
  tableIns.value.refresh()
}
onActivated(() => {
  init()
})
</script>

<style scoped lang="scss">
:deep(.el-table--fit) {
  min-height: 400px !important;
}
:deep(.el-form-item__label-wrap){
  margin-left: 15px!important;
}
:deep(.el-form-item__content){
  .el-input{
    width: 100%!important;
  }
}
.search-form {
  padding-top: 0!important;
}
:deep(.el-table__header){
  .is-leaf:first-child{
    .cell{
      margin-left: -20px!important;
    }
  }
}
:deep(.el-table__body){
  .el-table__cell:first-child{
    .cell{
      margin-left: -10px!important;
    }
  }
}

</style>
