<template>
  <view class="container" style="paddingBottom:1rpx;">
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" labelWidth="140rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
          <u-form-item label="上级部门" prop="parentName" @click="showDeptPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="parentName" disabled disabledColor="#ffffff" placeholder="请选择上级部门"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="部门名称" prop="deptName" required>
            <u--input v-model="form.deptName" placeholder="请输入部门名称" maxlength="30"
              inputAlign="left" :customStyle="getInputStyle('deptName')"></u--input>
          </u-form-item>

          <u-form-item label="显示排序">
            <u-number-box v-model="form.orderNum" :min="0" :max="999" inputAlign="right"></u-number-box>
          </u-form-item>

          <u-form-item label="负责人" prop="leader">
            <u--input v-model="form.leader" placeholder="请输入负责人" maxlength="20"
              inputAlign="left" :customStyle="getInputStyle('leader')"></u--input>
          </u-form-item>

          <u-form-item label="联系电话" prop="phone">
            <u--input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"
              inputAlign="left" :customStyle="getInputStyle('phone')"></u--input>
          </u-form-item>

          <u-form-item label="邮箱" prop="email">
            <u--input v-model="form.email" placeholder="请输入邮箱" maxlength="50"
              inputAlign="left" :customStyle="getInputStyle('email')"></u--input>
          </u-form-item>

          <u-form-item label="状态" prop="statusName" @click="showStatusPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="statusName" disabled disabledColor="#ffffff" placeholder="请选择状态"
                inputAlign="left" :customStyle="inputBaseStyle"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="showStatusPicker" :columns="statusList" keyName="dictLabel" @cancel="showStatusPicker = false"
      @confirm="handleStatusConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showDeptPicker" :columns="deptList" keyName="deptName" @cancel="showDeptPicker = false"
      @confirm="handleDeptConfirm"></u-picker>
  </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { getDept, addDept, updateDept, listDept } from '@/api/system/dept'
import { getDicts } from "@/api/system/dict/data"
import { onLoad } from "@dcloudio/uni-app"

const { proxy } = getCurrentInstance()
const statusList = ref([])
const deptList = ref([])
const title = ref('添加部门')
const showStatusPicker = ref(false)
const showDeptPicker = ref(false)
const statusName = ref('')
const parentName = ref('')

const form = reactive({
  deptId: undefined,
  parentId: 0,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0'
})

// 表单验证错误字段
const errorFields = ref([])

// 输入框基础样式
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '60rpx',
  lineHeight: '60rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 输入框错误样式
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '60rpx',
  lineHeight: '60rpx',
  width: '100%',
  boxSizing: 'border-box'
}

// 根据字段名获取输入框样式
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const rules = {
  deptName: [
    { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: ['blur'] }
  ]
}

onLoad((option) => {
  getDicts('sys_normal_disable').then(res => {
    statusList.value = [res.data]
  })

  if (option.id) {
    title.value = '修改部门'
    getDetail(option.id)
  } else {
    // 新增时加载部门列表
    loadDeptList()
    parentName.value = '顶级部门'
    setTimeout(() => {
      updateStatusName()
    }, 100)
  }
})

// 加载部门列表
function loadDeptList() {
  listDept().then(res => {
    const listData = res.data || []
    // 后端返回的是扁平数据，需要先构建树形结构
    const treeData = buildTree(listData)
    // 将树形结构扁平化为一维数组（带层级标记）
    const flatList = flattenDeptTree(treeData)
    deptList.value = [flatList]
  })
}

// 将扁平数据构建为树形结构
function buildTree(flatData) {
  const map = {}
  const tree = []
  
  // 先创建映射
  flatData.forEach(item => {
    map[item.deptId] = { ...item, children: [] }
  })
  
  // 构建树形结构
  flatData.forEach(item => {
    const node = map[item.deptId]
    if (item.parentId === '0' || !map[item.parentId]) {
      tree.push(node)
    } else {
      map[item.parentId].children.push(node)
    }
  })
  
  return tree
}

