<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <div class="w_1200">
          <el-col :span="24" class="one">
            <el-row :span="24" class="list">
              <el-col :span="4" class="left">
                <el-image
                  v-if="info.file && info.file.length > 0"
                  class="image"
                  :src="info.file[0].url"
                  fit="fill"
                />
                <el-image v-else class="image" :src="news" fit="fill" />
              </el-col>
              <el-col :span="18" class="right">
                <div class="join" :class="[info.match_status == '0' ? 'join0' : 'join1']">
                  {{ getDict(info.match_status, 'status') }}
                </div>
                <el-col :span="24" class="right_1">
                  <span class="type">{{ getDict(info.form, 'form') }}</span>
                  <span class="title">{{ info.name || '暂无比赛名称' }}</span>
                </el-col>
                <el-col :span="24" class="right_2">
                  组织单位：{{ info.organization || '暂无组织单位' }}
                </el-col>
                <el-col :span="24" class="right_2">
                  行业：{{ getDict(info.industry, 'industry') }}
                </el-col>
                <el-col :span="24" class="right_3">
                  <el-col :span="20" class="right_3Left">
                    比赛日期：{{ getTime(info.time) }}
                  </el-col>
                  <el-col :span="4" class="right_3Right">
                    {{ info.money || '免费' }}
                  </el-col>
                </el-col>
                <el-col :span="24" class="right_4">
                  <el-tag type="primary">{{ getDict(info.type, 'type') }}</el-tag>
                </el-col>
              </el-col>
              <el-col :span="2" class="file" @click="toCollection(0)" v-if="info.is_collection">
                <el-icon :size="16"><StarFilled /></el-icon>
                <span>已收藏</span>
              </el-col>
              <el-col :span="2" class="file" @click="toCollection(1)" v-else>
                <el-icon :size="16"><Star /></el-icon>
                <span>收藏</span>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24" class="two">
            <el-row class="two_1">
              <el-col :span="22" class="twoLeft">
                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                  <el-tab-pane label="赛制规则" name="first"></el-tab-pane>
                  <el-tab-pane label="常见问题" name="second"></el-tab-pane>
                </el-tabs>
              </el-col>
              <el-col :span="2" class="twoRight" v-if="info.match_status == '1'">
                <a-button type="primary" @click="toSign"> 报名参赛 </a-button>
              </el-col>
            </el-row>
            <el-row class="two_2" v-if="activeName === 'first'">
              <el-container style="height: 500px">
                <el-aside width="200px">
                  <el-menu default-active="rules1" class="el-menu" @select="selectOpen">
                    <el-menu-item
                      :index="item.label"
                      v-for="(item, index) in menuList"
                      :key="index"
                    >
                      <el-icon><Opportunity /></el-icon>
                      <span>{{ item.title }}</span>
                    </el-menu-item>
                  </el-menu>
                </el-aside>
                <el-main>
                  <el-col :span="24">
                    <h2>{{ rulesInfo.title }}</h2>
                    <div class="rich-text-container" v-html="rulesInfo.content"></div>
                  </el-col>
                </el-main>
              </el-container>
            </el-row>
            <el-row class="two_2" v-if="activeName === 'second'">
              <div v-html="info.brief"></div>
            </el-row>
          </el-col>
          <el-col :span="24" class="thr">
            <el-col :span="24" class="thr_1"> 相关推荐 </el-col>
            <el-col :span="24" class="thr_2">
              <el-col
                :span="11"
                class="list"
                v-for="(item, index) in list"
                :key="index"
                @click="toView(item)"
              >
                <div class="join" :class="[item.match_status == '0' ? 'join0' : 'join1']">
                  {{ getDict(item.match_status, 'status') }}
                </div>
                <el-col :span="6" class="left">
                  <el-image
                    v-if="item.file && item.file.length > 0"
                    class="image"
                    :src="item.file[0].url"
                    fit="fill"
                  />
                  <el-image v-else class="image" :src="news" fit="fill" />
                </el-col>
                <el-col :span="18" class="right">
                  <el-col :span="24" class="right_1">
                    <span class="type">{{ getDict(item.form, 'form') }}</span>
                    <span class="title">{{ item.name || '暂无比赛名称' }}</span>
                  </el-col>
                  <el-col :span="24" class="right_2">
                    组织单位：{{ item.organization || '暂无组织单位' }}
                  </el-col>
                  <el-col :span="24" class="right_3">
                    <el-col :span="16" class="right_3Left">
                      比赛日期：{{ getTime(item.time) }}
                    </el-col>
                    <el-col :span="8" class="right_3Right">
                      {{ item.money || '免费' }}
                    </el-col>
                  </el-col>
                  <el-col :span="24" class="right_4">
                    <el-tag type="primary">{{ getDict(item.type, 'type') }}</el-tag>
                  </el-col>
                </el-col>
              </el-col>
            </el-col>
          </el-col>
        </div>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog" title="报名参赛" :destroy-on-close="true" @close="toClose">
      <data-form></data-form>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from 'moment'
