<template>
  <div class="background">
    <div class="tree">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="primary" @click="showAddDialog">添加祖辈信息</el-button>
        <el-button type="success" @click="editMember">编辑祖辈信息</el-button>
        <!-- <el-button type="danger" @click="saveTreeData">保存族谱</el-button> -->
      </div>

      <!-- 族谱树图 -->
      <div class="tree-container">
        <TreeChart 
          :json="treeData" 
          :collapse-enabled="true"
          node-text="name"
        >
          <template #node="{ node }">
            <div class="custom-node" :class="{ 'current-user': node.isCurrentUser }">
              <img :size="50" :src="node.image_url" class="node-avatar"/>
              <div class="node-info">
                <span class="name">{{ node.name }}</span>
                <span class="relation">{{ node.relation }}</span>
                <span class="birth-date">{{ node.birthDate }}</span>
                <span class="phone">{{ node.phone }}</span>
              </div>
            </div>
          </template>
        </TreeChart>
      </div>

      <!-- 添加/编辑成员弹窗 -->
      <el-dialog 
        :title="dialogTitle" 
        v-model="dialogVisible" 
        width="500px"
      >
        <el-form :model="currentMember" ref="memberForm" label-width="100px" :rules="rules">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="currentMember.name"></el-input>
          </el-form-item>
          
          <el-form-item label="头像">
            <div class="avatar-uploader">
              <div class="avatar-wrapper">
                <img v-if="currentMember.image_url" :src="currentMember.image_url" class="avatar" >
                <el-icon v-else><Plus /></el-icon>     
                <input
                  type="file"
                  ref="fileInput"
                  @change="handleAvatarChange"
                  accept="image/jpeg,image/png"
                  class="file-input"
                >
              </div>
            </div>
          </el-form-item>

          <el-form-item label="所属分支" prop="parentId">
            <el-select v-model="currentMember.parentId" placeholder="选择所属分支">
              <el-option
                v-for="member in availableParents"
                :key="member.id"
                :label="member.name"
                :value="member.id"
              />
              <!-- <el-option label="新建分支" value="new" /> -->
            </el-select>
          </el-form-item>

          <el-form-item label="关系" prop="relation">
            <el-select v-model="currentMember.relation">
              <el-option label="子女" value="grandparent" />
              <!-- <el-option label="父辈" value="parent" />
              <el-option label="同辈" value="sibling" />
              <el-option label="子辈" value="child" /> -->
            </el-select>
          </el-form-item>

          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="currentMember.birthDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>

          <el-form-item label="联系电话">
            <el-input v-model="currentMember.phone"></el-input>
          </el-form-item>

          <el-form-item label="是否本人">
            <el-switch v-model="currentMember.isCurrentUser" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMember">确定</el-button>
          <el-button 
            v-if="currentMember.id" 
            type="danger" 
            @click="deleteMember"
          >删除</el-button>
        </template>
      </el-dialog>

      <!-- 编辑成员选择弹窗 -->
      <el-dialog
        title="选择要编辑的成员"
        v-model="editDialogVisible"
        width="400px"
      >
        <el-select v-model="selectedMemberId" placeholder="请选择成员" style="width: 100%">
          <el-option
            v-for="member in flattenedTreeData"
            :key="member.id"
            :label="member.name"
            :value="member.id"
          />
        </el-select>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditMember">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {getUserId} from '@/token/auth'
import TreeChart from 'vue-tree-chart-3'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '../../utils/axiosConfig'
import { flattenTree } from '@/utils/treeUtils'

