<template>
  <fvSearchForm :searchConfig="searchConfig" @search="search" searchProp="state"  style="margin-left: 16px"></fvSearchForm>


  <fvTable ref="tableIns" :tableConfig="tableConfig" @headBtnClick="headBtnClick">
    <template #empty>
      <el-empty description="暂无数据"/>
    </template>
  </fvTable>
</template>

<script setup lang="jsx">
import {useAuthStore} from '@/stores/userstore.js'
import Tag from '@/components/Tag.vue'
import {ElNotification} from "element-plus";
import {useCacheStore} from '@/stores/cache.js'
import {getRequirementStatePerm,filterRequirementName,deleteDemand} from "@/api/project-demand";
import {getSubCompOpt} from "@/api/user/user";
import fvSelect from "@/fvcomponents/fvSelect/index.vue";

const cacheStore = useCacheStore()
const authStore = useAuthStore()
const router = useRouter()
const tableIns = ref()
const userInfo = ref(authStore.userinfo)
const auths = {
  edit: ['mosr:requirement:resubmit'],
  detail: ['mosr:requirement:info'],
  add: ['mosr:requirement:add'],
  del: ['mosr:requirement:del'],
  report: ['mosr:collect:reported'],
}
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: 'collectType',
      label: '征集类型',
      align: 'center',
      // width: 200
    },
    {
      prop: 'companyName',
      label: '征集公司',
      align: 'center',
      // width: 200
    },

    {
      prop: 'deadline',
      label: '需求上报截止时间',
      align: 'center',
      width: 150,
    },
    {
      prop: 'approveName',
      label: '当前审批节点',
      align: 'center',
      width: 120,
      currentRender: ({row, index}) => {
        if (row.state == '1') {
          return <span>{row.approveName}</span>
        } else {
          return <span>{row.taskNode}</span>
        }
      }
    },
    {
      prop: 'state',
      label: '状态',
      align: 'center',
      width: 120,
      showOverflowTooltip: false,
      currentRender: ({row, index}) => (<Tag dictType={'demand_collection'} value={row.state}/>)
    },
    {
      prop: 'oper',
      label: '操作',
      align: 'center',
      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'})
        }
        if (buttons.has("report")) {
          btn.push({label: '需求上报', prem: auths.report, func: () => handleReport(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>
                ))
              }
              {
                buttons.has("delete") ?
                    <popover-delete name={row.requirementName} type={'需求征集'} btnType={'danger'}
                                    perm={auths.del}
                                    onDelete={() => handleDelete(row)}/> : ''
              }
            </div>
        )
      }
    }
  ],
  api: '/workflow/mosr/requirement',
  btns: [
    {name: '新增', key: 'add', color: '#DED0B2', auth: auths.add},
    // {name: '导出', key: 'export', type: ''},
  ],
  params: {}
})


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: 'collectType',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择征集类型',
      cacheKey: 'collect_type',
      clearable: true,
      filterable: true,
      remote: true
    }
  },
  {
    label: '征集公司',
    prop: 'affiliatedCompanyId',
    component: 'el-tree-select',
    props: {
      placeholder: '请输入征集公司查询',
      clearable: true,
      data: [],
      filterable: true,
      checkStrictly: true,
      remote: true
    }
  },
  {
    label: '状态',
    prop: 'state',
    component: shallowRef(fvSelect),
    props: {
      placeholder: '请选择状态',
      clearable: true,
      filterable: true,
      options: [],
      remote: true,
    }
  },
])

const init = async () => {
  const res = await getSubCompOpt()
  searchConfig.value.find(item=>item.prop == 'affiliatedCompanyId').props.data = res.data
  const res1 = await getRequirementStatePerm()
  searchConfig.value.find(item=>item.prop == 'state').props.options = res1.data
}

init()

const search = (val) => {
  tableConfig.params = {...val}
  tableIns.value.refresh()
}
const handleAdd = (row) => {
  router.push({
    name: 'Requirement/add',
    query: {
      // id: row.requirementId
    }
  })
}
const handleEdit = (row) => {
  router.push({
    name: 'Requirement/edit',
    query: {
      id: row.requirementId
    }
  })
}
const handleDelete = (row) => {
  deleteDemand(row.requirementId).then(res => {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: res.code === 1000 ? 'success' : 'error'
    })
    tableIns.value.refresh()
  })
}
const handleDetail = (row) => {
  router.push({
    name: 'Requirement/detail',
    query: {
      id: row.requirementId
    }
  })
}
const handleReport = (row) => {
  router.push({
    name: 'Summary/add',
    query: {
      id: row.requirementId
    }
  })
}
const headBtnClick = (key) => {
  switch (key) {
    case 'add':
      handleAdd()
      break;
    case 'export':
      handleExport()
      break;
  }
}
</script>
<style lang="scss">
.select-form {
  .el-select {

    .el-select__wrapper {
      .el-select__suffix::before {
        content: "";
        width: 6px;
        height: 6px;
        border: solid #a8abb2;
        border-width: 0 0 1px 1px;
        transform: translate(-50%, -50%) rotate(-45deg);
      }
    }

    .is-focused {
      .el-select__suffix::before {
        margin-top: 10px;
        transform: translate(-50%, -50%) rotate(-225deg) !important;
      }
    }
  }
}
</style>
<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>