import { get, cloneDeep } from 'lodash-es'
const $checkRes = inject('$checkRes')
// 组件
import dataForm from './parts/index.vue'
// 接口
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
import { DictDataStore } from '@/store/api/system/dictData'
import { CollectionStore } from '@/store/api/platform/collection'
import { MatchStore } from '@/store/api/platform/match'
import { SignStore } from '@/store/api/platform/sign'
const store = MatchStore()
const signStore = SignStore()
const collectionStore = CollectionStore()
const dictDataStore = DictDataStore()
// 图片引入
import news from '/images/news.png'
// 路由
const route = useRoute()
const router = useRouter()
// 加载中
const loading = ref(false)
const info = ref({})
const rulesInfo = ref({})
const activeName = ref('first')
// 字典表
const statusList = ref([])
const typeList = ref([])
const formList = ref([])
const cardTypeList = ref([])
const industryList = ref([])
const menuList = ref([
  { title: '大赛背景', label: 'rules1' },
  { title: '大赛主题和目标', label: 'rules2' },
  { title: '大赛基本情况介绍', label: 'rules3' },
  { title: '赛题任务', label: 'rules4' },
  { title: '赛程安排', label: 'rules5' },
  { title: '赛制阶段', label: 'rules6' },
  { title: '参赛资格', label: 'rules7' },
  { title: '参赛报名', label: 'rules8' },
  { title: '奖项设置与奖励办法', label: 'rules9' },
  { title: '组织单位', label: 'rules10' },
  { title: '赛事联络', label: 'rules11' },
  { title: '赛事交流', label: 'rules12' }
])
// 弹框
const ruleFormRef = ref()
const form = ref({})
const validatePhoneNumber = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/
  if (!value) {
    return callback(new Error('手机号不能为空'))
  }
  if (!reg.test(value)) {
    return callback(new Error('请输入正确的手机号'))
  }
  callback()
}
const validateCardNumber = (rule, value, callback) => {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!value) {
    return callback(new Error('证件号码不能为空'))
  }
  if (!reg.test(value)) {
    return callback(new Error('请输入正确的证件号码'))
  }
  callback()
}
const rules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, validator: validatePhoneNumber, trigger: 'blur' }],
  cardType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
  card: [{ required: true, validator: validateCardNumber, trigger: 'change' }],
  remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
})
const dialog = ref(false)
// 列表
const list = ref([])
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  await search()
  await searchMatch()
  loading.value = false
})
const searchOther = async () => {
  let result
  // 类型
  result = await dictDataStore.query({ code: 'matchType', is_use: '0' })
  if ($checkRes(result)) typeList.value = result.data
  // 类别
  result = await dictDataStore.query({ code: 'matchForm', is_use: '0' })
  if ($checkRes(result)) formList.value = result.data
  // 赛事状态
  result = await dictDataStore.query({ code: 'matchStatus', is_use: '0' })
  if ($checkRes(result)) statusList.value = result.data
  // 证件类型
  result = await dictDataStore.query({ code: 'cardType', is_use: '0' })
  if ($checkRes(result)) cardTypeList.value = result.data
  // 赛事行业
  result = await dictDataStore.query({ code: 'matchIndustry', is_use: '0' })
  if ($checkRes(result)) industryList.value = result.data
}
const searchMatch = async () => {
  const info = {
    skip: 0,
    limit: 10,
    is_use: '0',
    status: '1'
  }
  const res = await store.query(info)
  if (res.errcode == '0') list.value = res.data
}
const search = async () => {
  let id = route.query.id
  if (id) {
    let res = await store.detail(id)
    if (res.errcode == '0') {
      info.value = res.data
      rulesInfo.value = { title: '大赛背景', key: 'rules1', content: res.data.rules.rules1 }
    }
  }
}
// 字典数据转换
const getDict = (data, model) => {
  let res
  if (model == 'status') res = statusList.value.find((f) => f.value == data)
  else if (model == 'type') res = typeList.value.find((f) => f.value == data)
  else if (model == 'industry') res = industryList.value.find((f) => f.value == data)
  else if (model == 'form') res = formList.value.find((f) => f.value == data)
  return get(res, 'label')
}
// 时间
const getTime = (data) => {
  if (data) return `${data[0]} - ${data[1]}`
}
const selectOpen = (key) => {
  const res = menuList.value.find((f) => f.label == key)
  if (res) {
    rulesInfo.value = { title: get(res, 'title'), key, content: get(info.value.rules, key) }
  }
}
// 查看
const toView = (item) => {
  router.push({ path: '/innovation/detail', query: { id: item.id || item._id } })
}
// 报名参赛
const toSign = () => {
  dialog.value = true
}
const toClose = () => {
  dialog.value = false
  form.value = {}
}
// 收藏
const toCollection = async (status) => {
  if (user.value._id) {
    let res
    let message
    const data = {
      user: user.value._id,
      source: info.value._id,
      type: 'match',
      time: moment().format('YYYY-MM-DD')
    }
    if (status == '1') {
      message = '收藏成功'
      res = await collectionStore.create(data)
    } else {
      message = '取消收藏成功'
      res = await collectionStore.cancel(data)
    }
    if (res.errcode === 0) {
      ElMessage({
        message,
        type: 'success'
      })
      await search()
    }
  } else {
    ElMessage({
      message: '未登录无法进行收藏 请登录',
      type: 'warning'
    })
  }
}
// 报名
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = cloneDeep(form.value)
      const other = {
        match: info.value._id,
        user: user.value._id,
        time: moment().format('YYYY-MM-DD')
      }
      let res = await signStore.create({ ...data, ...other })
      if ($checkRes(res, true)) toClose()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// provide