export default {
  name: 'FamilyTree',
  components: {
    TreeChart,
    Plus
  },
  data() {
    return {
      userId: 3,
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择所属分支', trigger: 'change' }
        ],
        relation: [
          { required: true, message: '请选择关系', trigger: 'change' }
        ],
        birthDate: [
        { required: true, message: '请选择出生日期', trigger: 'change' }
        ]
      },
      treeData :{
        id: '1',
        name: '爷爷',
        image_url: require('@/assets/pictures/space/Inbase.png'),
        relation: 'grandfather',
        birthDate: '1940-01-01',
        phone: '13800138000',
        children: [
          {
            id: '2',
            name: '父亲',
            image_url: require('@/assets/pictures/space/Inbase.png'),
            relation: 'father',
            birthDate: '1965-01-01',
            phone: '13800138001',
            children: [
              {
                id: '3',
                name: '我',
                image_url: require('@/assets/pictures/space/career.png'),
                relation: 'self',
                birthDate: '1990-01-01',
                phone: '13800138002',
                isCurrentUser: true,
                children: []
              }
            ]
          },
          {
            id: '2',
            name: '父亲',
            image_url: require('@/assets/pictures/space/career.png'),
            relation: 'father',
            birthDate: '1965-01-01',
            phone: '13800138001',
            children: [
              {
                id: '3',
                name: '我',
                image_url: require('@/assets/pictures/space/career.png'),
                relation: 'self',
                birthDate: '1990-01-01',
                phone: '13800138002',
                isCurrentUser: true,
                children: []
              }
            ]
          }
        ],
      },
      dialogVisible: false,
      editDialogVisible: false,
      dialogTitle: '添加成员',
      selectedMemberId: '',
      currentMember: {
        id: '',
        name: '',
        image_url: '',
        parentId: '',
        relation: '',
        birthDate: '',
        phone: '',
        isCurrentUser: false
      },
      uploadUrl: '/upload',
      flattenedTreeData: [
        {
          id: 1,
          name: "祖父",
          parentId: null,
          avatar: "grandfather.jpg",
          relation: "祖父",
          birthDate: "1940-01-01",
          phone: "1234567890",
          isCurrentUser: false
        },
        {
          id: 2,
          name: "父亲",
          parentId: 1,
          avatar: "father.jpg",
          relation: "父亲",
          birthDate: "1970-05-10",
          phone: "0987654321",
          isCurrentUser: false
        },
        {
          id: 3,
          name: "我",
          parentId: 2,
          avatar: "me.jpg",
          relation: "本人",
          birthDate: "1995-08-20",
          phone: "1122334455",
          isCurrentUser: true
        }
      ],
      availableParents: [
        {
          id: 1,
          name: "祖父",
          parentId: null,
          avatar: "grandfather.jpg",
          relation: "祖父",
          birthDate: "1940-01-01",
          phone: "1234567890",
          isCurrentUser: false
        },
        {
          id: 2,
          name: "父亲",
          parentId: 1,
          avatar: "father.jpg",
          relation: "父亲",
          birthDate: "1970-05-10",
          phone: "0987654321",
          isCurrentUser: false
        },
        {
          id: 3,
          name: "我",
          parentId: 2,
          avatar: "me.jpg",
          relation: "本人",
          birthDate: "1995-08-20",
          phone: "1122334455",
          isCurrentUser: true
        }
      ]
    }
  },
  created() {
    this.fetchTreeData()
    this.userId = getUserId();
  },
  methods: {
    // 获取族谱数据
    async fetchTreeData() {
      try {
        const response = await request.get(`/family-tree/${this.userId}`)
        this.processTreeData(response)
        this.treeData = response
        this.flattenedTreeData = flattenTree(response)
        this.availableParents = this.flattenedTreeData
        // console.log('获取族谱树数据成功：', response)
      } catch (error) {
        ElMessage.error('获取族谱数据失败')
      }
    },
    processTreeData(node) {
      // 将 avatar 字段改为 image_url，并使用 require 处理图片路径
      try {
        // 如果后端返回的是完整的图片路径，则使用 require 处理
        node.image_url = node.image_url ? require('@/assets/pictures/space/' + node.image_url) : require('@/assets/pictures/1.png')
      } catch (e) {
        // 如果 require 失败，使用默认图片
        node.image_url = require('@/assets/pictures/1.png')
      }

      // 设置默认值
      node.relation = node.relation || '未知'
      node.birthDate = node.birthDate || '未知'
      node.phone = node.phone || '未知'
      
      // 递归处理子节点
      if (node.children && node.children.length) {
        node.children.forEach(child => this.processTreeData(child))
      }
    },
    // 显示添加对话框
    showAddDialog() {
      this.dialogTitle = '添加成员'
      this.currentMember = {
        id: '',
        name: '',
        avatar: '',
        parentId: '',
        relation: '',
        birthDate: '',
        phone: '',
        isCurrentUser: false
      }
      this.dialogVisible = true
    },

    // 显示编辑对话框
    editMember() {
      this.editDialogVisible = true
    },

    // 处理编辑成员
    async handleEditMember() {
      if (!this.selectedMemberId) {
        ElMessage.warning('请选择要编辑的成员')
        return
      }
      
      const member = this.flattenedTreeData.find(m => m.id === this.selectedMemberId)
      if (member) {
        this.currentMember = { ...member }
        this.dialogTitle = '编辑成员'
        this.editDialogVisible = false
        this.dialogVisible = true
      }
    },

    // 上传头像并回显
    handleAvatarChange(event) {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
        return
      }

      // 使用 FileReader 预览图片
      const reader = new FileReader()
      reader.onload = (e) => {
        this.currentMember.image_url = e.target.result
      }
      reader.readAsDataURL(file)

      // 如果需要上传到服务器，可以在这里添加上传逻辑
      // const formData = new FormData()
      // formData.append('file', file)
      // 调用上传API...
    },

    // 保存成员信息
    async saveMember() {
      const isValid = await new Promise((resolve) => {
        this.$refs.memberForm.validate((valid) => {
          resolve(valid);
        });
      });
      if (!isValid) {
        ElMessage.error('请填写完整的表单信息!');
        return;
      }

      try {
        const url = this.currentMember.id ? 
          `/family-tree/${this.currentMember.id}` : 
          '/family-tree'
        await request({
          url,
          method: this.currentMember.id ? 'put' : 'post',
          data: this.currentMember
        })
        // console.log('保存成功:',response)  没有response么嘎
          ElMessage.success('保存成功')
          this.dialogVisible = false
          this.fetchTreeData()
      } catch (error) {
        console.log('新增成员失败', this.currentMember)
        ElMessage.error('保存失败')
      }
    },

    // 删除成员
    async deleteMember() {
      try {
        const confirmResult = await this.$confirm(
          '此操作将永久删除该成员, 是否继续?', 
          '提示', 
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err);

        // 如果用户确认删除，则 confirmResult 为 'confirm'
        // 如果用户取消删除，则 confirmResult 为 'cancel'
        if (confirmResult !== 'confirm') {
          return; // 用户取消操作，直接返回
        }

        // 执行删除操作
        await request.delete(`/family-tree/${this.currentMember.id}`);
        ElMessage.success('删除成功');
        this.dialogVisible = false;
        this.fetchTreeData();

      } catch (error) {
        ElMessage.error('删除失败')
      }
    },

    // 保存整个族谱
    async saveTreeData() {
      try {
        await request.put('/family-tree', this.treeData)
        ElMessage.success('保存成功')
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  }
}
</script>

<style scoped>
@import url('../../assets/css/space/familyTree.css');
</style>