<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" style="margin-left: 16px"></fvSearchForm>
  <fvTable ref="tableIns" :tableConfig="tableConfig">
    <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 {switchAttachmentState} from "@/api/project-manage/attachment";
import {ElMessageBox} from "element-plus";
import { getSubCompOpt } from '@/api/user/user.js';
import {filterProjectName} from "@/api/project-manage";
import {filterRequirementName} from "@/api/project-demand";

const router = useRouter()
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 = ref([
  {
    label: '征集名称',
    prop: 'requirementName',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请输入征集名称查询',
      clearable: true,
      filterable: true,
      options: [],
      remote: true,
      remoteMethod:async (val)=>{
        if(val){
          const res=await filterRequirementName(val)
          if(res.code==1000){
            let optionObj={}
            let options=[]
            res.data.forEach(item=>{
              optionObj={
                value:item,
                label:item
              }
              options.push(optionObj)
            })
            searchConfig.value.find(item => item.prop == 'requirementName').props.options = options
          }
        }
      }
    }
  },
  {
    label: '征集公司',
    prop: 'affiliatedCompanyId',
    component: 'el-tree-select',
    props: {
      placeholder: '请输入征集公司查询',
      clearable: true,
      data: [],
      filterable: true,
      checkStrictly: true,
      remote:true
    }
  },
  {
    label: '项目名称',
    prop: 'projectName',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请输入项目名称查询',
      clearable: true,
      filterable: true,
      options: [],
      remote: true,
      remoteMethod:async (val)=>{
        if(val){
          const res=await filterProjectName(val,'50')
          if(res.code==1000){
            let optionObj={}
            let options=[]
            res.data.forEach(item=>{
              optionObj={
                value:item,
                label:item
              }
              options.push(optionObj)
            })
            searchConfig.value.find(item => item.prop == 'projectName').props.options = options
          }
        }
      }
    }
  },
  {
    label: '项目类型',
    prop: 'projectType',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择项目类型',
      cacheKey: 'project_type',
      clearable: true,
      filterable: true,
      remote: true
    }
  },
  {
    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,
      cacheKey: 'project_filing',
      filterable: true,
      remote: true
    }
  },
  // {
  //   label: '最小金额',
  //   prop: 'requirementName',
  //   component: 'el-input',
  //   props: {
  //     placeholder: '请输入金额查询',
  //     clearable: true,
  //     filterable: true,
  //     checkStrictly: true
  //   }
  // },
  // {
  //   label: '最大金额',
  //   prop: 'requirementName',
  //   component: 'el-input',
  //   props: {
  //     placeholder: '请输入金额查询',
  //     clearable: true,
  //     filterable: true,
  //     checkStrictly: true
  //   }
  // },
])
const tableIns = ref()
const tableConfig = reactive({
  columns: [
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width:85,
      index: index => {
        return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
      }
    },
    {
      prop: 'requirementName',
      label: '征集名称',
      align: 'center',
    },
    {
      prop: 'affiliatedCompany',
      label: '征集公司',
      align: 'center'
    },
    {
      prop: 'projectName',
      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: 120,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.projectImpact !== null) {
          return (<Tag dictType={'project_impact'} value={row.projectImpact}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'economicEstimate',
      label: '预估经费预算',
      align: 'center',
      width: 150,
      currentRender:({row})=>{
        return <span>{toThousands(row.economicEstimate)}</span>
      }
    },
    {
      prop: 'startTime',
      label: '起止时间',
      align: 'center',
      currentRender: ({row}) => {
        return row.startTime + ' 至 ' + row.endTime
      }
    },
    {
      prop: 'approveName',
      label: '当前审批节点',
      align: 'center',
      width: 120,
      currentRender: ({row, index}) => {
        if(row.state=='3'||row.state=='4'){
          return <span>{row.taskNode}</span>
        }else  if(row.state=='1'){
          return <span>{row.approveName}</span>
        }else {
          return <span>--</span>
        }
      }
    },
    {
      prop: 'state',
      label: '状态',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.state !== null) {
          return (<Tag dictType={'project_filing'} 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: ['project:management:filing:detail'], func: () => handleDetail(row), type: 'primary'})
        }
        if (buttons.has("attachments")) {
          btn.push({label: '附件', prem: ['project:management:filing:attachment'], func: () => handleAttachment(row), type: 'primary'})
        }
        if (buttons.has("entry")) {
          btn.push({label: '结项', prem: ['project:management:filing:conclusion'], func: () => handleConclusion(row), type: 'primary'})
        }
        if (buttons.has("edit")) {
          btn.push({label: '编辑', prem: ['project:management:filing:conclusion'], func: () => handleEdit(row), type: 'primary'})
        }
        if (buttons.has("openFileSwitch")) {
          btn.push({label: '开启上传', prem: ['project:management:filing:conclusion'], func: () => handleOpenUpload(row,true), type: 'primary'})
        }
        if (buttons.has("closeFileSwitch")) {
          btn.push({label: '关闭上传', prem: ['project:management:filing:conclusion'], func: () => handleOpenUpload(row,false), 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/project/filing',
  params: {},
})

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 handleDetail = (row) => {
  router.push({
    name: 'Implementation/detail',
    query: {
      id: row.requirementId,
      projectId: row.projectId,
      state: row.state,
      step: '50'
    }
  })
}
const handleAttachment = (row) => {
  router.push({
    name: 'Filing/attachment',
    query: {
      id: row.projectId,
      requirementId:row.requirementId
    }
  })
}
const handleConclusion = (row) => {
  router.push({
    name: 'Filing/conclusion',
    query: {
      id: row.requirementId,
      projectId: row.projectId
    }
  })
}
const handleEdit = (row) => {
  router.push({
    name: 'Filing/edit',
    query: {
      id: row.requirementId,
      projectId: row.projectId
    }
  })
}
const handleOpenUpload=(row,flag)=>{
  ElMessageBox.confirm(`是否确认${flag?'开启':'关闭'}上传文件？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let params={
      open: flag,
      projectId:  row.projectId
    }
    switchAttachmentState(params).then(res=>{
      tableIns.value.refresh()
    })
  })
}
const init = async () => {
  const res = await getSubCompOpt()
  searchConfig.value.find(item=>item.prop == 'affiliatedCompanyId').props.data = res.data
}

init()
</script>
<style scoped lang="scss">
: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;
    }
  }
}
</style>
