<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" style="margin-left: 15px"></fvSearchForm>
  <div style="float: left">
    <import-cost-excel @success="importTheExpenseLedger"/>
  </div>
  <fvTable ref="tableIns" class="tablte" :tableConfig="tableConfig" @headBtnClick="headBtnClick"
           :changeExportPosition="true">
    <template #empty>
      <el-empty description="暂无数据"/>
    </template>
  </fvTable>
</template>

<script setup lang="jsx">
import {reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {costTemplateDownload, exportExcel, ledgerTemplateDownload} from "../../../api/project-manage";
import ImportCostExcel from "@/components/ImportCostExcel.vue";
import fvSelect from "@/fvcomponents/fvSelect/index.vue";
import {
  getExpenseMasterProjectNameOption, getExpenseSubprojectNameOption,
  getMasterProjectNameOption,
  getSubprojectNameOption
} from "@/api/project-demand/summary/index.js";

const router = useRouter()
const route = useRoute()
const searchConfig = ref([
  {
    label: '年份',
    prop: 'rdYear',
    component: 'el-date-picker',
    props: {
      placeholder: '请选择年份',
      clearable: true,
      type: 'year',
      format: 'YYYY',
      valueFormat: 'YYYY',
    },
    colProps: {}
  },
  {
    label: '月份',
    prop: 'rdMonth',
    component: 'el-date-picker',
    props: {
      placeholder: '请选择月份',
      clearable: true,
      type: 'month',
      format: 'M',
      valueFormat: 'M',
    },
    colProps: {}
  },
  {
    label: '主项目',
    prop: 'masterProjectName',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请输入主项目',
      clearable: true,
      filterable: true,
      options: [],
      remote: true,
      remoteMethod: async (val) => {
        console.log('val', val)
        searchConfig.value.find(item => item.prop == 'masterProjectName').props.options = JSON.parse(localStorage.getItem("masterProjectNameOption"))

        if (val) {
          await getMasterProjectName(val)

        }
      }
    },
  },
  {
    label: '子项目',
    prop: 'subProjectName',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请输入子项目',
      clearable: true,
      filterable: true,
      options: [],
      remote: true,
      remoteMethod: async (val) => {
        searchConfig.value.find(item => item.prop == 'subProjectName').props.options = JSON.parse(localStorage.getItem("subprojectNameOption"))

        if (val) {
          await getSubprojectName(val)
        }
      }
    },
  },
  {
    label: '会计凭证记载金额(元)',
    prop: 'recordedAmount',
    component: 'el-input',
    props: {
      placeholder: '请输入会计凭证记载金额查询',
      clearable: true,
      filterable: true,
      checkStrictly: true
    }
  },
  {
    label: '归集研发费用金额(元)',
    prop: 'rdAmount',
    component: 'el-input',
    props: {
      placeholder: '请输入归集研发费用金额查询',
      clearable: true,
      filterable: true,
      checkStrictly: true
    }
  },
  // {
  //   label: '项目类型',
  //   prop: 'projectType',
  //   component: shallowRef(fvSelect),
  //   props: {
  //     placeholder: '请选择项目类型',
  //     cacheKey: 'project_type',
  //     clearable: true,
  //     filterable: true,
  //     remote: true
  //   },
  //   colProps: {}
  // },

])
const tableIns = ref()
const tableConfig = reactive({
  columns: [
    // {
    //   prop: 'name',
    //   type: 'index',
    //   label: '序号',
    //   align: 'center',
    //   width:85,
    //   index: index => {
    //     return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
    //   }
    // },
    {
      prop: 'rdYear',
      label: '年',
      align: 'center',
      width: 80
    },
    {
      prop: 'rdMonth',
      label: '月',
      align: 'center',
      width: 80
    },
    {
      prop: 'rdDay',
      label: '日',
      align: 'center',
      width: 80
    },

    {
      prop: 'masterProjectName',
      label: '主项目',
      align: 'center',
      width: 120,

    },

    {
      prop: 'subProjectName',
      label: '子项目',
      align: 'center',
      width: 120,
    },
    {
      prop: 'certificateDate',
      label: '凭证日期',
      align: 'center',
      width: 120,
    },
    {
      prop: 'voucherNumber',
      label: '凭证号',
      align: 'center'
    },
    {
      prop: 'entryNumber',
      label: '分录号',
      align: 'center',

    },
    {
      prop: 'digest',
      label: '摘要',
      align: 'center',
      showOverflowTooltip: false,
    },
    {
      prop: 'accountCode',
      label: '科目编码',
      align: 'center',
      showOverflowTooltip: false,

    },
    {
      prop: 'accountName',
      label: '科目名称',
      align: 'center',
      showOverflowTooltip: false,
    },
    {
      prop: 'auxiliaryItem',
      label: '辅助项',
      align: 'center',
      showOverflowTooltip: false,
    },
    {
      prop: 'recordedAmount',
      label: '会计凭证记载金额(元)',
      align: 'center',
      width: 170
    },
    {
      prop: 'rdAmount',
      label: '归集研发费用金额(元)',
      align: 'center',
      width: 170
    },
  ],
  api: '/workflow/mosr/rd/expense/list',
  params: {},
  btns: [
    {name: '模板下载', key: 'down', color: '#DED0B2'},
    // {name: '导入', key: 'import', color: '#DED0B2'}
  ],
  export: {
    open: true,
    fileName: `研发费用明细表`
  }
})

