<template>
  <div class="app-container">
    <page-search
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick"
    />
    <page-content
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      :isDataPower="isDataPower"
      :isExport="false"
      pageName="/system/role"
      @dataPowerBtnClick="handleDataPowerClick"
      @assignUserBtnClick="handleAssignUserClick"
      @newBtnClick="handleNewData"
      @editBtnClick="handleEditData"
    >
    <template #rolestatus="{ row }">
      <el-tag :type="row.status === '1' ? 'error' : 'success'">{{ row.status === '1' ? '禁用' : '启用' }}</el-tag>
    </template> 
    <template #handler="scope">
      <el-button
            icon="Setting"
            size="small"
            type="primary"
            link
            @click="handleAssignUserClick(scope.row)"
          >
            分配用户
          </el-button>
    </template>
  </page-content>
    <page-modal
      :defaultInfo="defaultInfo"
      ref="pageModalRef"
      pageName="/system/role"
      :modalConfig="modalConfigRef"
      :dataProcessingFn="dataProcessingFn"
    >
      <template #otherchildslot>
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')"
          >展开/折叠</el-checkbox
        >
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')"
          >全选/全不选</el-checkbox
        >
        <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')"
          >父子联动</el-checkbox
        >
        <el-tree
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="menuRef"
          node-key="id"
          :check-strictly="!menuCheckStrictly"
          empty-text="加载中，请稍候"
          :props="{ label: 'label', children: 'children' }"
          @check="treeSelectChange"
        ></el-tree>
        <!-- <el-tree-select
          v-model="treeValue"
          :data="menuOptions"
          :render-after-expand="false"
          show-checkbox
        /> -->
      </template>
      <template #otherchildslot2> 我是插槽2 </template>
    </page-modal>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" v-model="openDataScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>

        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import { defineComponent, ref, watch } from 'vue';

  import PageSearch from '@/components/page-search';
  import PageContent from '@/components/page-content';
  import PageModal from '@/components/page-modal';

  import { searchFormConfig } from './config/search.config';
  import { contentTableConfig } from './config/content.config';
  import { modalConfig } from './config/modal.config';

  import { usePageSearch } from '@/hooks/use-page-search';
  import { usePageModal } from '@/hooks/use-page-modal';
  import { dataScope } from '@/api/system/role';
  import { roleMenuTreeselect, treeselect as menuTreeselect } from '@/api/system/menu';
  import useSelectStore from '@/store/commonSelect/common';

  import router from '@/router';

  const isDataPower = ref(true);

  const dataScopeOptions = ref([
    { value: '1', label: '全部数据权限' },
    { value: '2', label: '自定数据权限' },
    { value: '3', label: '本部门数据权限' },
    { value: '4', label: '本部门及以下数据权限' },
    { value: '5', label: '仅本人数据权限' },
  ]);
  export default defineComponent({
    name: 'Role',
    components: {
      PageSearch,
      PageContent,
      PageModal,
    },
    setup() {
      const [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch();
      const title = ref('');
      const openDataScope = ref(false);
      const form = ref({});
      const menuCheckStrictly = ref(true);
      const treeValue = ref();
      const menuExpand = ref(false);
      const menuNodeAll = ref(false);
      const menuRef = ref(null);
      const checkedKeysData = ref([]);
      const menuOptions = ref([]);

      //     watch(getChatMsg, (newValue, oldValue) => {
      //   if (newValue) {
      //     if (!isJSON(newValue)) {
      //       console.log(newValue)
      //     }
      //   }
      // })
      function treeSelectChange(data, item) {
        // console.log(data, item, 'item');
        checkedKeysData.value = item.checkedKeys;
        if (item.halfCheckedKeys)
          checkedKeysData.value = Array.from(
            new Set(item.checkedKeys.concat(item.halfCheckedKeys)),
          );

        // console.log(checkedKeysData.value, 'checkedKeysData.value');
        // defaultInfo.value.menuIds = item.checkedKeys
      }
      function getMenuTreeselect(roleId) {
        roleMenuTreeselect(roleId).then((response) => {
          menuOptions.value = response.data.menus;
          if (response.data.checkedKeys.length > 0) {
            console.log(response.data);
            checkedKeysData.value = response.data.checkedKeys;
            let checkedKeys = response.data.checkedKeys;
            nextTick(() => {
              checkedKeys.forEach((v) => {
                nextTick(() => {
                  console.log(v);
                  menuRef.value.setChecked(v, true, false);
                });
              });
            });
          }
        });
      }
      function handleCheckedTreeExpand(value, type) {
        if (type == 'menu') {
          let treeList = menuOptions.value;
          for (let i = 0; i < treeList.length; i++) {
            menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      }
      function handleCheckedTreeNodeAll(value, type) {
        if (type == 'menu') {
          menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
        }
      }
      /** 树权限（父子联动） */
      function handleCheckedTreeConnect(value, type) {
        if (type == 'menu') {
          form.value.menuCheckStrictly = value ? true : false;
        }
      }
      const handleDataPowerClick = (row) => {
        title.value = '数据权限';
        openDataScope.value = true;
        form.value = row;
      };
      const handleAssignUserClick = (row) => {
        router.push('/system/role-auth/user/' + row.roleId);
      };
      const submitDataScope = () => {
        form.value.deptIds = getDeptAllCheckedKeys();
        dataScope(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功');
          openDataScope.value = false;
          handleQueryClick();
        });
      };
      const cancelDataScope = () => {
        openDataScope.value = false;
      };

      // 1.处理逻辑
      const newCallback = () => {
        console.log('添加');
        getMenuTreeselect(1);
      };
      const editCallback = () => {
        console.log('编辑');
        console.log(defaultInfo.value.roleId);
        getMenuTreeselect(defaultInfo.value.roleId);
      };

      // 2.动态添加部门和角色列表
      const modalConfigRef = computed(() => {
        return modalConfig;
      });

      // 3.调用hook获取公共变量和函数
      const [pageModalRef, defaultInfo, handleNewData, handleEditData] = usePageModal(
        newCallback,
        editCallback,
      );

      // 处理请求数据
      function dataProcessingFn(data) {
        data.menuIds = checkedKeysData.value;
        console.log(data, 'dataProcessingFn');
        return data;
      }
      return {
        dataProcessingFn,
        checkedKeysData,
        searchFormConfig,
        contentTableConfig,
        pageContentRef,
        handleResetClick,
        handleQueryClick,
        modalConfigRef,
        pageModalRef,
        defaultInfo,
        handleNewData,
        handleEditData,
        isDataPower,
        openDataScope,
        title,
        form,
        menuCheckStrictly,
        treeValue,
        dataScopeOptions,
        handleDataPowerClick,
        handleAssignUserClick,
        submitDataScope,
        cancelDataScope,
        getMenuTreeselect,
        menuOptions,
        menuRef,
        menuExpand,
        menuNodeAll,
        treeSelectChange,
        handleCheckedTreeNodeAll,
        handleCheckedTreeExpand,
        handleCheckedTreeConnect,
      };
    },
  });
</script>
