<template>
    <div class="p-2">
      <transition>
        <div class="mb-[10px]">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
              <!-- <el-form-item label="角色名称" prop="role_name">
                <el-input v-model="queryParams.role_name" placeholder="请输入角色名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="权限字符" prop="role_code">
                <el-input v-model="queryParams.role_code" placeholder="请输入权限字符" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>  -->
              <el-form-item label="任务开始时间" label-width="120px" style="width: 400px">
                <el-date-picker
                  v-model="dateRange"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                ></el-date-picker>
              </el-form-item>
  
              <el-form-item>
                <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                <el-button @click="resetQuery" icon="Refresh">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </transition>
  
      <el-card shadow="hover">
        <template #header>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" plain @click="handleAdd()" icon="Plus">新增</el-button>
            </el-col>  
          </el-row>
        </template> 
        <el-table ref="roleTableRef" v-loading="loading" :data="roleList">  
          <el-table-column label="任务名称" prop="role_name" :show-overflow-tooltip="true"  />
          <el-table-column label="执行人" prop="role_code" :show-overflow-tooltip="true"  />
          <el-table-column label="作业项数" prop="description"/>
          <el-table-column label="作业状态" align="center" width="150">
            <template #default="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="任务状态" align="center" width="150">
            <template #default="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="任务起止时间" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="任务结束时间" align="center" prop="createTime">
            <template #default="scope">
              <span>{{ parseTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
              </el-tooltip> 
              <!-- <el-tooltip content="分配菜单权限" placement="top">
                <el-button link type="primary" icon="Menu" @click="handleAuthMenu(scope.row,'menu')"></el-button>
              </el-tooltip>
              <el-tooltip content="分配接口权限" placement="top">
                <el-button link type="primary" icon="DocumentAdd" @click="handleAuthMenu(scope.row,'interface')"></el-button>
              </el-tooltip> -->
            </template>
          </el-table-column>
        </el-table>
  
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.page_size"
          @pagination="getList"
        />
      </el-card>
  
      <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="roleFormRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="role_name">
            <el-input v-model="form.role_name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item prop="role_code">
            <template #label>
              <span>
                <el-tooltip content="控制器中定义的权限字符，如：admin" placement="top">
                  <el-icon><question-filled /></el-icon>
                </el-tooltip>
                权限字符
              </span>
            </template>
            <el-input v-model="form.role_code" placeholder="请输入权限字符" />
          </el-form-item>  
          <el-form-item label="备注">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
        </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> 
      <!-- 分配权限 -->
      <DistributionMenu ref="distributionMenuRef"/>
    </div>
</template>
  
  <script setup name="roleManagement">
  import { addRole, changeRoleStatus, delRole, getRole, listRole, updateRole } from "@/api/role.js";
  import { roleMenuTreeselect, treeselect } from '@/api/menu.js';
  import { ElMessage ,ElMessageBox} from "element-plus"; 
  import DistributionMenu from '@/views/roleManagement/distributionMenu.vue'
  
  const router = useRouter();
  const { proxy } = getCurrentInstance(); 
  
  const roleList = ref();
  const loading = ref(true)  
  const total = ref(0)
  const dateRange = ref(['', ''])
  const menuOptions = ref([])  
  const sys_normal_disable = ref([
    { value: "1", label: "正常" },
    { value: "0", label: "停用" },
  ])
  
  const queryFormRef = ref();
  const roleFormRef = ref(); 
  const menuRef = ref();
  const deptRef = ref();
  const distributionMenuRef = ref();
  
  const initForm = {
    uid: undefined,  
    role_name: '',
    role_code: '',  
    description: '',  
  }
  
  const data = reactive({
    form: { ...initForm },
    queryParams: {
      page: 1,
      page_size: 10,
      role_name: '',
      role_code: '',
      created_from: '',
      created_to:'' ,
    },
    rules: {
      role_name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
      role_code: [{ required: true, message: "权限字符不能为空", trigger: "blur" }], 
    }
  })
  const { form, queryParams, rules } = toRefs(data)
  
  const dialog = reactive({
    visible: false,
    title: ''
  });
  
  /**
   * 查询角色列表
   */
  const getList = async () => {   
    loading.value = true;
    queryParams.value.created_from = dateRange.value[0];
    queryParams.value.created_to = dateRange.value[1];
    const res = await listRole(queryParams.value);
    loading.value = false;
    roleList.value = res.data.roles;
    total.value = res.data.pagination.total; 
  }
  
  /**
   * 搜索按钮操作
   */
  const handleQuery = () => {
    queryParams.value.page = 1;
    getList();
  }

    /** 跳转菜单分配 */
// const handleAuthMenu = (row) => {
//   const roleId = row.uid;
//   router.push("/role-auth/menu/" + roleId);
// }
const handleAuthMenu = (row,type) => {
    distributionMenuRef.value?.show(row,type);
}
  
  /** 重置 */
  const resetQuery = () => {
    dateRange.value = ['', '']
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  /**删除按钮操作 */
  const handleDelete = async (row) => { 
    try { 
        await ElMessageBox.confirm(
            `确认要删除"${row.role_name}" 角色吗?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ); 
        const roleid = row?.uid;  
        const res = await delRole(roleid);
        if(res.meta.code !== 200){
            ElMessage.error(res.data.message);
            return;
        } 
        getList();
        ElMessage.success(`${row.role_name}角色删除成功`); 
    } catch (err) {  
        const errorMsg = err?.toString() || ''; 
        if (errorMsg.includes('cancel') || 
            errorMsg.includes('取消') || 
            errorMsg === 'cancel' || 
            err === 'cancel') { 
            return;
        }    
        if (errorMsg.includes('close') || err === 'close') { 
            return;
        }
        ElMessage.error(`${row.role_name}角色删除失败`);
    }    
  }
  
  
  /** 角色状态修改 */
  const handleStatusChange = async (row) => {
    let text = row.status === "1" ? "启用" : "停用";
    try {
      await proxy?.$modal.confirm('确认要"' + text + '""' + row.role_name + '"角色吗?');
      await changeRoleStatus(row.roleId, row.status);
      proxy?.$modal.msgSuccess(text + "成功");
    } catch {
      row.status = row.status === "0" ? "1" : "0";
    }
  }

  /** 所有部门节点数据 */
  const getDeptAllCheckedKeys = () => {
    // 目前被选中的部门节点
    let checkedKeys = deptRef.value?.getCheckedKeys();
    // 半选中的部门节点
    let halfCheckedKeys = deptRef.value?.getHalfCheckedKeys();
    if (halfCheckedKeys) {
      checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    }
    return checkedKeys
  }
  /** 重置新增的表单以及其他数据  */
  const reset = () => {
    menuRef.value?.setCheckedKeys([]); 
    form.value = { ...initForm };
    roleFormRef.value?.resetFields();
  
  }
  
  /** 添加角色 */
  const handleAdd = () => {
    reset(); 
    dialog.visible = true;
    dialog.title = "添加角色";
  }
  /** 修改角色 */
  const handleUpdate = async (row) => {
    try{
        reset();
        const roleId = row?.uid
        const {meta, data } = await getRole(roleId);
        if(meta.code !== 200){
            ElMessage.error(meta.message);
            return;
        }
        Object.assign(form.value, data);  
        dialog.title = "修改角色";
        dialog.visible = true;  
    }catch(err){
      ElMessage.error(err.message);
    }

  }
  /** 根据角色ID查询菜单树结构 */
  const getRoleMenuTreeselect = (roleId) => {
    return roleMenuTreeselect(roleId).then((res) => {
      menuOptions.value = res.data.menus;
      return res.data;
    })
  }
 
  /** 所有菜单节点数据 */
  const getMenuAllCheckedKeys = () => {
    // 目前被选中的菜单节点
    let checkedKeys = menuRef.value?.getCheckedKeys();
    // 半选中的菜单节点
    let halfCheckedKeys = menuRef.value?.getHalfCheckedKeys();
    if (halfCheckedKeys) {
      checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    }
    return checkedKeys;
  }
  /** 提交按钮 */
  const submitForm = () => {
    roleFormRef.value?.validate(async (valid) => {
      if (valid) { 
        form.value.uid ? await updateRole(form.value) : await addRole(form.value);
        const text = form.value.uid ? "更新成功" : "添加成功";
        ElMessage.success(text);
        dialog.visible = false
        getList()
      }
    })
  }
  /** 取消按钮 */
  const cancel = () => {
    reset()
    dialog.visible = false;
  }
  onMounted(() => {
    getList();
  });
  </script>
  