const getMasterProjectName = async (val) => {
  const res = await getExpenseMasterProjectNameOption(val)
  if (res.code == 1000) {
    let optionObj = {}
    let optionsMap = new Map();
    res.data.forEach(item => {
      optionObj = {
        value: item.label,
        label: item.label
      }
      optionsMap.set(optionObj.value, optionObj);
    })
    if (!val) {
      localStorage.setItem('masterProjectNameOption', JSON.stringify(Array.from(optionsMap.values())))
    }
    // 将 Map 转换为数组
    searchConfig.value.find(item => item.prop == 'masterProjectName').props.options = Array.from(optionsMap.values())
  }
}
const getSubprojectName = async (val) => {
  const res = await getExpenseSubprojectNameOption(val)
  if (res.code == 1000) {
    let optionObj = {}
    let optionsMap = new Map();
    res.data.forEach(item => {
      optionObj = {
        value: item.label,
        label: item.label
      }
      optionsMap.set(optionObj.value, optionObj);
    })
    if (!val) {
      localStorage.setItem('subprojectNameOption', JSON.stringify(Array.from(optionsMap.values())))
    }
    // 将 Map 转换为数组
    searchConfig.value.find(item => item.prop == 'subProjectName').props.options = Array.from(optionsMap.values())
  }
}
getMasterProjectName()
getSubprojectName()

const search = (val) => {
  // 去除 rdMonth 前置0

  let param={
    ...val
  }
  if (param.rdMonth) {
    param.rdMonth = parseInt(param.rdMonth, 10).toString();
  }
  tableConfig.params = {...param}
  tableIns.value.refresh()
}

const headBtnClick = (key) => {
  switch (key) {
    case 'down':
      handleImportTemplateDownload()
      break;
    case 'import':
      handleAdd()
      break;
  }
}
const exportTable = () => {
  const $e = tableIns.value.$el
  let $table = $e.querySelector('.el-table__fixed')
  if (!$table) {
    $table = $e
  }
  exportExcel($table, (5 + (Object.keys(tableData.value[0]).length - 5) * 5), "四川省国有资产经营投资管理有限责任公司科技创新项目人工成本分摊明细表", 2)
}
//导入模板下载
const handleImportTemplateDownload = () => {
  costTemplateDownload().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 importTheExpenseLedger = () => {
  tableIns.value.refresh()
}
</script>
<style scoped lang="scss">
:deep(.el-form-item__label-wrap) {
  margin-left: 0 !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-date-editor--month) {
  width: 100%;
}
</style>
