<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <div class="w_1200 one">
          <demand v-if="routeType == 'demand'"></demand>
          <project v-if="routeType == 'project'"></project>
          <match v-if="routeType == 'match'"></match>
          <achievement v-if="routeType == 'achievement'"></achievement>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
const $checkRes = inject('$checkRes')
import { cloneDeep, get } from 'lodash-es'
const route = useRoute()
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
// 接口
import { AchievementStore } from '@/store/api/platform/achievement'
import { DemandStore } from '@/store/api/platform/demand'
import { SupplyStore } from '@/store/api/platform/supply'
import { ProjectStore } from '@/store/api/platform/project'
import { MatchStore } from '@/store/api/platform/match'
import { DictDataStore } from '@/store/api/system/dictData'
const achieveStore = AchievementStore()
const demandStore = DemandStore()
const projectStore = ProjectStore()
const matchStore = MatchStore()
const dictDataStore = DictDataStore()
const supplyStore = SupplyStore()
// 组件
import demand from './parts/demand.vue'
import project from './parts/project.vue'
import match from './parts/match.vue'
import achievement from './parts/achievement.vue'
// 加载中
const loading = ref(false)
// 路由
const router = useRouter()
// 显示类型
const type = ref('0')
const routeType = ref('0')
const form = ref({})
const typeDemand = ref('0')
// 字典表
const fieldList = ref([])
const statusList = ref([])
const matchList = ref([])
const typeList = ref([
  { value: '0', label: '供给' },
  { value: '1', label: '需求' }
])
//
const fields = ref([])
// 列表
const list = ref([])
let skip = 0
let limit = inject('limit')
const total = ref(0)
const currentPage = ref(1)
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  await searchField()
  loading.value = false
})
const searchField = async () => {
  routeType.value = route.query.type
  if (routeType.value == 'achievement') {
    fields.value = [
      { label: '成果名称', model: 'name', type: 'name' },
      { label: '技术领域：', model: 'field', type: 'dict' },
      { label: '成果地区：', model: 'area', type: 'area' },
      { label: '审核状态：', model: 'status', type: 'dict' }
    ]
  } else if (routeType.value == 'demand') {
    fields.value = [
      { label: '需求名称', model: 'name', type: 'name' },
      { label: '技术领域：', model: 'field', type: 'dict' },
      { label: '类型：', model: 'type', type: 'dict' },
      { label: '需求地区：', model: 'area', type: 'area' },
      { label: '审核状态：', model: 'status', type: 'dict' }
    ]
  } else if (routeType.value == 'project') {
    fields.value = [
      { label: '项目名称', model: 'name', type: 'name' },
      { label: '技术领域：', model: 'field', type: 'dict' },
      { label: '发布时间：', model: 'time' },
      { label: '项目地区：', model: 'area', type: 'area' },
      { label: '审核状态：', model: 'status', type: 'dict' }
    ]
  } else if (routeType.value == 'match') {
    fields.value = [
      { label: '比赛名称', model: 'name', type: 'name' },
      { label: '比赛金额：', model: 'money' },
      { label: '比赛日期：', model: 'time', type: 'time' },
      { label: '赛事状态：', model: 'match_status', type: 'dict' },
      { label: '审核状态：', model: 'status', type: 'dict' }
    ]
  }
  await search({ skip, limit })
}
const search = async (query = { skip: 0, limit }) => {
  const info = {
    skip: query.skip,
    limit: query.limit,
    user: user.value._id
  }
  let res
  if (routeType.value == 'achievement') res = await achieveStore.query(info)
  else if (routeType.value == 'demand') {
    if (typeDemand.value == '0') res = await demandStore.query(info)
    else if (typeDemand.value == '1') res = await supplyStore.query(info)
  } else if (routeType.value == 'project') res = await projectStore.query(info)
  else if (routeType.value == 'match') res = await matchStore.query(info)
  if (res.errcode == '0') {
    list.value = res.data
    total.value = res.total
  }
}
const handleClick = async (tab) => {
  typeDemand.value = tab.props.name
  loading.value = true
  await search({ skip, limit })
  loading.value = false
}
const searchOther = async () => {
  let result
  // 技术领域
  result = await dictDataStore.query({ code: 'field', is_use: '0' })
  if ($checkRes(result)) fieldList.value = result.data
  // 状态
  result = await dictDataStore.query({ code: 'examStatus', is_use: '0' })
  if ($checkRes(result)) statusList.value = result.data
  // 赛事状态
  result = await dictDataStore.query({ code: 'matchStatus', is_use: '0' })
  if ($checkRes(result)) matchList.value = result.data
}
// 字典数据转换
const getDict = (data, model) => {
  let res
  if (model == 'field') res = fieldList.value.find((f) => f.value == data)
  if (model == 'status') res = statusList.value.find((f) => f.value == data)
  if (model == 'type') res = typeList.value.find((f) => f.value == data)
  if (model == 'match_status') res = matchList.value.find((f) => f.value == data)
  return get(res, 'label')
}
// 地区显示
const getArea = (data) => {
  if (data) return data.join(',')
  else return '暂无'
}
// 时间
const getTime = (data) => {
  if (data) return `${data[0]} - ${data[1]}`
  else return '暂无'
}
const toCommon = (data) => {
  if (routeType.value == 'match') form.value = { file: [], rules: {} }
  else form.value = {}
  type.value = data
}
// 查看
const toView = (item) => {
  let path
  if (routeType.value == 'achievement') path = '/achievement/detail'
  else if (routeType.value == 'demand') path = '/demand/detail'
  else if (routeType.value == 'project') path = '/project/detail'
  else if (routeType.value == 'match') path = '/innovation/detail'
  router.push({ path, query: { id: item.id || item._id } })
}
// 删除
const toDel = (item) => {
  ElMessageBox.confirm('是否确认删除该信息?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res
      if (routeType.value == 'achievement') res = await achieveStore.del(item._id)
      else if (routeType.value == 'demand') {
        if (typeDemand.value == '0') res = await demandStore.del(item._id)
        else if (typeDemand.value == '1') res = await supplyStore.del(item._id)
      } else if (routeType.value == 'project') res = await projectStore.del(item._id)
      else if (routeType.value == 'match') res = await matchStore.del(item._id)
      if ($checkRes(res, true)) {
        search({ skip: 0, limit })
      }
    })
    .catch(() => {})
}
// 修改
const toEdit = (item) => {
  form.value = item
  type.value = '1'
}
// 保存
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = cloneDeep(form.value)
      const other = { status: '0', user: user.value._id }
      let res
      if (get(data, '_id')) {
        if (routeType.value == 'achievement') res = await achieveStore.update({ ...data, ...other })
        else if (routeType.value == 'demand') {
          if (typeDemand.value == '0') res = await demandStore.update({ ...data, ...other })
          else if (typeDemand.value == '1') res = await supplyStore.update({ ...data, ...other })
        } else if (routeType.value == 'project') {
          res = await projectStore.update({ ...data, ...other })
        } else if (routeType.value == 'match') res = await matchStore.update({ ...data, ...other })
      } else {
        if (routeType.value == 'achievement') res = await achieveStore.create({ ...data, ...other })
        else if (routeType.value == 'demand') {
          if (typeDemand.value == '0') res = await demandStore.create({ ...data, ...other })
          else if (typeDemand.value == '1') res = await supplyStore.create({ ...data, ...other })
        } else if (routeType.value == 'project') {
          res = await projectStore.create({ ...data, ...other })
        } else if (routeType.value == 'match') res = await matchStore.create({ ...data, ...other })
      }
      if ($checkRes(res, true)) {
        type.value = '0'
        list.value = []
        searchField()
        search({ skip: 0, limit })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 分页
const changePage = (page = currentPage.value) => {
  search({ skip: (page - 1) * limit, limit: limit })
}
const sizeChange = (limits) => {
  limit = limits
  currentPage.value = 1
  search({ skip: 0, limit: limit })
}
watch(
  route,
  (newVal) => {
    if (newVal) {
      type.value = '0'
      list.value = []
      if (routeType.value == 'match') form.value = { file: [], rules: {} }
      else form.value = {}
      searchField()
    }
  },
  {
    immediate: true //初始化立即执行
  }
)
// provide
provide('form', form)
provide('type', type)
provide('toCommon', toCommon)
provide('submitForm', submitForm)
provide('fields', fields)
provide('list', list)
provide('toView', toView)
provide('toEdit', toEdit)
provide('toDel', toDel)
provide('getArea', getArea)
provide('getTime', getTime)
provide('getDict', getDict)
provide('limit', limit)
provide('total', total)
provide('currentPage', currentPage)
provide('sizeChange', sizeChange)
provide('changePage', changePage)
provide('handleClick', handleClick)
</script>
<style scoped lang="scss">
.main {
  background-color: #f1f2f5;
  padding: 10px;
  min-height: 77vh;
}
</style>
