<template>
  <baseTitle title="基础信息"></baseTitle>
  <fvForm :schema="schema" @getInstance="(e)=>baseForm = e"></fvForm>
  <fvSearchForm :searchConfig="searchConfig" @search="search"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick" @selectionChange="selectionChange">
    <template #empty>
      <el-empty description="暂无数据"/>
    </template>
  </fvTable>
</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} from "@/api/project-manage";

const router = useRouter()
const route = useRoute()
const formArray = ref([
  {
    label: '征集名称',
    prop: 'requirementName',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目名称',
    prop: 'projectName',
    colProps: {
      span: 12
    }
  }
])
const formDataArray = ref([
  {
    label: '征集名称',
    prop: 'requirementName',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目名称',
    prop: 'projectName',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目负责人',
    prop: 'projectChargePerson',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目开始时间',
    prop: 'startTime',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目预计持续时间',
    prop: 'endTime',
    colProps: {
      span: 12
    }
  },
  {
    label: '项目开展方式',
    prop: 'projectDevelopmentWay',
    colProps: {
      span: 24
    }
  },
  {
    label: '项目预算',
    prop: 'projectBudgetDescription',
    colProps: {
      span: 24
    }
  },
  {
    label: '项目总体完成率（%）',
    prop: 'projectCompletionRate',
    colProps: {
      span: 6
    },
    component: ()=><span>{tableData.value.projectCompletionRate}%</span>
  },
  {
    label: '已完成工作量',
    prop: 'completeWork',
    colProps: {
      span: 18
    }
  }
])
const tableData = ref({})
const schema = computed(() => {
  if (JSON.stringify(tableData.value) !== '{}') {
    return formDataArray.value
  } else {
    return formArray.value
  }
})
const baseForm = ref()
const tableIns = ref()
const btns = ref([
  {name: '表格更新', key: 'update', color: '#DED0B2', auth: ''},
  {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-DD HH:mm:ss',
    },
    colProps: {}
  },
  {
    label: '项目费用',
    prop: 'projectCost',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择项目费用查询',
      clearable: true,
      filterable: true,
      cacheKey: 'project_cost',
    }
  },
  {
    label: '研发阶段',
    prop: 'researchStage',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择研发阶段查询',
      clearable: true,
      filterable: true,
      checkStrictly: true,
      cacheKey: 'fee_stage',
    }
  },
  {
    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'
    },
    {
      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
})
if (route.query.state !== '4') {
  btns.value.push({name: '上传费用', key: 'add', color: '#DED0B2', auth: ''})
}
const exportIds=ref([])
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)
  } catch {
  }
}

getBaseInfo()
const headBtnClick = (key) => {
  switch (key) {
    case 'add':
      handleUploadFee()
      break;
    case 'update':
      handleUpdateTable()
      break;
    case 'export':
      exportExcelHandler()
      break;
  }
}
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 reg = /filename=([^&]+)/;
    let contentDisposition = decodeURI(res.headers['content-disposition'])
    let result = reg.exec(contentDisposition)
    let fileName = result[1]
    fileName = fileName.replace(/\"/g, '')
    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()
}
const init = async () => {
  const {code, msg, data} = await searchUpdateLedgerData(route.query.id)
  if (data) {
    tableData.value = data
    baseForm.value.setValues(data)
  }
  // if (code !== 1000) {
  //   ElNotification({
  //     title: '提示',
  //     message: msg,
  //     type: 'error'
  //   })
  // }
}
init()
</script>

<style scoped>

</style>
