<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" title="新增用户" width="700px"
    destroy-on-close append-to-body>
    <el-form :model="form" label-width="90px" class="user-form">
      <el-row :gutter="20">
        <el-col :span="24" style="text-align: center; margin-bottom: 25px;">
          <el-upload action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUserUploadFile">
            <el-avatar :size="80"
              :src="userAvatarDisplayUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              class="upload-avatar" />
            <div style="margin-top: 8px; font-size: 12px; color: #409EFF;">点击修改头像</div>
          </el-upload>
        </el-col>

        <el-col :span="24">
          <div class="form-section-header">基本资料</div>
        </el-col>
        <!-- 录入来源不在表单中展示，自动使用当前登录用户的 tenantId，提交时静默传递 -->
        <el-col :span="24">
          <el-form-item label="所属站点" required>
            <el-cascader v-model="formAreaValue" :options="areaTreeOptions" placeholder="请选择站点"
              :props="{ checkStrictly: true, value: 'value', label: 'label' }" style="width: 100%" clearable
              @change="handleFormAreaChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" required><el-input v-model="form.name" placeholder="请输入姓名" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" required><el-input v-model="form.phone" placeholder="请输入电话" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select v-model="form.gender" placeholder="请选择">
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <div class="form-section-header">居住信息</div>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所在地区">
            <RegionCascader v-model="regionCascaderValue" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详细住址" required><el-input v-model="form.address" placeholder="请输入街道/门牌号" /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房屋类型">
            <el-radio-group v-model="form.houseType">
              <el-radio v-for="dict in sys_house_type" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入门方式" required>
            <el-radio-group v-model="form.entryMethod">
              <el-radio v-for="dict in sys_entry_method" :key="dict.value" :value="dict.value">{{ dict.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.entryMethod === 'password'">
          <el-form-item label="开门密码" required>
            <el-input v-model="form.entryPassword" placeholder="请输入密码" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.entryMethod === 'key'">
          <el-form-item label="钥匙位置" required>
            <el-input v-model="form.keyLocation" placeholder="如：地毯下" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <div class="form-section-header">其他</div>
        </el-col>
        <el-col :span="24">
          <el-form-item label="用户标签">
            <el-select v-model="selectedTagIds" multiple placeholder="选择标签" style="width: 100%">
              <el-option v-for="tag in allUserTags" :key="tag.id" :label="tag.name" :value="tag.id">
                <el-tag :type="tag.colorType || 'info'" effect="light" size="small">{{ tag.name }}</el-tag>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注说明"><el-input type="textarea" v-model="form.remark" rows="3" /></el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="text-align: center; margin-top: 20px;">
        <el-button @click="$emit('update:visible', false)" size="large" style="width: 120px;">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="saveUser" size="large"
          style="width: 120px;">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, getCurrentInstance, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { globalHeaders } from '@/utils/request'
import { addCustomerOnOrder } from '@/api/archieves/customer'
import { listAllTag } from '@/api/archieves/tag'
import { listAreaStation } from '@/api/system/areaStation'
import RegionCascader from '@/components/RegionCascader/index.vue'
import PageSelect from '@/components/PageSelect/index.vue'
import { useUserStore } from '@/store/modules/user'

const props = defineProps({
  visible: { type: Boolean, default: false },
  stationId: { type: [String, Number], default: undefined }
})

const emit = defineEmits(['update:visible', 'success'])

const { proxy } = getCurrentInstance()
const { sys_user_sex, sys_house_type, sys_entry_method } = toRefs(
  proxy?.useDict('sys_user_sex', 'sys_house_type', 'sys_entry_method')
)

const submitLoading = ref(false)

// 获取当前登录用户的 tenantId
const userStore = useUserStore()

const allNodes = ref([])
const allUserTags = ref([])

const formAreaValue = ref([])
const regionCascaderValue = ref([])
const selectedTagIds = ref([])
const userAvatarDisplayUrl = ref('')

const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadUrl = baseUrl + '/resource/oss/upload'

const form = reactive({
  name: '',
  phone: '',
  avatar: undefined,
  gender: undefined,
  birthday: '',
  idCard: '',
  areaId: undefined,
  stationId: undefined,
  regionCode: '',
  region: [],
  address: '',
  houseType: '',
  entryMethod: '',
  entryPassword: '',
  keyLocation: '',
  // 录入来源默认为当前登录用户的 tenantId
  tenantId: userStore.tenantId,
  emergencyContact: '',
  emergencyPhone: '',
  memberLevel: 0,
  status: 0,
  remark: '',
  tagIds: []
})

watch(() => props.visible, (val) => {
  if (val) {
    resetForm()
  }
})

const resetForm = () => {
  submitLoading.value = false
  selectedTagIds.value = []
  userAvatarDisplayUrl.value = ''
  formAreaValue.value = []
  regionCascaderValue.value = []
  Object.assign(form, {
    name: '', phone: '', avatar: undefined, gender: undefined, birthday: '', idCard: '',
    areaId: undefined, stationId: undefined, regionCode: '', region: [], address: '',
    houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
    // 重置时依然保留当前 tenantId 作为录入来源
    tenantId: userStore.tenantId,
    emergencyContact: '', emergencyPhone: '', memberLevel: 0, status: 0, remark: '', tagIds: []
  })
  // 根据门店站点自动选中所属站点
  if (props.stationId && allNodes.value.length > 0) {
    const path = getStationPath(props.stationId)
    if (path.length > 0) {
      formAreaValue.value = path
      handleFormAreaChange(path)
    }
  }
}

// 根据站点ID获取级联路径
const getStationPath = (id) => {
  if (!id) return []
  const path = []
  let currentId = String(id)
  let maxDepth = 10
  while (currentId && maxDepth-- > 0) {
    const node = allNodes.value.find(n => String(n.id) === currentId)
    if (!node) break
    path.unshift(node.id)
    currentId = node.parentId != null ? String(node.parentId) : null
  }
  return path
}

const areaTreeOptions = computed(() => {
  const buildTree = (data, parentId) => {
    return data
      .filter(item => String(item.parentId) === String(parentId))
      .map(item => {
        const children = buildTree(data, item.id)
        const node = { value: item.id, label: item.name }
        if (children.length > 0) node.children = children
        return node
      })
  }
  const areaData = allNodes.value
  return buildTree(areaData, 0)
})

const handleFormAreaChange = (value) => {
  if (value && value.length > 0) {
    const lastId = value[value.length - 1]
    const node = allNodes.value.find(n => String(n.id) === String(lastId))
    if (node) {
      if (String(node.type) === '2') {
        form.stationId = lastId
        form.areaId = node.parentId
      } else {
        form.areaId = lastId
        form.stationId = undefined
      }
    }
  } else {
    form.areaId = undefined
    form.stationId = undefined
  }
}

// 品牌列表相关逻辑已移除，录入来源改为自动使用当前用户 tenantId

const loadTags = () => {
  listAllTag({ category: 'customer', status: 0 }).then((res) => {
    allUserTags.value = res.data || []
  })
}

const loadAreaStation = () => {
  listAreaStation().then((res) => {
    allNodes.value = res.data || []
  })
}

const handleUserUploadFile = async (file) => {
  const formData = new FormData()
  formData.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, {
      method: 'POST',
      headers: {
        'Authorization': headers.Authorization,
        'clientid': headers.clientid
      },
      body: formData
    })
    const result = await res.json()
    if (result.code === 200) {
      form.avatar = result.data.ossId
      userAvatarDisplayUrl.value = result.data.url
    } else {
      ElMessage.error(result.msg || '头像上传失败')
    }
  } catch (e) {
    ElMessage.error('头像上传失败')
  }
}

