<template>
  <div class="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <div class="thr" v-if="companyInfo && companyInfo.id">
          <el-button class="button" size="large" @click="toJoin" type="primary">入驻孵化器</el-button>
        </div>
        <el-col :span="24" class="one">基本信息 </el-col>
        <el-col :span="24" class="two">
          <el-form label-position="top" ref="ruleFormRef" :model="form" :rules="rules" label-width="80px" class="form">
            <el-form-item label="账号" prop="account">
              <el-input size="large" clearable disabled v-model="form.account" placeholder="请输入账号">
                <template #prefix>
                  <el-icon>
                    <User />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="板块选择" prop="industry">
              <el-checkbox-group v-model="form.industry">
                <el-checkbox v-for="(item, index) in plateList" :key="index" :value="item.title">{{ item.title }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="昵称" prop="nick_name">
              <el-input size="large" clearable v-model="form.nick_name" placeholder="请输入昵称">
                <template #prefix>
                  <el-icon>
                    <Avatar />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select size="large" v-model="form.gender" width="100%" placeholder="请选择性别">
                <el-option v-for="(item, index) in genderList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </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="email">
              <el-input size="large" clearable v-model="form.email" placeholder="请填入正确的电子邮箱">
                <template #prefix>
                  <el-icon>
                    <Message />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-col :span="24" class="button">
              <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
            </el-col>
          </el-form>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog v-model="dialog.show" :title="dialog.title" :destroy-on-close="false" @close="toClose">
      <el-row>
        <el-col :span="24" v-if="dialog.type == '1'" class="dialog_one">
          <el-select size="large" style="width: 350px" clearable v-model="incubator_id" filterable remote reserve-keyword placeholder="请输入想要选择的孵化器" :remote-method="remoteMethod" :loading="searchLoading">
            <el-option v-for="item in searchList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button class="button" size="large" @click="toSave" type="primary">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import moment from 'moment'
import { cloneDeep, get } from 'lodash-es'
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
import { UsersStore } from '@/store/api/user/user'
import { DictDataStore } from '@/store/api/system/dictData'
import { SectorStore } from '@/store/api/platform/sector'
// 接口
import { CompanyStore } from '@/store/api/user/company'
import { CirelationStore } from '@/store/api/user/cirelation'
import { IncubatorStore } from '@/store/api/user/incubator'
const incubatorStore = IncubatorStore()
const companystore = CompanyStore()
const cirelationStore = CirelationStore()
const store = UsersStore()
const dictDataStore = DictDataStore()
const sectorStore = SectorStore()
const $checkRes = inject('$checkRes')
const form = ref({ industry: [] })

// 加载中
const searchLoading = ref(false)
const searchList = ref([])
const incubator_id = ref('')
const companyInfo = 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 rules = reactive({
  nick_name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  phone: [{ required: true, validator: validatePhoneNumber, trigger: 'blur' }],
  email: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  industry: [{ required: true, message: '请选择板块', trigger: 'blur' }]
})
// 加载中
const loading = ref(false)
// 字典
const genderList = ref([])
const plateList = ref([])
const dialog = ref({ type: '1', show: false, title: '入驻孵化器' })
// 请求
onMounted(async () => {
  loading.value = true
  await searchOther()
  await search()
  loading.value = false
})
const search = async () => {
  if (user.value.id) {
    let res = await store.detail(user.value.id)
    if (res.errcode == '0') {
      const data = get(res, 'data')
      if (!get(data, 'industry')) data.industry = []
      else {
        if (!Array.isArray(data.industry)) data.industry = [data.industry]
      }
      userStore.setUser(data)
      form.value = data || { industry: [] }
    }
  }
}
const searchOther = async () => {
  let result
  // 性别
  result = await dictDataStore.query({ code: 'gender', is_use: '0' })
  if ($checkRes(result)) genderList.value = result.data
  // 板块
  result = await sectorStore.query({ is_use: '0' })

  if ($checkRes(result)) plateList.value = result.data
  if (user.value.id) {
    let res = await companystore.query({ user: user.value.id, status: '1' })
    if (res.errcode == '0') {
      if (res.data[0] && !res.data[0].logo) res.data[0].logo = []
      companyInfo.value = res.data[0] || { logo: [] }
    }
  }
}
// 保存
const submitForm = async (ruleFormRef) => {
  if (!ruleFormRef) return
  await ruleFormRef.validate(async (valid, fields) => {
    if (valid) {
      const data = cloneDeep(form.value)
      const res = await store.update(data)
      if ($checkRes(res, true)) search()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const remoteMethod = (query) => {
  if (query) {
    searchLoading.value = true
    setTimeout(async () => {
      searchLoading.value = false
      const info = { status: '1', name: query }
      const res = await incubatorStore.query(info)
      if (res.errcode == '0') searchList.value = res.data
    }, 200)
  } else {
    searchList.value = []
  }
}
const toSave = () => {
  ElMessageBox.confirm(`您确认选择该数据?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      const data = {
        user: user.value.id,
        incubator: incubator_id.value,
        company: companyInfo.value.id,
        time: moment().format('YYYY-MM-DD'),
        status: '0'
      }
      const res = await cirelationStore.create(data)
      if ($checkRes(res, true)) ElMessage({ message: `申请进入孵化器成功等待审核`, type: 'success' })
      incubator_id.value = ''
    })
    .catch(() => {})
}
// 入驻孵化器
const toJoin = () => {
  dialog.value = { type: '1', show: true, title: '入驻孵化器' }
}
</script>
<style scoped lang="scss">
.main {
  .one {
    font-size: $global-font-size-20;
    font-weight: 700;
    margin: 0 0 20px 0;
  }
  .two {
    .button {
      margin: 10px 0 0 0;
      text-align: center;
    }
  }
  .thr {
    margin: 10px 0;
  }
}
.dialog_one {
  display: flex;
  align-items: center;
  margin: 0 0 10px 0;
  .button {
    margin: 0 0 0 5px;
  }
}
</style>
