<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" :title="dialogTitle"
    width="760px" destroy-on-close append-to-body class="add-customer-dialog">
    <div class="dialog-body">
      <!-- 头像区 -->
      <div class="avatar-section">
        <el-upload action="#" :show-file-list="false" :auto-upload="false" :on-change="handleUploadFile">
          <el-avatar :size="80"
            :src="avatarDisplayUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            class="avatar-preview" />
          <div class="avatar-tip">点击修改头像</div>
        </el-upload>
      </div>

      <el-form :model="form" label-position="top" class="customer-form">
        <!-- 基本资料 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">基本资料</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属站点" required>
              <el-cascader v-model="formAreaValue" :options="areaTreeOptions"
                :props="{ value: 'value', label: 'label' }" placeholder="请选择站点" style="width: 100%" clearable
                @change="handleFormAreaChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" required><el-input v-model="form.name" placeholder="请输入" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电话" required><el-input v-model="form.phone" placeholder="请输入" /></el-form-item>
          </el-col>
          <el-col :span="8">
            <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-row>

        <!-- 居住信息 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">居住信息</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在地区">
              <RegionCascader v-model="regionCascaderValue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细住址" required>
              <el-input v-model="form.address" placeholder="请输入街道/门牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房屋类型">
              <el-select v-model="form.houseType" placeholder="请选择">
                <el-option v-for="dict in sys_house_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入门方式">
              <el-select v-model="form.entryMethod" placeholder="请选择">
                <el-option v-for="dict in sys_entry_method" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" 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="8" v-if="form.entryMethod === 'key'">
            <el-form-item label="钥匙位置" required>
              <el-input v-model="form.keyLocation" placeholder="如：地毯下" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 其他 -->
        <div class="section-heading">
          <span class="section-line"></span>
          <span class="section-text">其他信息</span>
          <span class="section-line"></span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户标签">
              <el-select v-model="selectedTagIds" multiple placeholder="选择标签" collapse-tags collapse-tags-tooltip>
                <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="12">
            <el-form-item label="备注说明">
              <el-input type="textarea" v-model="form.remark" :rows="2" placeholder="备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)" size="large">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="saveUser" size="large">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

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

const props = defineProps({
  visible: { type: Boolean, default: false },
  editData: { type: Object, default: null },
  orderMode: { type: Boolean, default: false },
  tenantId: { type: [String, Number], default: undefined },
  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 userStore = useUserStore()
const { loadRegionData } = useRegionData()

const submitLoading = ref(false)
const avatarDisplayUrl = ref('')
const selectedTagIds = ref([])
const allUserTags = ref([])
const allNodes = ref([])
const formAreaValue = ref([])
const regionCascaderValue = ref([])

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

const form = reactive({
  id: undefined, name: '', phone: '', avatar: undefined, gender: undefined,
  areaId: undefined, stationId: undefined, regionCode: '', address: '',
  houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
  tenantId: undefined, remark: '', tagIds: []
})

const areaTreeOptions = computed(() => {
  const buildTree = (data, parentId) =>
    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
    })
  return buildTree(allNodes.value, 0)
})

const dialogTitle = computed(() => props.editData ? '编辑用户' : '新增用户')

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

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 }
}

const handleUploadFile = async (file) => {
  const fd = new FormData(); fd.append('file', file.raw)
  try {
    const headers = globalHeaders()
    const res = await fetch(uploadUrl, { method: 'POST', headers: { 'Authorization': headers.Authorization, 'clientid': headers.clientid }, body: fd })
    const result = await res.json()
    if (result.code === 200) { form.avatar = result.data.ossId; avatarDisplayUrl.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 === 'password' && !form.entryPassword) return ElMessage.warning('请输入开门密码')
  if (form.entryMethod === 'key' && !form.keyLocation) return ElMessage.warning('请输入钥匙存放位置')
  submitLoading.value = true
  form.tagIds = selectedTagIds.value
  form.regionCode = (regionCascaderValue.value && regionCascaderValue.value.length > 0) ? regionCascaderValue.value.join('/') : ''
  if (props.orderMode) { form.tenantId = props.tenantId; form.stationId = props.stationId }
  else { form.tenantId = userStore.tenantId }
  const api = form.id ? updateCustomer(form) : addCustomer(form)
  api.then((res) => { ElMessage.success('保存成功'); emit('update:visible', false); emit('success', res.data) })
    .finally(() => { submitLoading.value = false })
}

const initForm = () => {
  selectedTagIds.value = []
  Object.assign(form, {
    id: undefined, name: '', phone: '', avatar: undefined, gender: undefined,
    areaId: undefined, stationId: undefined, regionCode: '', address: '',
    houseType: '', entryMethod: '', entryPassword: '', keyLocation: '',
    tenantId: props.orderMode ? props.tenantId : userStore.tenantId,
    remark: '', tagIds: []
  })
  avatarDisplayUrl.value = ''
  formAreaValue.value = []
  regionCascaderValue.value = []
}

const loadEditData = (data) => {
  Object.assign(form, {
    id: data.id, name: data.name, phone: data.phone, avatar: data.avatar,
    gender: data.gender, areaId: data.areaId, stationId: data.stationId,
    regionCode: data.regionCode || '', address: data.address,
    houseType: data.houseType, entryMethod: data.entryMethod,
    entryPassword: data.entryPassword, keyLocation: data.keyLocation,
    tenantId: props.orderMode ? props.tenantId : data.tenantId || userStore.tenantId,
    remark: data.remark || '', tagIds: []
  })
  avatarDisplayUrl.value = data.avatarUrl || ''
  regionCascaderValue.value = data.regionCode ? data.regionCode.split('/') : []
  selectedTagIds.value = data.tags ? data.tags.map(t => t.id) : []
  const targetId = data.stationId || data.areaId
  if (targetId) {
    const findPath = (nodes, targetId, path = []) => {
      for (const node of nodes) {
        const currentPath = [...path, node.id]
        if (String(node.id) === String(targetId)) return currentPath
        const children = allNodes.value.filter(n => String(n.parentId) === String(node.id))
        if (children.length > 0) { const result = findPath(children, targetId, currentPath); if (result) return result }
      }
      return null
    }
    formAreaValue.value = findPath(allNodes.value.filter(n => String(n.parentId) === '0'), targetId) || []
  } else { formAreaValue.value = [] }
}

watch(() => props.visible, (val) => { if (val) { props.editData ? loadEditData(props.editData) : initForm() } })

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

<style scoped>
.add-customer-dialog :deep(.el-dialog__body) {
  padding: 0 36px 0;
  max-height: 62vh;
  overflow-y: auto;
}

.dialog-body {
  padding-top: 12px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.avatar-preview {
  box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
  border: 3px solid #fff;
  outline: 1px solid #e8e8e8;
  cursor: pointer;
}

.avatar-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #409eff;
  text-align: center;
}

.customer-form {
  padding-bottom: 12px;
}

.section-heading {
  display: flex;
  align-items: center;
  margin: 32px 0 20px;
}

.section-heading:first-of-type {
  margin-top: 0;
}

.section-line {
  flex: 1;
  height: 1px;
  background: #e8e8e8;
}

.section-text {
  padding: 0 20px;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 12px;
}
</style>
