<template>
  <el-card shadow="hover">

    <el-row>
      <el-col :span="20">
        <el-button @click="addUser">新增用户</el-button>
        <el-input
            style="width: 200px;margin-left: 10px"
            :suffix-icon="Search"
            v-model="search.inputSearch"
            placeholder="请输入用户名"
            @change="searchQuery"
        >
        </el-input>
        <el-button style="margin-left: 10px" @click="clearSerach">清空查询</el-button>
        <el-button @click="updateUserRole">为所有用户添加角色</el-button>
      </el-col>
      <el-col :span="4">
        <el-button @click="searchPage">刷新</el-button>
      </el-col>
    </el-row>

    <br/>

    <vxe-table
        round
        border="inner"
        size="mini"
        keep-source
        :row-config="{isHover: true}"
        :column-config="{resizable: true}"
        ref="tableRef"
        :data="tableData"
    >
      <vxe-column type="seq" width="60"></vxe-column>
      <vxe-column field="username" title="用户名" show-overflow/>
      <vxe-column field="nickname" title="昵称" show-overflow/>
      <vxe-column field="roleName" title="角色" show-overflow/>
      <vxe-column field="enabled" title="是否可用" formatter="formatIsNo"/>
      <vxe-column field="createTime" title="创建时间"/>
      <vxe-column title="操作" width="240">
        <template #default="{ row }">
          <el-button link type="primary" @click="editUserRoles(row)">角色设置</el-button>
          <el-button link type="primary" @click="updateUser(row)">详情</el-button>
          <el-button link type="primary" @click="updateUserPw(row)">修改密码</el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="delUser(row)">
            <template #reference>
              <el-button link type="primary">删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </vxe-column>
    </vxe-table>

    <br/>

    <el-pagination
        small
        :currentPage="page.current"
        :page-size="page.size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <el-dialog
        draggable
        v-model="userDialogVisible"
        :title="dialogTitle"
        width="35vw"
    >

      <el-form :model="userFrom" ref="userformRef" :rules="rules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username" :style="formInputWidth">
          <el-input v-model="userFrom.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="dialogTitle === '新增用户'" label="密码" :label-width="formLabelWidth" prop="password" :style="formInputWidth">
          <el-input v-model="userFrom.password" placeholder="请输入密码" type="password" show-password/>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname" :style="formInputWidth">
          <el-input v-model="userFrom.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="是否可用" :label-width="formLabelWidth" prop="enabled" :style="formInputWidth">
          <el-switch v-model="userFrom.enabled" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="userSave">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog
        draggable
        v-model="userRoleDialogVisible"
        title="角色设置"
        width="600px"
    >

      <el-transfer
          v-model="userRoleList"
          :data="roleList"
          filterable
          filter-placeholder="请输入角色名"
          :titles="['系统角色', '用户角色']"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="userRoleSave">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
        draggable
        v-model="userPwDialogVisible"
        title="修改密码"
        width="35vw"
    >
      <el-form :model="userPwFrom" ref="userPwformRef" :rules="rulesPw">
        <el-form-item label="用户" :label-width="formLabelWidth">{{ currentUser.username }}</el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="password" :style="formInputWidth">
          <el-input v-model="userPwFrom.password" placeholder="请输入新密码" type="password" show-password/>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userPwDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="userPwSave">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import { Plus, ArrowLeft, Search } from '@element-plus/icons-vue'

const {proxy} = getCurrentInstance()

const ConditionEnum = proxy.$launchUtil.ConditionEnum
const {Page, Query, createSelectPage} = proxy.$launchUtil.selectPage
const {handleData} = proxy.$launchUtil.vxeUtils

const usersApi = proxy.$launchApi.usersApi
const rolesApi = proxy.$launchApi.rolesApi

// 搜索
let search = ref({})

// 分页
let newPage = new Page(10,1)
newPage.setOrders([
  {column:"update_time",asc:false}
])
let page = ref(newPage)
let querys = ref([])

// 表格
let tableRef = ref(null)

let tableData = ref([])

// 用户弹出层
let dialogTitle = ref("")
let userDialogVisible = ref(false)

