<template>
  <custom-layout class="main">
    <el-col :span="24" class="w_1300 one">
      <div v-if="!user.id">
        <div class="text">注册信息</div>
        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px" class="form" label-position="left">
          <el-form-item label="账号" prop="account">
            <el-input size="large" clearable v-model="form.account" placeholder="请输入姓名/单位名称">
              <template #prefix>
                <el-icon>
                  <Avatar />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input size="large" clearable v-model="form.phone" placeholder="请输入手机号">
              <template #prefix>
                <el-icon>
                  <Iphone />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input size="large" v-model="form.password" type="password" show-password placeholder="请输入包含英文字母大小写、数字和特殊符号的 8-16 位组合">
              <template #prefix>
                <el-icon>
                  <Unlock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email">
            <el-input size="large" clearable v-model="form.email" placeholder="请输入电子邮箱">
              <template #prefix>
                <el-icon>
                  <Briefcase />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="text">填报信息</div>
      <div class="list" v-for="(item, index) in investigate" :key="index">
        <div class="problem">
          <el-icon v-if="item.is_must == '0'" color="red"><StarFilled /></el-icon>
          <span style="margin: 0 0 0 10px" v-if="item.is_must == '0'">{{ item.problem }}</span>
          <span style="margin: 0 0 0 10px" v-else>{{ item.problem }}</span>
        </div>
        <div class="type" v-if="item.type == '0'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-radio-group v-model="item.reply">
            <el-radio v-for="(i, radio) in item.answer" :key="radio" :value="i.text">{{ i.text }}</el-radio>
          </el-radio-group>
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '1'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-checkbox-group v-model="checkbox" @change="checkChange($event, item)">
            <el-checkbox v-for="(i, checkbox) in item.answer" :key="checkbox" :label="i.text" :value="i.text">
              {{ i.text }}
            </el-checkbox>
          </el-checkbox-group>
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '2'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-select v-model="item.reply" placeholder="请选择" size="large" style="width: 100%">
            <el-option v-for="(i, select) in item.answer" :key="select" :label="i.text" :value="i.text" />
          </el-select>
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '3'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-input size="large" v-model="item.reply" type="number" :placeholder="getField(item.problem)" />
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '4'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-input size="large" v-model="item.reply" :placeholder="getField(item.problem)" />
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '5'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <el-input v-model="item.reply" type="textarea" :placeholder="getField(item.problem)" />
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '6'">
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
          <custom-upload model="reply" :list="file" accept="*" :limit="10" url="/files/web/cxyy_match/upload" @change="onUpload($event, item)"></custom-upload>
          <div v-if="errors[item.problem]" class="error-message">{{ errors[item.problem] }}</div>
        </div>
        <div class="type" v-if="item.type == '7'">
          <div class="list">
            <div v-for="(aa, ina) in item.answer" :key="ina" class="name">{{ aa.text }}</div>
          </div>
          <div class="list" v-for="(gg, inx) in item.reply" :key="inx">
            <div v-for="(aa, ina) in item.answer" :key="ina" class="input">
              <el-input size="large" v-model="gg[aa.text]" :placeholder="getField(item.problem)" />
            </div>
            <el-icon class="icon" size="25" @click="toDel(item, gg.sid)"><Close /></el-icon>
          </div>
          <div class="add" @click="toAdd(item)">+新增一行</div>
        </div>
        <div class="type" v-if="item.type == '8'">
          <div v-for="(as, img) in item.answer" :key="img">
            <el-link :href="getUrl(as)" target="_blank">{{ as.name }}</el-link>
          </div>
          <div class="remark" v-if="item.remark">{{ item.remark }}</div>
        </div>
      </div>
      <div class="button">
        <el-button type="primary" @click="toBack()">返回上一页</el-button>
        <el-button type="primary" @click="toSave()">保存</el-button>
      </div>
    </el-col>
  </custom-layout>
</template>

<script setup>
import moment from 'moment'
import { get } from 'lodash-es'
// 接口
import { MatchStore } from '@/store/api/platform/match'
const store = MatchStore()
import { MatchRegStore } from '@/store/api/platform/matchReg'
const matchRegStore = MatchRegStore()
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
// 加载中
const loading = ref(false)
// 路由
const route = useRoute()
const info = ref({})
const investigate = ref([])
const file = ref([])
const form = ref({ gender: '0', role: ['User'] })
const checkbox = ref([])
// 表单验证
const ruleFormRef = 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 passwordValValidate = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入密码'))
  } else if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[._~!@#$^&*])[A-Za-z0-9._~!@#$^&*]{8,16}$/g.test(value)) {
    return callback()
  } else {
    return callback(new Error('请输入包含英文字母大小写、数字和特殊符号的 8-16 位组合'))
  }
}
const rules = reactive({
  nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  phone: [{ required: true, validator: validatePhoneNumber, trigger: 'blur' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, validator: passwordValValidate, trigger: 'blur' }],
  email: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }],
  checkCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

