<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getMemberConnectionsList, getMemberFieldsList, createMember, updateMember } from '../api'
import type { ConnectionsProp, MemberFieldsProp, MemberProp } from '../types'
import { useMapStore } from '@/stores/map'

const store = useMapStore()

const ruleFormRef = ref<FormInstance>()

onMounted(() => {
  getConnectionsList()
  getFieldsList()
})

// 链接列表（所属链接选项）
let connectionOptions = $ref<ConnectionsProp[]>()
const getConnectionsList = function () {
  getMemberConnectionsList().then((res: { data: ConnectionsProp[] }) => {
    connectionOptions = res.data
  })
}

// 用户属性
let fieldsList = $ref<MemberFieldsProp[]>([])
const getFieldsList = function () {
  getMemberFieldsList().then((res: { data: MemberFieldsProp[] }) => {
    fieldsList = res.data.map((item: any) => {
      item.value = ''
      if (props.data) {
        item.value = props.data?.fields[item.id]
      }
      return item
    })
  })
}
interface Props {
  data?: MemberProp
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const form = $ref(
  props.data || {
    name: '',
    status: '1',
    experiment_connection_id: '',
    gender: '',
    mobile: ''
  }
)

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入' }],
  status: [{ required: true, message: '请选择' }],
  experiment_connection_id: [{ required: true, message: '请选择' }],
  gender: [{ required: true, message: '请选择' }],
  mobile: [{ required: true, message: '请输入' }]
})

// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  const fields = fieldsList.reduce((a: any, b: { id: string; value: string }) => {
    a[b.id] = b.value
    return a
  }, {})
  const params = { ...form, fields: fields }
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      if (props.data?.id) {
        updateMember(params).then(() => {
          emit('update')
          emit('update:modelValue', false)
          ElMessage({ message: '更新成功', type: 'success' })
        })
      } else {
        createMember(params)
          .then(() => {
            emit('update')
            emit('update:modelValue', false)
            ElMessage({ message: '添加成功', type: 'success' })
          })
          .catch((res: any) => {
            ElMessage.closeAll()
            ElMessage.error(fieldsList.find((item: any) => item.id === res.data.error_field)?.name + res.message)
          })
      }
    } else {
      console.log('error submit!')
    }
  })
}
</script>

<template>
  <el-dialog
    class="connect-form"
    :title="props.data ? (props.data?.isView ? '查看用户' : '编辑用户') : '新建用户'"
    :close-on-click-modal="false"
    width="800px"
    @closed="$emit('update:modelValue', false)">
    <el-form
      :disabled="props.data?.isView"
      ref="ruleFormRef"
      style="width: 400px; margin: 0 auto; padding: 0 30px 30px 0"
      :model="form"
      :rules="rules"
      label-suffix="："
      label-width="auto">
      <el-form-item label="来源链接" prop="experiment_connection_id">
        <el-select v-model="form.experiment_connection_id" style="width: 100%">
          <el-option
            v-for="item in connectionOptions"
            :key="item.id"
            :label="item?.type_name"
            :value="item?.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" style="width: 100%"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-text="生效" active-value="1" inactive-text="失效" inactive-value="0" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" style="width: 100%">
          <el-option
            v-for="item in store.getMapValuesByKey('system_gender')"
            :key="item.id"
            :label="item?.label"
            :value="item?.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="form.mobile" style="width: 100%"></el-input>
      </el-form-item>
      <el-form-item :label="item.name" v-for="item in fieldsList" :key="item.id">
        <template v-if="item.type === '4' || item.type === '5'">
          <el-date-picker
            v-if="item.format === 'yyyy-mm-dd'"
            v-model="item.value"
            type="date"
            placeholder="请选择"
            style="width: 100%"
            value-format="YYYY-MM-DD" />
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-else
            v-model="item.value"
            type="datetime"
            placeholder="请选择"
            style="width: 100%" />
        </template>
        <el-input v-else v-model="item.value" style="width: 100%" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: center">
      <el-button v-if="!props.data?.isView" type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
    </div>
  </el-dialog>
</template>
<style lang="scss">
.btn-box {
  text-align: center;
  margin-bottom: 20px;
}
</style>
