<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" style="margin-left: 16px">></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick"
           @selectionChange="selectionChange"></fvTable>
</template>

<script setup lang="jsx">
import fvSelect from '@/fvcomponents/fvSelect/index.vue'
import {addPlan} from "@/api/project-demand/summary";

const tableIns = ref()
const router = useRouter()
const projectSelectList = ref([])
const shortcuts = [
  {
    text: '上周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '上月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '三月前',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
const searchConfig = reactive([
  {
    label: '征集名称',
    prop: 'requirementName',
    props: {
      placeholder: '请输入征集名称',
      clearable: true,
      checkStrictly: true
    },
    component: 'el-input',
    colProps: {}
  },
  {
    label: '项目类型',
    prop: 'projectType',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择项目类型',
      cacheKey: 'project_type',
      clearable: true,
      filterable: true,
      remote: true
    },
    colProps: {}
  },
  {
    label: '项目影响',
    prop: 'projectImpact',
    component: shallowRef(fvSelect),
    props: {
      cacheKey: 'project_impact',
      placeholder: '请选择项目影响',
      clearable: true,
      filterable: true,
      remote: true
    },
    colProps: {}
  },
  {
    label: '研发主体',
    prop: 'rdSubject',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择研发主体',
      cacheKey: 'rd_subject',
      clearable: true,
      filterable: true,
      remote: true
    }
  },
  {
    label: '起止时间',
    prop: 'dateValue',
    component: 'el-date-picker',
    props: {
      clearable: true,
      type: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      shortcuts: shortcuts
    }
  },
  {
    label: '状态',
    prop: 'state',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择状态',
      clearable: true,
      filterable:true,
      cacheKey: 'demand_summary',
      remote: true
    }
  },
  // {
  //   label: '项目影响',
  //   prop: 'projectImpact',
  //   component: shallowRef(fvSelect),
  //   props: {
  //     placeholder: '请选择项目影响',
  //     cacheKey: 'project_impact',
  //     clearable: true,
  //     filterable: true
  //   },
  //   colProps: {}
  // },
  // {
  //   label: '起止时间',
  //   prop: 'startTime',
  //   component: 'el-date-picker',
  //   props: {},
  //   colProps: {}
  // },
  // {
  //   label: '最小金额',
  //   prop: 'minMoney',
  //   component: 'el-input',
  //   colProps: {}
  // },
  // {
  //   label: '最大金额',
  //   prop: 'maxMoney',
  //   component: 'el-input',
  //   colProps: {}
  // },
])
const auths = {
  edit: ['mosr:collect:resubmit'],
  detail: ['mosr:collect:info'],
  report: ['mosr:collect:reported'],
  planAdd: ['annual:plan:add'],
}
const tableConfig = reactive({
  columns: [
    {
      type: 'selection',
      prop: 'selection',
      selectable: (row, index) => {
        return row.state === '4';
      }
    },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width:60,
      index: index => {
        return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
      }
    },
    {
      prop: 'requirementName',
      label: '征集名称',
      align: 'center'
    },
    {
      prop: 'projectName',
      label: '项目名称',
      align: 'center'
    },
    {
      prop: 'undertaker',
      label: '承办单位',
      align: 'center'
    },
    {
      prop: 'projectType',
      label: '项目类型',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.projectType !== null) {
          return (<Tag dictType={'project_type'} value={row.projectType}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'rdSubject',
      label: '研发主体',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.rdSubject !== null) {
          return (<Tag dictType={'rd_subject'} value={row.rdSubject}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'projectImpact',
      label: '项目影响',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.projectImpact !== null) {
          return (<Tag dictType={'project_impact'} value={row.projectImpact}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'startTime',
      label: '起止时间',
      align: 'center',
      currentRender: ({row}) => {
        return row.startTime + ' 至 ' + row.endTime
      }
    },
    {
      prop: 'state',
      label: '状态',
      align: 'center',
      width: 150,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.state !== null && row.state != 0) {
          return (<Tag dictType={'demand_summary'} value={row.state}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      fixed: 'right',
      width: 150,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        let btn = []
        let buttons = new Set(Array.from(row.buttons))
        if (buttons.has("details")) {
          btn.push({label: '详情', prem: auths.detail, func: () => handleDetail(row), type: 'primary'})
        }
        if (buttons.has("edit")) {
          btn.push({label: '编辑', prem: auths.edit, func: () => handleEdit(row), type: 'primary'})
        }
        return (
            <div style={{width: '100%'}}>
              {
                btn.map(item => (
                    <el-button
                        type={item.type}
                        v-perm={item.prem}
                        onClick={() => item.func()}
                        link
                    >
                      {item.label}
                    </el-button>
                ))
              }
            </div>
        )
      }
    }
  ],
  api: '/workflow/mosr/requirement/collect',
  params: {},
  btns: [
    {name: '新增上报', key: 'add', color: '#DED0B2', auth: auths.report},
    {name: '创建年度计划', key: 'export', color: '#DED0B2', auth: auths.planAdd},
    // {name: '经费预算生成', key: 'preMonty', auth: ''},
  ]
})
// {
//   buttons.has("delete") ?
//       <popover-delete name={row.requirementName} type={'需求'} btnType={'danger'}
//                       perm={['mosr:collect:del']} onDelete={() => handleDelete(row)}/>
//       : ''
// }
const headBtnClick = (key) => {
  switch (key) {
    case 'add':
      handleAdd()
      break;
    case 'export':
      createAnnualPlan()
      break;
  }
}
const selectionChange = (data) => {
  console.log('data', data, tableIns.value.tableInstance)

  data.forEach(item => {
    //   toggleRowSelection
  })
  projectSelectList.value = data
}
const createAnnualPlan = () => {
  let projectIds = []
  projectSelectList.value.map(item => {
    projectIds.push(item.projectId)
  })
  if (projectSelectList.value.length > 0) {
    let params = {
      projectIds: projectIds
    }
    addPlan(params).then(res => {
      if (res.code === 1000) {
        router.push({
          name: 'Plan/detail',
          query: {
            annualPlanId: res.data,
            type:'summary'
          }
        })
      }
    })
  }
}
const search = (val) => {
  let obj = {...val}
  if (obj.dateValue) {
    obj.startTime = obj.dateValue[0]
    obj.endTime = obj.dateValue[1]
    delete obj.dateValue
  }
  tableConfig.params = obj
  tableIns.value.refresh()
}

const handleAdd = () => {
  router.push({
    name: 'Summary/add',
    query: {
      // id: row.requirementId
    }
  })
}
const handleEdit = (row) => {
  router.push({
    name: 'Summary/edit',
    query: {
      id: row.requirementId,
      projectId: row.projectId
    }
  })
}
// const handleDetail = (row) => {
//   router.push({
//     name: 'Summary/detail',
//     query: {
//       id: row.requirementId == null ? '-1' : row.requirementId,
//       projectId: row.projectId,
//       state: row.state
//     }
//   })
// }

const handleDetail = (row) => {
  router.push({
    name: 'Implementation/detail',
    query: {
      id: row.requirementId == null ? '-1' : row.requirementId,
      projectId: row.projectId,
      state: row.state,
      step: '10'
    }
  })
}
</script>

<style lang="scss" scoped>

</style>