let userFrom = ref({})
let userformRef = ref(null)
let rules = ref({
  username:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
  password:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
  nickname:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
  enabled:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ],
})
let formLabelWidth = ref('120px')
let formInputWidth = ref("width: 300px")

// 当前编辑临时数据
let currentUser = ref({})

// 用户设置角色弹出层
let userRoleDialogVisible = ref(false)
let roleList = ref([])
let userRoleList = ref([])

// 修改密码弹出层
let userPwDialogVisible = ref(false)
let userPwFrom = ref({})
let userPwformRef = ref(null)
let rulesPw = ref({
  password:[
    { required: true, message: '该值不能为空',trigger: 'change'}
  ]
})


function addUser() {
  dialogTitle.value = "新增用户"
  userDialogVisible.value = true
  userFrom.value = {
    enabled: true
  }

}

function userSave() {
  let valid = userformRef.value.validate((valid, fields) => {
    return valid
  })
  valid.then(val => {
    if(!val){
      proxy.$message.error("请输入所有必填项")
    }
    if(dialogTitle.value === "用户详情"){
      // 未修改数据处理
      if(userFrom.value.username === currentUser.value.username
          && userFrom.value.nickname === currentUser.value.nickname
          && userFrom.value.enabled === currentUser.value.enabled){
        proxy.$message.warning("暂无可提交数据")
        return
      }
    }
    if(val){
      usersApi.save(userFrom.value).then(result => {
        if(result){
          proxy.$message.success("保存成功")
          userDialogVisible.value = false
          searchPage()

        }
      })
    }

  })

}



function searchQuery() {
  let queryArray = []
  if(search.value.inputSearch && search.value.inputSearch.trim() !== ""){
    let query = new Query()
    query.setCondition(ConditionEnum.eq())
    query.setVal(search.value.inputSearch)
    query.setColumn("username")
    queryArray.push(query)
  }
  querys.value = queryArray
  searchPage()
}

function clearSerach() {
  search.value = {}
  querys.value = []
  searchPage()
}

function searchPage() {
  usersApi.selectPage(createSelectPage(page.value,querys.value)).then(data => {
    if(data != null){
      tableData.value = data.records
      page.value.total = data.total
      page.value.current = data.current
    }
  })
}

function delUser(row) {
  usersApi.deleteById(row.id).then(result => {
    if(result === 1){
      proxy.$message.success("删除成功")
      searchPage()
    }
  })
}

function updateUser(row) {
  dialogTitle.value = "用户详情"
  userDialogVisible.value = true
  userFrom.value = handleData(row)
  currentUser.value = row
}

function editUserRoles(row) {
  currentUser.value = row
  userRoleDialogVisible.value = true
  // 获取用户和角色数据
  rolesApi.getRoles().then(result => {
    if(result){
      roleList.value = result
    }
  })
  rolesApi.getUserRoles(row.id).then(result => {
    if(result){
      userRoleList.value = result
    }
  })

}

function userRoleSave() {
  rolesApi.updateUserRoles(currentUser.value.id,userRoleList.value).then(result => {
    if(result){
      proxy.$message.success("修改成功！")
      userRoleDialogVisible.value = false
      searchPage()
    }
  })
}


function updateUserPw(row) {
  userPwDialogVisible.value = true
  currentUser.value = row
  userPwFrom.value = {
    password: ""
  }
}

function userPwSave() {
  let valid = userPwformRef.value.validate((valid, fields) => {
    return valid
  })
  valid.then(val => {
    if(!val){
      proxy.$message.error("请输入所有必填项")
    }
    if(val){
      let data = {
        userId: currentUser.value.id,
        pw: userPwFrom.value.password
      }
      usersApi.updatePw(data).then(result => {
        if(result === 1){
          proxy.$message.success("修改成功")
          userPwDialogVisible.value = false
        }
      })
    }

  })
}


// 分页操作
function handleSizeChange(val) {
  page.value.size = val
  searchPage()
}

function handleCurrentChange(val) {
  page.value.current = val
  searchPage()
}


function updateUserRole() {
  
}


onMounted(() => {

  searchPage()
})
</script>

<style scoped>
.dialog-footer{
  margin-right: var(--launch-dialog-footer-m-r);
}
</style>