<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="menuList"
      row-key="deptBizId"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="deptName" label="部门名称" width="140px"></el-table-column>

      <el-table-column prop="type" label="类型">
        <template #default="scope">
          <dict-tag :options="sys_dept_type" :value="scope.row.menuType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="150">
        <template #default="scope">
          <el-switch
            v-if="
              (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
              userStore.isSuperAdmin === 1
            "
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @click="
              evt => {
                evt.preventDefault()
                handleStatusChange(scope.row)
              }
            "
          ></el-switch>
          <dict-tag
            :options="sys_status"
            :value="scope.row.status"
            v-if="userStore.isSuperAdmin === 0 && scope.row.scope === 1"
          />
        </template>
      </el-table-column>
      <el-table-column prop="attribute" label="组织属性">
        <template #default="scope">
          <dict-tag :options="sys_dept_attribute" :value="scope.row.attribute" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>

      <el-table-column prop="scope" label="作用域">
        <template #default="scope">
          <dict-tag :options="sys_scope" :value="scope.row.scope" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-if="
              (userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
              userStore.isSuperAdmin === 1
            "
            >修改</el-button
          >
          <!-- <el-button
            v-if="
              scope.row.parentId != 0 &&
              ((userStore.isSuperAdmin === 0 && scope.row.scope !== 1) ||
                userStore.isSuperAdmin === 1)
            "
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级部门" prop="parentBizId">
              <el-tree-select
                v-model="form.parentBizId"
                :data="menuOptions"
                :props="{ value: 'deptBizId', label: 'deptName', children: 'children' }"
                value-key="deptBizId"
                placeholder="选择上级部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="form.type" @change="handleTypeChange">
                <el-radio
                  v-for="dict in sys_dept_type"
                  :key="Number(dict.value)"
                  :value="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_status"
                  :key="dict.value"
                  :value="Number(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="`${nameDept}名称`" prop="deptName">
              <el-input v-model="form.deptName" :placeholder="`请输入${nameDept}名称`" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="组织属性" prop="attribute">
              <el-select v-model="form.attribute" placeholder="请输入">
                <el-option
                  v-for="item in sys_dept_attribute"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="scope" label="作用域">
              <el-select v-model="form.scope" placeholder="请输入" @change="handleScopeChange">
                <el-option
                  v-for="item in sys_scope"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 所属租户 - 可搜索下拉框 -->
            <el-form-item v-if="form.scope == '2'" label="所属租户" prop="tenantBizId">
              <el-select
                v-model="form.tenantBizId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索租户"
                :remote-method="searchTenants"
                :loading="tenantLoading"
              >
                <el-option
                  v-for="item in tenantOptions"
                  :key="item.tenantBizId"
                  :label="item.tenantName"
                  :value="item.tenantBizId"
                />
              </el-select>
            </el-form-item>

            <!-- 所属项目 - 可搜索下拉框 -->
            <el-form-item v-if="form.scope == '3'" label="所属项目" prop="projectBizId">
              <el-select
                v-model="form.projectBizId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索项目"
                :remote-method="searchProjects"
                :loading="projectLoading"
              >
                <el-option
                  v-for="item in projectOptions"
                  :key="item.projectBizId"
                  :label="item.projectName"
                  :value="item.projectBizId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Menu">
import { addMenu, delMenu, getMenu, updateMenu, searchScopeList } from '@/api/system/menu'
import { deptStatusChange, editDept, addDept, deptList, getDept } from '@/api/system/dept'
import useUserStore from '@/store/modules/user'
import SvgIcon from '@/components/SvgIcon'
import IconSelect from '@/components/IconSelect'

const { proxy } = getCurrentInstance()
const { sys_scope, sys_status, sys_dept_type, sys_dept_attribute } = proxy.useDict(
  'sys_scope',
  'sys_status',
  'sys_dept_attribute',
  'sys_dept_type'
)
const userStore = useUserStore()

const menuList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref('')
const menuOptions = ref([])
const isExpandAll = ref(false)
const refreshTable = ref(true)
const iconSelectRef = ref(null)
const nameDept = ref('部门')

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 999999,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    menuName: undefined
  },
  rules: {
    deptName: [{ required: true, message: `名称不能为空`, trigger: 'blur' }],
    orderNum: [{ required: true, message: '顺序不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
    scope: [{ required: true, message: '作用域不能为空', trigger: 'blur' }],
    attribute: [{ required: true, message: '组织属性不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    projectBizId: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
    tenantBizId: [{ required: true, message: '租户不能为空', trigger: 'blur' }],
    parentBizId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }]
  }
})

const { queryParams, form, rules } = toRefs(data)
// 类型修改
const handleTypeChange = value => {
  sys_dept_type.value.forEach(item => {
    if (item.value == value) {
      nameDept.value = item.label
    }
  })
  console.log('item', nameDept.value)
}

/** 部门状态修改  还未连调 */
const handleStatusChange = row => {
  const newStatus = row.status === 0 ? 0 : 1 // 获取切换后的新状态
  const text = newStatus === 0 ? '停用' : '启用' // 根据新状态显示文本
  proxy.$modal
    .confirm(`确认要${text}"${row.deptName}"吗?`)
    .then(function () {
      return deptStatusChange(row.deptBizId, newStatus).then(() => {
        proxy.$modal.msgSuccess(`${text}成功`)
        // 请求成功后，更新状态
        row.status = newStatus
        getList()
      })
    })
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 1 ? 0 : 1
      // 用户取消操作，保持原状态不变
      // 这里不需要做任何操作，因为switch会自动回滚
    })
}
/** 查询菜单列表 */
function getList() {
  loading.value = true
  deptList(queryParams.value).then(response => {
    menuList.value = proxy.handleTree(response.data.records, 'deptBizId')
    console.log('menuList.value', menuList.value)

    loading.value = false
  })
}