provide('form', form)
provide('rules', rules)
provide('ruleFormRef', ruleFormRef)
provide('cardTypeList', cardTypeList)
provide('submitForm', submitForm)
</script>
<style scoped lang="scss">
.main {
  background: rgb(248, 248, 248);
  .one {
    margin-top: 20px;
    background: #ffffff;
    border-radius: 10px;
    padding: 15px;

    .list {
      display: flex;
      align-items: center;
      min-height: 150px;
      width: 100%;
      margin-bottom: 10px;
      position: relative;
      overflow: hidden;
      border: 1px solid #f5f5f5;
      .left {
        display: flex;
        align-items: center;
        justify-content: center;
        .image {
          width: 180px;
          height: 120px;
        }
      }
      .right {
        .right_1 {
          padding: 10px 0 0 0;
          .type {
            padding-left: 4px;
            padding-right: 4px;
            height: 22px;
            line-height: 20px;
            background: #f8f9fc;
            border-radius: 1px;
            border: 1px solid #dde2e7;
            font-size: 12px;
            font-family:
              PingFangSC-Regular,
              PingFang SC;
            font-weight: 400;
            color: #a9b2c6;
            text-align: center;
            vertical-align: top;
            display: inline-block;
            margin-right: 8px;
          }
          .title {
            max-width: 88%;
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 16px;
            font-family:
              PingFangSC-Medium,
              PingFang SC;
            font-weight: 500;
            color: #222;
            line-height: 22px;
          }
        }
        .right_2 {
          padding: 5px 0;
          font-size: 12px;
          font-family:
            PingFangSC-Regular,
            PingFang SC;
          font-weight: 400;
          color: #666;
        }
        .right_3 {
          padding: 5px 0;
          display: flex;
          justify-content: space-between;
          .right_3Left {
            font-size: 12px;
            font-family:
              PingFangSC-Regular,
              PingFang SC;
            font-weight: 400;
            color: #949fb8;
          }
          .right_3Right {
            text-align: right;
            font-size: 16px;
            font-family:
              PingFangSC-Semibold,
              PingFang SC;
            font-weight: 600;
            color: #ff5602;
          }
        }
        .right_4 {
          padding: 5px 0;
          border-top: 1px solid #f3f3f3;
        }
      }
      .file {
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: PingFangSC-Regular;
        font-size: 14px;
        color: #2374ff;
        span {
          margin: 0 0 0 5px;
        }
      }
      .join {
        position: absolute;
        right: -23px;
        top: 10px;
        font-size: 12px;
        font-family:
          PingFangSC-Normal,
          PingFang SC;
        color: #fff;
        line-height: 21px;
        height: 21px;
        width: 100px;
        text-align: center;
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        padding-left: 9px;
      }
      .join0 {
        background: #e6f4fe;
        color: #638aa5;
      }
      .join1 {
        background: #ededed;
        color: #666c7d;
      }
    }
  }
  .two {
    margin: 20px 0;
    background: #ffffff;
    border-radius: 10px;
    padding: 15px;
    .two_1 {
      border-bottom: 1px solid #e4e7ed;
      :deep(.el-tabs__nav-wrap:after) {
        background-color: transparent !important;
      }
    }
    .two_2 {
      padding: 15px;
      min-height: 500px;
      :deep(.el-aside)::-webkit-scrollbar {
        display: none;
      }
      h2 {
        padding-bottom: 0.3em;
        border-bottom: 1px solid #eaecef;
      }
      .rich-text-container {
        :deep(table) {
          border-collapse: collapse;
        }
        :deep(table) {
          border: 1px solid black;
        }
        :deep(th) {
          border: 1px solid black;
        }
        :deep(td) {
          border: 1px solid black;
        }
      }
    }
  }
  .thr {
    margin: 20px 0;
    background: #ffffff;
    border-radius: 10px;
    padding: 15px;
    .thr_1 {
      padding: 10px;
      font-family: PingFangSC-Semibold;
      font-size: 18px;
      color: #383b40;
      letter-spacing: 0;
      line-height: 18px;
      font-weight: 600;
    }
    .thr_2 {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      margin: 10px 0 0 0;
      .list {
        display: flex;
        align-items: center;
        min-height: 150px;
        width: 100%;
        margin: 10px;
        position: relative;
        overflow: hidden;
        border: 1px solid #f5f5f5;
        .left {
          display: flex;
          align-items: center;
          justify-content: center;
          .image {
            width: 120px;
            height: 120px;
          }
        }
        .right {
          .right_1 {
            padding: 10px 0 0 0;
            .type {
              padding-left: 4px;
              padding-right: 4px;
              height: 22px;
              line-height: 20px;
              background: #f8f9fc;
              border-radius: 1px;
              border: 1px solid #dde2e7;
              font-size: 12px;
              font-family:
                PingFangSC-Regular,
                PingFang SC;
              font-weight: 400;
              color: #a9b2c6;
              text-align: center;
              vertical-align: top;
              display: inline-block;
              margin-right: 8px;
            }
            .title {
              max-width: 88%;
              display: inline-block;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              font-size: 16px;
              font-family:
                PingFangSC-Medium,
                PingFang SC;
              font-weight: 500;
              color: #222;
              line-height: 22px;
            }
          }
          .right_2 {
            padding: 5px 0;
            font-size: 12px;
            font-family:
              PingFangSC-Regular,
              PingFang SC;
            font-weight: 400;
            color: #666;
          }
          .right_3 {
            padding: 5px 5px 5px 0;
            display: flex;
            justify-content: space-between;
            .right_3Left {
              font-size: 12px;
              font-family:
                PingFangSC-Regular,
                PingFang SC;
              font-weight: 400;
              color: #949fb8;
            }
            .right_3Right {
              text-align: right;
              font-size: 16px;
              font-family:
                PingFangSC-Semibold,
                PingFang SC;
              font-weight: 600;
              color: #ff5602;
            }
          }
          .right_4 {
            padding: 5px 0;
            border-top: 1px solid #f3f3f3;
          }
        }
        .join {
          position: absolute;
          right: -23px;
          top: 10px;
          font-size: 12px;
          font-family:
            PingFangSC-Normal,
            PingFang SC;
          color: #fff;
          line-height: 21px;
          height: 21px;
          width: 100px;
          text-align: center;
          -ms-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          padding-left: 9px;
        }
        .join0 {
          background: #e6f4fe;
          color: #638aa5;
        }
        .join1 {
          background: #ededed;
          color: #666c7d;
        }
      }
    }
  }
}
</style>