const saveUser = () => {
  if (!form.name) return ElMessage.warning('请输入姓名')
  if (!form.phone) return ElMessage.warning('请输入电话')
  if (!form.stationId) return ElMessage.warning('所属站点只能选择具体的站点')
  if (!form.address) return ElMessage.warning('请输入详细住址')
  if (!form.entryMethod) return ElMessage.warning('请选择入门方式')
  if (form.entryMethod === 'password' && !form.entryPassword) return ElMessage.warning('请输入开门密码')
  if (form.entryMethod === 'key' && !form.keyLocation) return ElMessage.warning('请输入钥匙存放位置')

  submitLoading.value = true
  form.tagIds = selectedTagIds.value
  if (regionCascaderValue.value && regionCascaderValue.value.length > 0) {
    form.regionCode = regionCascaderValue.value.join('/')
  } else {
    form.regionCode = ''
  }

  addCustomerOnOrder(form).then(res => {
    emit('success', res.data)
    emit('update:visible', false)
  }).finally(() => {
    submitLoading.value = false
  })
}

onMounted(() => {
  loadAreaStation()
  loadTags()
})
</script>

<style scoped>
.form-section-header {
  font-weight: bold;
  margin-bottom: 20px;
  font-size: 15px;
  color: #303133;
}

.upload-avatar {
  cursor: pointer;
  border: 2px solid #e4e7ed;
  transition: border-color 0.2s;
  border-radius: 50%;
}

.upload-avatar:hover {
  border-color: #409EFF;
}
</style>