// 错误信息
const errors = ref({})
// 请求
onMounted(async () => {
  loading.value = true
  await search()
  loading.value = false
})
const search = async () => {
  let id = route.query.id
  if (id) {
    let res = await store.fetch(id)
    if (res.errcode == '0') {
      info.value = res.data
      if (res.data.ext_info && res.data.ext_info.length > 0) investigate.value = res.data.ext_info
    }
  }
}
const getField = (data) => {
  let res = '请输入内容'
  if (data) res = `请输入${data}`
  return res
}
// 图片处理
const getUrl = (e) => {
  if (e) return `${import.meta.env.VITE_APP_HOST}${get(e, 'uri')}`
}
// 上传图片
const onUpload = (e, item) => {
  const { value } = e
  for (let val of investigate.value) {
    if (val.sid == item.sid) val.reply = value
  }
}
// 新增一行
const toAdd = (item) => {
  for (let val of investigate.value) {
    if (val.sid == item.sid) {
      let answer = []
      let obj = {
        sid: moment().valueOf()
      }
      for (let s of val.answer) {
        obj[s.text] = ''
      }
      answer.push(obj)
      if (val.reply) val.reply = [...val.reply, ...answer]
      else val.reply = answer
    }
  }
}
// 删除一行
const toDel = (item, sid) => {
  if (item && item.reply && item.reply.length > 0) {
    let answer = item.reply.filter((i) => i.sid != sid)
    for (let val of investigate.value) {
      if (val.sid == item.sid) {
        val.reply = answer
      }
    }
  }
}
const checkChange = (data, item) => {
  for (let val of investigate.value) {
    if (val.sid == item.sid) {
      val.reply = data
    }
  }
}
// 自定义的验证函数
const validateObject = async (arr) => {
  const errors = {}
  for (const obj of arr) {
    if (obj.is_must == '0') {
      if (!obj.reply || obj.reply.length == 0) {
        if (obj.type == '0' || obj.type == '1' || obj.type == '1') errors[obj.problem] = `请选择${obj.problem}`
        else if (obj.type == '6') errors[obj.problem] = `请上传${obj.problem}`
        else errors[obj.problem] = `请填写${obj.problem}`
      }
    }
  }
  // 如果有错误，返回错误对象
  if (Object.keys(errors).length > 0) {
    return errors
  }
  // 如果没有错误，返回null或undefined
  return null
}
const toSave = async () => {
  const errorsInfo = await validateObject(investigate.value)
  // 检查是否有错误
  if (errorsInfo) {
    errors.value = errorsInfo
    console.log(errorsInfo)
  } else {
    errors.value = {}
    const data = { match_id: info.value.id, info: investigate.value }
    if (user.value.id) {
      data.user_id = user.value.id
      const res = await matchRegStore.create(data)
      if (res.errcode == '0') {
        ElMessageBox.alert('请在 个人中心-活动管理-大赛报名 中查看报名信息', '报名信息', {
          confirmButtonText: '确定',
          callback: () => {
            toBack()
          }
        })
      } else ElMessage({ message: res.errmsg, type: 'error' })
    } else {
      if (!ruleFormRef.value) return
      await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          form.value.nick_name = form.value.account
          data.user = form.value
          const res = await matchRegStore.create(data)
          if (res.errcode == '0') {
            ElMessageBox.alert('请在 个人中心-活动管理-大赛报名 中查看报名信息', '报名信息', {
              confirmButtonText: '确定',
              callback: () => {
                toBack()
              }
            })
          } else ElMessage({ message: res.errmsg, type: 'error' })
        }
      })
    }
  }
}
// 返回上一页
const toBack = () => {
  window.history.go(-1)
}
</script>
<style scoped lang="scss">
.main {
  .one {
    .text {
      margin: 0 0 10px 0;
      color: #000;
      display: inline-block;
      padding-bottom: 20px;
      font-size: 30px;
      border-bottom: 5px solid #378cff;
      cursor: pointer;
    }
    .list {
      .problem {
        display: flex;
        align-items: center;
        font-size: 20px;
        margin: 10px 0;
      }

      .type {
        padding: 0 0 10px 15px;

        .list {
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 10px 0;

          .name {
            width: 50%;
            text-align: center;
          }

          .input {
            width: 50%;
            margin: 0 5px 0 0;

            .name {
              width: 50%;
              text-align: center;
              margin: 0 0 10px 0;
            }
          }

          .icon {
            display: none;
            margin: 5px 0 0 0;
          }
        }

        .list:hover {
          .icon {
            display: block;
          }
        }

        .add {
          border: 1px solid #e5e5e5;
          border-radius: 5px;
          text-align: center;
          padding: 10px;
          cursor: pointer;
        }

        .image {
          width: 100%;
        }
        .error-message {
          margin: 10px 0 0 10px;
          font-size: 14px;
          color: red;
        }
        .remark {
          margin: 10px 0 10px 20px;
          font-size: 14px;
          color: red;
        }
      }
    }

    .button {
      margin: 10px 0;
      padding: 10px;
      text-align: center;

      button {
        padding: 20px 0;
        width: 240px;
        background-color: #007aff;
      }
    }
  }
}
</style>
