<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container" style="margin-top: 20px">
          <el-input
            v-model="filterText"
            placeholder="请输入部门名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
          <el-tree
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            ref="treeRef"
            node-key="id"
            highlight-current
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <page-search :searchFormConfig="searchFormConfig" :deptId="deptId" @resetBtnClick="handleResetClick"
          @queryBtnClick="handleQueryClick" />
        <page-content ref="pageContentRef" :contentTableConfig="contentTableConfig"
          pageName="/system/user" @newBtnClick="handleNewData" @editBtnClick="handleEditData"
          @resetPassBtnClick="handleResetPassClick" @allotRoleBtnClick="handleAllotRoleClick">
          <template #userstatus="{ row }">
            <el-tag :type="row.status === '1' ? 'error' : 'success'">{{ row.status === '1' ? '禁用' : '启用' }}</el-tag>
          </template> 
          <template #deptName="{ row }">
            <span>{{ row.dept && row.dept.deptName ? row.dept.deptName : '' }}</span>
          </template>
          <template #handler="scope">
              <!-- <el-button
                icon="Setting"
                size="small"
                type="primary"
                link
                @click="handleResetPassClick(scope.row)"
              >
                重置密码
              </el-button>
              <el-button
                icon="Setting"
                size="small"
                type="primary"
                link
                @click="handleAllotRoleClick(scope.row)"
              >
                分配角色
              </el-button> -->
              <el-dropdown style="margin-top: 6px;">
                <span class="el-dropdown-link">
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleResetPassClick(scope.row)">重置密码</el-dropdown-item>
                    <el-dropdown-item  @click="handleAllotRoleClick(scope.row)">分配角色</el-dropdown-item>
                    
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
          </template>
        </page-content>
        <page-modal :defaultInfo="defaultInfo" ref="pageModalRef" pageName="/system/user"
          :modalConfig="modalConfigRef" :dataProcessingFn="dataProcessingFn"></page-modal>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { defineComponent, ref, computed, watch, getCurrentInstance } 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 { deptTreeSelect, resetUserPwd } from '@/api/system/user'
import useSelectStore from '@/store/commonSelect/common'
import router from '@/router'
const deptOptions = ref(undefined)
/** 查询部门下拉树结构 */
getDeptTree()
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data
  })
}
export default defineComponent({
  name: 'User',
  components: {
    PageSearch,
    PageContent,
    PageModal
  },
  setup() {
    const filterText = ref('')
    const deptId = ref(0)
    const [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch()
    const { proxy } = getCurrentInstance()

    watch(filterText, (val) => {
      proxy.$refs['treeRef'].filter(val)
    })
    // watch(defaultInfo, (val) => {
    //   console.log(val)
    // })
    const filterNode = (value, data) => {
      if (!value) return true
      return data.label.includes(value)
    }

    //点击部门
    const handleNodeClick = (data) => {
      deptId.value = data.id
      console.log(deptId.value, 'deptId.value');
      // handleQueryClick()
    }
    const handleResetPassClick = (row) => {
      proxy
        .$prompt('请输入"' + row.userName + '"的新密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
        })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            proxy.$modal.msgSuccess('修改成功，新密码是：' + value)
          })
        })
        .catch(() => {})
    }
    const handleAllotRoleClick = (row) => {
      const userId = row.userId
      router.push('/system/user-auth/role/' + userId)
    }

    // 1.处理逻辑
    const newCallback = () => {}
    const editCallback = () => {
      console.log('1111')
      console.log(defaultInfo.value)
    }

    // 2.动态添加部门和角色列表
    const modalConfigRef = computed(() => {
      const DeptItem = modalConfig.formItems.find(
        (item) => item.field === 'deptId'
      )
      DeptItem.options = useSelectStore().deptListData
	  console.log(DeptItem.options)

      const RoleItem = modalConfig.formItems.find(
        (item) => item.field === 'roleIds'
      )
      if (RoleItem) RoleItem.options = useSelectStore().roleList
      

      const PostItem = modalConfig.formItems.find(
        (item) => item.field === 'postIds'
      )
      PostItem.options = useSelectStore().postList
      return modalConfig
    })

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

	// 处理请求数据
    function dataProcessingFn (data){
		console.log(data) 
		return data;
	}
	
	return {
	  dataProcessingFn,
      searchFormConfig,
      contentTableConfig,
      pageContentRef,
      handleResetClick,
      handleQueryClick,
      modalConfigRef,
      pageModalRef,
      defaultInfo,
      handleNewData,
      handleEditData,
      deptOptions,
      filterText,
      filterNode,
      deptId,
      handleNodeClick,
      handleResetPassClick,
      handleAllotRoleClick
    }
  }
})
</script>
