<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="角色状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sys_status"
            :key="dict.value"
            :label="dict.label"
            :value="Number(dict.value)"
          />
        </el-select>
      </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-table v-loading="loading" :data="roleList">
      <el-table-column label="角色名称" prop="roleName"  />
      <el-table-column label="角色类型" prop="roleType" >
        <template #default="scope">
          <dict-tag :options="sys_role_type" :value="scope.row.roleType" />
        </template>
      </el-table-column>
      <el-table-column label="作用域" prop="scope" >
        <template #default="scope">
          <dict-tag :options="sys_scope" :value="scope.row.scope" />
        </template>
      </el-table-column>
      <el-table-column
        label="所属租户名称"
        prop="tenantName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="所属项目名称"
        prop="projectName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="状态" align="center" width="100">
        <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 label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <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 link type="primary" icon="Delete"
                     v-if="(userStore.isSuperAdmin === 0 && scope.row.scope !== 1) || userStore.isSuperAdmin === 1">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入角色名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色类型" prop="roleType">
              <el-select v-model="form.roleType" placeholder="请选择角色类型">
                <el-option
                  v-for="dict in filteredRoleTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 作用域选择 -->
            <el-form-item label="作用域" prop="scope">
              <el-radio-group v-model="form.scope" @change="handleScopeChange">
                <el-radio
                    v-for="dict in sys_scope"
                    :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-row>
        <el-row>
          <el-col :span="12">
            <!-- 所属租户 - 可搜索下拉框 -->
            <el-form-item
                v-if="[2].includes(form.scope)"
                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="[3].includes(form.scope)"
                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-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </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="Role">
import {
  addRole,
  roleStatusChange,
  delRole,
  listRole,
  getRoleDetail,
  roleUpdate,
  searchScopeList
} from '@/api/system/role'
import useUserStore from '@/store/modules/user'
import {computed} from "vue";

const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_role_type, sys_scope, sys_status } = proxy.useDict(
  'sys_role_type',
  'sys_scope',
  'sys_status'
)

const roleList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref('')
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    loginTenantBizId: userStore.currentTenant.apiLoginTenantInfoResponse.tenantBizId,
    roleName: undefined,
    roleKey: undefined,
    status: undefined
  },
  rules: {
    roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
    roleType: [{ required: true, message: '角色类型不能为空', trigger: 'blur' }],
    scope: [{ required: true, message: '作用域不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    projectBizId: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
    tenantBizId: [{ required: true, message: '租户不能为空', trigger: 'blur' }]
  }
})
const { queryParams, form, rules } = toRefs(data)

/** 计算属性-角色类型 */
const filteredRoleTypeOptions = computed(() => {
  //角色类型或者角色类型数组是否存在
  if (!sys_role_type.value || !Array.isArray(sys_role_type.value)) return []

  return sys_role_type.value.filter(option => {
    // 过滤掉超级管理员选项
    if (!option || typeof option.value === 'undefined') return false
    return Number(option.value) !== 1
  })
})

/** 查询角色列表 */
function getList() {
  loading.value = true
  listRole(queryParams.value).then(response => {
    if (response.code === 200) {
      roleList.value = response.data.records
      total.value = response.data.total
      loading.value = false
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || ids.value
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      return delRole(roleIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 角色状态修改 */
function handleStatusChange(row) {
  const newStatus = row.status === 0 ? 0 : 1 // 获取切换后的新状态
  const text = newStatus === 0 ? '停用' : '启用' // 根据新状态显示文本
  console.log('newStatus', newStatus)
  proxy.$modal
    .confirm(`确认要${text}"${row.roleName}"角色吗?`)
    .then(function () {
      return roleStatusChange(row.roleBizId, newStatus).then(() => {
        proxy.$modal.msgSuccess(`${text}成功`)
        // 请求成功后，更新状态
        row.status = newStatus
        getList()
      })
    })
    .catch(() => {
      // 操作取消时恢复原状态
      row.status = row.status === 1 ? 0 : 1
      // 用户取消操作，保持原状态不变
      // 这里不需要做任何操作，因为switch会自动回滚
    })
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {}
  proxy.resetForm('roleRef')
}

/** 添加角色 */
function handleAdd() {
  form.value = {}
  open.value = true
  title.value = '添加角色'
}

/** 修改角色 */
function handleUpdate(row) {
  reset()
  const roleBizId = row.roleBizId
  getRoleDetail(roleBizId).then(response => {
    if (response.code === 200) {
      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
        });
      }

      open.value = true
      title.value = '修改角色'
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['roleRef'].validate(valid => {
    if (valid) {
      if (form.value.roleBizId) {
        roleUpdate(form.value).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(response.msg)
          }
        })
      } else {
        addRole(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}
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>
