<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="main animate__animated animate__backInRight" v-loading="loading">
        <div class="w_1200 one">
          <el-tabs v-model="activeName" type="card" class="tabs">
            <el-tab-pane label="个人中心" name="first">
              <el-col :span="24" class="one_1"> 基本信息</el-col>
              <el-col :span="24" class="one_2">
                <el-form
                  label-position="top"
                  ref="ruleFormRef"
                  :model="form"
                  :rules="rules"
                  label-width="80px"
                  class="form"
                >
                  <el-form-item label="账号" prop="account">
                    <el-input 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="nick_name">
                    <el-input 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 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 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 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-row v-if="form.role_type != 'User'">
                <el-col :span="24" class="one_1">
                  基本资料
                  <span>(注意：如需修改信息需要重新审核才可显示!)</span>
                </el-col>
                <el-col :span="24" class="one_2">
                  <expert v-if="form.role_type == 'Expert'"></expert>
                  <company v-if="form.role_type == 'Company'"></company>
                  <incubator v-if="form.role_type == 'Incubator'"></incubator>
                  <competition v-if="form.role_type == 'Competition'"></competition>
                  <investment v-if="form.role_type == 'Investment'"></investment>
                  <association v-if="form.role_type == 'Association'"></association>
                  <state v-if="form.role_type == 'State'"></state>
                  <unit v-if="form.role_type == 'Unit'"></unit>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="second">
              <el-col :span="24" class="one_2">
                <el-form
                  label-position="top"
                  ref="secondRule"
                  :model="secondForm"
                  :rules="secondRules"
                  label-width="80px"
                  class="form"
                >
                  <el-form-item label="新密码" prop="password">
                    <el-input
                      v-model="secondForm.password"
                      type="password"
                      show-password
                      placeholder="请输入新密码"
                    >
                      <template #prefix>
                        <el-icon>
                          <Unlock />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="refpassword">
                    <el-input
                      v-model="secondForm.refpassword"
                      type="password"
                      show-password
                      placeholder="请再次确认输入密码"
                    >
                      <template #prefix>
                        <el-icon>
                          <Unlock />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-col :span="24" class="button">
                    <el-button type="primary" @click="submit(secondRule)">修改密码</el-button>
                  </el-col>
                </el-form>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
// API 引用
import { getCity } from '@/utils/city'
import { cloneDeep } from 'lodash-es'
// 组件
import association from './parts/association.vue'
import company from './parts/company.vue'
import competition from './parts/competition.vue'
import expert from './parts/expert.vue'
import incubator from './parts/incubator.vue'
import state from './parts/state.vue'
import unit from './parts/unit.vue'
import investment from './parts/investment.vue'
// 接口
import { UserStore } from '@/store/user'
const userStore = UserStore()
const user = computed(() => userStore.user)
const router = useRouter()
import { UsersStore } from '@/store/api/user/user'
const store = UsersStore()
import { DictDataStore } from '@/store/api/system/dictData'
import { LoginStore } from '@/store/api/login'
const loginStore = LoginStore()
const dictDataStore = DictDataStore()
const $checkRes = inject('$checkRes')
// 加载中
const loading = ref(false)
const activeName = ref('first')
const form = 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 validatePassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入确认密码'))
  }
  if (secondForm.value.password !== value) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    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' }]
})
const secondRule = ref()
const secondForm = ref({})
const secondRules = reactive({
  password: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  refpassword: [{ required: true, validator: validatePassword, trigger: 'blur' }]
})
// 字典
const typeList = ref([])
const genderList = ref([])
const fieldList = ref([])
const educationList = ref([])
const cityList = ref([])
const isUseList = ref([])
const patternList = ref([])
const scaleList = ref([])
const IndustryList = ref([])
const cardTypeList = ref([])
const contributionList = ref([])
// 请求
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') form.value = res.data
  }
}
const searchOther = async () => {
  let result
  // 性别
  result = await dictDataStore.query({ code: 'gender', is_use: '0' })
  if ($checkRes(result)) genderList.value = result.data
  // 用户类型
  result = await dictDataStore.query({ code: 'userType', is_use: '0' })
  if ($checkRes(result)) typeList.value = result.data
  // 专家领域
  result = await dictDataStore.query({ code: 'field', is_use: '0' })
  if ($checkRes(result)) fieldList.value = result.data
  // 企业类型
  result = await dictDataStore.query({ code: 'companyType', is_use: '0' })
  if ($checkRes(result)) patternList.value = result.data
  // 企业规模
  result = await dictDataStore.query({ code: 'companyScale', is_use: '0' })
  if ($checkRes(result)) scaleList.value = result.data
  // 企业所属行业
  result = await dictDataStore.query({ code: 'companyIndustry', is_use: '0' })
  if ($checkRes(result)) IndustryList.value = result.data
  // 学历
  result = await dictDataStore.query({ code: 'education', is_use: '0' })
  if ($checkRes(result)) educationList.value = result.data
  // 证件类型
  result = await dictDataStore.query({ code: 'cardType', is_use: '0' })
  if ($checkRes(result)) cardTypeList.value = result.data
  // 出资方式
  result = await dictDataStore.query({ code: 'contribution', is_use: '0' })
  if ($checkRes(result)) contributionList.value = result.data
  // 是否使用
  result = await dictDataStore.query({ code: 'isUse', is_use: '0' })
  if ($checkRes(result)) isUseList.value = result.data
  // 城市
  getCity().then((response) => (cityList.value = response.address))
}
// 保存
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = cloneDeep(form.value)
      if (data.role_type) delete data.role_type
      const res = await store.update(data)
      if ($checkRes(res, true)) search()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 修改密码
const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = cloneDeep(secondForm.value)
      const res = await loginStore.rp({
        type: 'User',
        _id: user.value._id,
        password: data.password
      })
      if ($checkRes(res, true)) {
        userStore.logOut()
        router.push('/login')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// provide
provide('cloneDeep', cloneDeep)
provide('ruleFormRef ', ruleFormRef)
// 字典
provide('genderList', genderList)
provide('fieldList', fieldList)
provide('educationList', educationList)
provide('cityList', cityList)
provide('isUseList', isUseList)
provide('patternList', patternList)
provide('scaleList', scaleList)
provide('IndustryList', IndustryList)
provide('cardTypeList', cardTypeList)
provide('contributionList', contributionList)
</script>
<style scoped lang="scss">
.main {
  background-color: #f1f2f5;
  padding: 20px;
  .one {
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    .one_1 {
      line-height: 20px;
      font-size: 16px;
      font-weight: 500;
      border-bottom: 1px solid #f9f9f9;
      padding: 10px 0;
      span {
        color: red;
        font-size: 12px;
      }
    }
    .one_2 {
      padding: 10px;
    }
    .button {
      text-align: center;
    }
  }
}
</style>