/** 查询菜单下拉树结构 */
function getTreeselect() {
  menuOptions.value = []
  deptList(queryParams.value).then(response => {
    const menu = { deptBizId: '0', deptName: '主类目', children: [] }
    menu.children = proxy.handleTree(response.data.records, 'deptBizId', 'parentBizId')
    console.log('deptMenu', menu)
    menuOptions.value.push(menu)
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {}
  proxy.resetForm('deptRef')
}

/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset()
}

/** 选择图标 */
function selected(name) {
  form.value.icon = name
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getTreeselect()
  open.value = true
  title.value = '添加'
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  getDept(row.deptBizId).then(response => {
    form.value = response.data

    // 根据作用域类型预加载关联数据
    if (response.data.scope === 2) {
      tenantOptions.value.push({
        tenantBizId: response.data.tenantBizId,
        tenantName: response.data.tenantName
      })
    } else if (response.data.scope === 3) {
      projectOptions.value.push({
        projectBizId: response.data.projectBizId,
        projectName: response.data.projectName
      })
    }
    handleTypeChange(response.data.type)
    open.value = true
    title.value = `编辑`
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['deptRef'].validate(valid => {
    if (valid) {
      if (form.value.deptBizId) {
        editDept(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.deptName + '"的数据项?')
    .then(function () {
      return delDept(row.deptBizId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
getList()

//========作用域-切换逻辑开始=========
const tenantOptions = ref([])
const tenantLoading = ref(false)
const projectOptions = ref([])
const projectLoading = ref(false)
// 作用域变更处理
function handleScopeChange(val) {
  console.log('作用域变更:', val)

  // 清空不需要的字段值
  if (val === 2) {
    form.value.projectBizId = ''
    // 自动加载租户列表（可选）
    searchTenants('')
  } else if (val === 3) {
    form.value.tenantBizId = ''
    // 自动加载项目列表（可选）
    searchProjects('')
  } else if (val === 1) {
    //系统级
    form.value.tenantBizId = ''
    form.value.projectBizId = ''
  }
}
// 搜索租户方法
function searchTenants(query) {
  tenantLoading.value = true
  try {
    const params = {
      loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
      scope: 2,
      name: query,
      pageNo: 1,
      pageSize: 10
    }

    searchScopeList(params).then(response => {
      tenantOptions.value = response.data.records
    })
  } catch (error) {
    console.error('租户搜索失败', error)
    tenantOptions.value = []
  } finally {
    tenantLoading.value = false
  }
}

// 搜索项目方法
function searchProjects(query) {
  projectLoading.value = true
  try {
    const params = {
      loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
      scope: 3,
      name: query,
      pageNo: 1,
      pageSize: 10
    }
    searchScopeList(params).then(response => {
      projectOptions.value = response.data.records
    })
  } catch (error) {
    console.error('项目搜索失败', error)
    projectOptions.value = []
  } finally {
    projectLoading.value = false
  }
}
//========作用域-切换逻辑结束=========
</script>