// 将部门树形结构扁平化
function flattenDeptTree(tree, result = [], level = 0) {
  tree.forEach(item => {
    // 使用更明显的层级标记：每级增加2个空格 + 符号
    let prefix = ''
    if (level === 1) {
      prefix = '　└─ '  // 使用全角空格
    } else if (level > 1) {
      prefix = '　'.repeat(level) + '└─ '
    }
    result.push({
      deptId: item.deptId,
      deptName: prefix + item.deptName,
      originalName: item.deptName,
      level: level
    })
    if (item.children && item.children.length > 0) {
      flattenDeptTree(item.children, result, level + 1)
    }
  })
  return result
}

// 获取详情
function getDetail(id) {
  getDept(id).then(res => {
    Object.assign(form, res.data)
    updateStatusName()
    updateParentName()
    // 修改时也加载部门列表
    loadDeptList()
  })
}

// 更新状态名称显示
function updateStatusName() {
  if (statusList.value.length > 0 && statusList.value[0].length > 0) {
    const item = statusList.value[0].find(v => v.dictValue === form.status)
    statusName.value = item ? item.dictLabel : ''
  }
}

// 更新上级部门名称显示
function updateParentName() {
  if (form.parentId && form.parentId !== 0) {
    getDept(form.parentId).then(res => {
      parentName.value = res.data.deptName
    })
  } else {
    parentName.value = '无'
  }
}

// 状态选择确认
function handleStatusConfirm(e) {
  form.status = e.value[0].dictValue
  statusName.value = e.value[0].dictLabel
  showStatusPicker.value = false
}

// 部门选择确认
function handleDeptConfirm(e) {
  form.parentId = e.value[0].deptId
  parentName.value = e.value[0].originalName
  showDeptPicker.value = false
}

// 提交
function submit() {
  errorFields.value = [] // 清空错误字段
  proxy.$refs['uForm'].validate().then(() => {
    if (form.deptId) {
      updateDept(form).then(() => {
        proxy.$refs['uToast'].show({
          message: '修改成功', complete() {
            uni.navigateTo({ url: `/pages_mine/pages/system/dept/list` })
          }
        })
      })
    } else {
      addDept(form).then(() => {
        proxy.$refs['uToast'].show({
          message: '新增成功', complete() {
            uni.navigateTo({ url: `/pages_mine/pages/system/dept/list` })
          }
        })
      })
    }
  }).catch((errors) => {
    // 记录验证失败的字段
    if (errors && Array.isArray(errors)) {
      errorFields.value = errors.map(err => err.field || err.prop)
    }
    proxy.$modal.msgError('请填写完整信息')
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
}

.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;

    .form-btn {
      padding-top: 16rpx;
    }
  }
}

.input-with-arrow {
  position: relative;
  width: 100%;
  
  .arrow-icon {
    position: absolute;
    right: 20rpx;
    top: 50%;
    transform: translateY(-50%);
    color: #c0c4cc;
    font-size: 20rpx;
    pointer-events: none;
    z-index: 10;
  }
}
</style>

<style lang="scss">
.form-btn .u-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  border: none !important;
  border-radius: 24rpx !important;
  height: 80rpx !important;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4) !important;
}

.form-btn .u-button__text {
  font-size: 30rpx !important;
  font-weight: 500 !important;
  letter-spacing: 2rpx !important;
}

/* 统一输入框高度和行高 */
.u--input,
.u-input__content__field-wrapper {
  height: 60rpx !important;
  line-height: 60rpx !important;
  min-height: 60rpx !important;
  box-sizing: border-box !important;
}

/* 强制统一所有输入框宽度 */
.u-form-item__body {
  flex: 1 !important;
}

.u-form-item__body .u--input {
  width: 100% !important;
  box-sizing: border-box !important;
}

/* 确保输入框内的文字垂直居中 */
.u-input__content__field-wrapper__field {
  line-height: 60rpx !important;
  height: 60rpx !important;
}
</style>
