<template>
  <view style="overflow-y: scroll">
    <baseTitle title="基础信息"></baseTitle>
    <el-form :model="basicData">
      <el-row>
        <el-col :span="8">
          <el-form-item prop="requirementName" label="征集名称">
            <span>{{ basicData.requirementName ||'--'}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="projectName" label="项目名称" label-width="75">
            <span>{{ basicData.projectName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <fvForm :schema="schema" @getInstance="(e)=>baseForm = e"></fvForm>
    <fvSearchForm :searchConfig="searchConfig" @search="search"></fvSearchForm>
    <div style="display: flex">
      <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 ImportExcel from "../../../components/ImportExcel";

const router = useRouter()
const route = useRoute()
const projectId = ref(route.query.id)
const basicData = ref({})
const tableData = ref({})
const formDataArray = ref([
  {
    label: '项目负责人',
    prop: 'projectChargePersonName',
    colProps: {
      span: 8
    },
    labelWidth:'left'
  },
  {
    label: '项目开始时间',
    prop: 'startTime',
    colProps: {
      span: 8
    },
    labelWidth:'left'
  },
  {
    label: '项目预计持续时间',
    prop: 'endTime',
    colProps: {
      span: 8
    },
    labelWidth:'left'
  },
  {
    label: '项目开展方式',
    prop: 'projectDevelopmentWay',
    colProps: {
      span: 24
    },
    labelWidth:'left'
  },
  {
    label: '项目预算',
    prop: 'projectBudgetDescription',
    colProps: {
      span: 24
    },
    labelWidth:'left'
  },
  {
    label: '项目总体完成率',
    prop: 'projectCompletionRate',
    colProps: {
      span: 8
    },
    labelWidth:'left',
    component: () => <span>{tableData.value.projectCompletionRate}%</span>
  },
  {
    label: '已完成工作量',
    prop: 'completeWork',
    colProps: {
      span: 16
    },
    labelWidth:'left'
  }
])
const buttonShow = ref(false)
const schema = computed(() => {
  return formDataArray.value
})
const baseForm = 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',
    }
  },
  {
    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
})
// 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)
    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
    })
    baseForm.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: 0!important;
}
:deep(.el-form-item__content){
  .el-input{
    width: 100%!important;
  }
}
</style>
