<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" searchProp="state" :searchValue="route.query.state" 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 { getSubCompOpt } from '@/api/user/user.js';
import {filterProjectName} from "@/api/project-manage";
import {filterRequirementName} from "@/api/project-demand";

const route = useRoute()
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,'40')
          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: {
      placeholder: '请选择项目影响',
      cacheKey: 'project_impact',
      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: 'project_implementation',
      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: [
    // {
    //   type: 'selection',
    //   prop: 'selection'
    // },
    {
      prop: 'index',
      type: 'index',
      label: '序号',
      align: 'center',
      width:85,
      index: index => {
        return (tableIns.value.getQuery().pageNum - 1) * tableIns.value.getQuery().pageSize + index + 1
      }
    },

    {
      prop: 'processNumber',
      label: '项目编号',
      align: 'center',
    },
    {
      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 && row.projectType !== null && row.projectType !== undefined) {
          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 && row.rdSubject !== null && row.rdSubject !== undefined) {
          return (<Tag dictType={'rd_subject'} value={row.rdSubject}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'researchStage',
      label: '研发阶段',
      align: 'center',
      width: 100,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.researchStage && row.researchStage !== null && row.researchStage !== undefined) {
          return (<Tag dictType={'research_stage'} value={row.researchStage}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'projectImpact',
      label: '项目影响',
      align: 'center',
      width: 120,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        if (row.projectImpact && row.projectImpact !== null && row.projectImpact !== undefined) {
          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 && row.state !== null && row.state !== undefined) {
          return (<Tag dictType={'project_implementation'} value={row.state}/>)
        } else {
          return '--'
        }
      }
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      fixed:'right',
      showOverflowTooltip: false,
      currentRender: ({row, index}) => {
        let btn = []
        let buttons = new Set(Array.from(row.buttons))
        if (buttons.has("details")) {
          btn.push({label: '详情', prem: ['mosr:implementation:info'], func: () => handleDetail(row), type: 'primary'})
        }
        if (buttons.has("check")) {
          btn.push({label: '验收', prem: ['mosr:implementation:check'], func: () => handleCheck(row), type: 'primary'})
        }
        if (buttons.has("edit")) {
          btn.push({label: '编辑', prem: ['mosr:implementation:resubmit'], func: () => handleEdit(row), type: 'primary'})
        }
        if (buttons.has("standing")) {
          btn.push({label: '台账', prem: ['project:management:implementation:account'], func: () => handleStandingBook(row), type: 'primary'})
        }
        // if (buttons.has("attachments")) {
        // btn.push({label: '附件', prem: ['project:management:implementation:attachment'], func: () => handleAttachment(row), type: 'primary'})
        // }
        if (buttons.has("viewAllocation")) {
          btn.push({label: '查看分摊', prem: ['project:management:implementation:share'], func: () => handleShare(row), type: 'primary'})
        }
        if (buttons.has("phaseChange")) {
          btn.push({label: '阶段变更', prem: ['mosr:phase:change'], func: () => handlePhaseChange(row), type: 'primary'})
        }
        if (buttons.has("phaseChangeInfo")) {
          btn.push({label: '阶段变更详情', prem: ['mosr:phase:info'], func: () => handlePhaseChangeDetail(row), type: 'primary'})
        }
        if (buttons.has("phaseChangeEdit")) {
          btn.push({label: '阶段变更编辑', prem: ['mosr:phase:resubmit'], func: () => handlePhaseChangeEdit(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/project/implementation',
  params: {},
  btns: [
    // {name: '生成分摊报表', key: '_export', color: '#DED0B2', auth: ''}
  ]
})

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) => {
  let step=''
  if(row.state==0){
    step='30'
  }else {
    step='40'
  }
  router.push({
    name: 'Implementation/detail',
    query: {
      id: row.requirementId,
      projectId: row.projectId,
      state: row.state,
      step: step
    }
  })
}
const handleCheck = (row) => {
  router.push({
    name: 'Implementation/check',
    query: {
      id: row.requirementId,
      projectId: row.projectId
    }
  })
}
const handleEdit = (row) => {
  router.push({
    name: 'Implementation/edit',
    query: {
      id: row.requirementId,
      projectId: row.projectId
    }
  })
}
const handleStandingBook = (row) => {
  router.push({
    name: 'Implementation/account',
    query: {
      id: row.projectId
    }
  })
}
const handleAttachment = (row) => {
  router.push({
    name: 'Implementation/attachment',
    query: {
      id: row.projectId,
    }
  })
}
const handleShare = (row) => {
  router.push({
    name: 'Implementation/share',
    query: {
      id: row.projectId
    }
  })
}
const handlePhaseChange = (row) => {
  router.push({
    name: 'Phase/change',
    query: {
      id: row.requirementId,
      projectId:row.projectId
    }
  })
}
const handlePhaseChangeDetail = (row) => {
  router.push({
    name: 'Phase/detail',
    query: {
      projectId:row.projectId
    }
  })
}

const handlePhaseChangeEdit = (row) => {
  router.push({
    name: 'Phase/edit',
    query: {
      id: row.requirementId,
      projectId:row.projectId
    }
  })
}
const init = async () => {
  const res = await getSubCompOpt()
  searchConfig.value.find(item=>item.prop == 'affiliatedCompanyId').props.data = res.data
  if(route.query.state=='0'){
    search({state:route.query.state})
  }else if(route.query.state=='4'){
    search({state:route.query.state})
  }
}

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>
