<template>
  <Page>
    <ElForm v-show="showSearchForm" inline @submit.prevent="paging">
      <ElFormItem label="姓名">
        <ElInput
          v-model="searchForm.nickname"
          placeholder="姓名"/>
      </ElFormItem>
      <ElFormItem label="手机号">
        <ElInput
          v-model="searchForm.phone"
          placeholder="手机号"/>
      </ElFormItem>
      <ElFormItem>
        <ElButton :icon="elIcons.Search" :loading="searching" native-type="submit" type="primary">搜索</ElButton>
        <ElButton :icon="elIcons.Refresh" :loading="searching" @click="reset">重置</ElButton>
      </ElFormItem>
    </ElForm>
    <div class="tool-bar">
      <ElButton :icon="elIcons.Plus" type="primary" @click="addHandler">新建</ElButton>
      <ElButton :icon="elIcons.Filter" type="default" @click="showSearchForm = !showSearchForm"/>
    </div>
    <ElTable v-loading="searching" :data="tableData"
      cell-class-name="table-cell"
      class="table-list"
      empty-text="暂无数据"
      header-row-class-name="table-header"
      row-key="id">
      <ElTableColumn label="昵称" prop="nickname"/>
      <ElTableColumn label="头像" prop="avatar" width="60">
        <template #default="{row}">
          <ElImage :src="AppApi.fileUrl(row.avatar)" class="avatar">
            <template #error>
              <ElIcon>
                <ElIconPicture/>
              </ElIcon>
            </template>
          </ElImage>
        </template>
      </ElTableColumn>
      <ElTableColumn label="联系电话" prop="phone"/>
      <ElTableColumn label="登录手机号" prop="account.phone"/>
      <ElTableColumn label="用户名" prop="account.username"/>
      <ElTableColumn label="微信标识" prop="account.wechatOpenid"/>
      <ElTableColumn label="已授权客户端" prop="account.clientCode" width="110">
        <template #default="{row}">
          <ElCheckboxGroup v-model="row.account.clients" :disabled="row.id == '1'" @change="clientChangeHandler($event,row)">
            <ElCheckbox v-for="client in  ClientUtil.clients" :key="client.val" :label="client.txt" :value="client.val"/>
          </ElCheckboxGroup>
        </template>
      </ElTableColumn>
      <ElTableColumn label="是否禁用" prop="account.disabled">
        <template #default="{row}">
          <ElSwitch v-model="row.account.disabled" :disabled="row.id == '1'" @change="disabledUserHandler($event,row.id)"/>
        </template>
      </ElTableColumn>
      <ElTableColumn label="注册时间" prop="account.regdate" width="170"/>

      <ElTableColumn label="操作" width="180">
        <template #default="scope">
          <!-- <ElButton text type="danger" :loading="deling" @click="delHandler(scope)">删除</ElButton> -->
          <div class="action-btn">
            <ElButton text type="primary" @click="bindRoleHandler(scope)">权限</ElButton>
            <ElButton v-if="scope.row.id != '1'" text type="primary" @click="modifyHandler(scope)">修改</ElButton>
            <ElButton v-if="scope.row.id != '1'" text type="primary" @click="resetPasswd(scope)">重置密码</ElButton>
          </div>
        </template>
      </ElTableColumn>
    </ElTable>
    <ElPagination
      v-model:current-page="searchForm.current"
      v-model:page-size="searchForm.size"
      :hide-on-single-page="false"
      :page-sizes="[10, 20, 50, 100, 500]"
      :teleported="false"
      :total="totalCount"
      layout="->, sizes, total, prev, pager, next"
      @change="paging"/>
    <UserForm ref="userForm" @edit-succ="paging"/>
    <BindRole ref="bindRole"/>
  </Page>
</template>
<script lang="ts" setup>
import UserApi from '@/pages/sys/user/user-api.ts'
import Page from '@/components/page/Page.vue'
import { elIcons } from '@/common/element/element.ts'
import UserForm from '@/pages/sys/user/UserForm.vue'
import {
  type CheckboxValueType,
  ElMessage,
} from 'element-plus'
import AppApi from '@/common/app/app-api.ts'
import BindRole from '@/pages/sys/user/BindRole.vue'
import ClientUtil from '@/common/utils/client-util.ts'
import Utils from '@/common/utils'

const totalCount = ref(0)
const tableData = Utils.resetAble(reactive<UserTypes.SearchUserResult[]>([]))
const searchForm = Utils.resetAble(reactive<UserTypes.SearchUserParam>({
  current: 1,
  size: 20,
}))
const searching = ref(false)
// const deling = ref(false)
const showSearchForm = ref(true)
const userFormIns = useTemplateRef<InstanceType<typeof UserForm>>('userForm')
const bindRoleIns = useTemplateRef<InstanceType<typeof BindRole>>('bindRole')

function showDialog(data?: UserTypes.SearchUserResult) {
  userFormIns.value?.open(data)
}

/* function delHandler({row}: { row: UserTypes.SearchUserResult }) {
 if (row.id == '1') {
 ElMessage.error('不能删除管理员')
 return
 }
 deling.value = true
 UserApi.del([ row.id! ])
 .then(() => {
 ElMessage.success('删除成功')
 paging()
 })
 .finally(() => {
 deling.value = false
 })
 } */

function modifyHandler({row}: { row: UserTypes.SearchUserResult }) {
  if (row.id == '1') {
    ElMessage.error('不能修改管理员')
    return
  }
  showDialog(row)
}

function resetPasswd({row}: { row: UserTypes.SearchUserResult }) {
  if (row.id == '1') {
    ElMessage.error('不能修改管理员')
    return
  }
  UserApi.resetPasswd(row.id!)
    .then((res) => {
      ElMessage.success(res.msg)
    })
}

function bindRoleHandler({row}: { row: UserTypes.SearchUserResult }) {
  bindRoleIns.value?.open(row.id!)
}

function addHandler() {
  showDialog()
}

function reset() {
  searchForm.$reset()
  paging()
}

function clientChangeHandler(clients: CheckboxValueType[], data: UserTypes.SearchUserResult) {
  if (data.id == '1') {
    ElMessage.error('不能操作管理员')
    return
  }
  searching.value = true
  UserApi.bindClient(data.id!, clients as number[])
    .then(() => {
      ElMessage.success('修改成功')
      paging()
    })
}

function disabledUserHandler(val: string | number | boolean, id: string) {
  if (id == '1') {
    ElMessage.error('不能操作管理员')
    return
  }
  searching.value = true
  UserApi.disable(id, val as boolean)
    .then(() => {
      ElMessage.success(val ? '禁用成功' : '启用成功')
      paging()
    })
}

function paging() {
  searching.value = true
  UserApi.paging(searchForm)
    .then(res => {
      totalCount.value = res.data?.total ?? 0
      tableData.$reset((res.data?.records ?? []).map(it => {
        it.account.clients = ClientUtil.getClients(it.account.clientCode!).map(it => it.val)
        return it
      }))
    })
    .finally(() => {
      searching.value = false
    })
}

onMounted(() => {
  paging()
})
</script>
<style lang="stylus" scoped>
.table-list {
  flex 1;
  margin 0 0 20px 0
  width 100%

  :deep(.table-header) {
    color #454C59

    th {
      background-color #EDF1F7
      font-weight 500
      position relative

      & > div {
        display flex
        gap 5px
        align-items center
      }

      &:not(:first-child) > div::before {
        position: absolute;
        top: 50%;
        left: 1px;
        width: 1px;
        background-color: #D3D7DE;
        transform: translateY(-50%);
        content: "";
        height 50%
      }
    }
  }

  :deep(.table-cell) {
    color #2F3540
  }

  .action-btn {
    width 100%
    display flex
    flex-wrap wrap

    & > button {
      margin 0
    }
  }
}

.tool-bar {
  display flex
  justify-content space-between
  margin 0 0 20px 0
}

.avatar {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  :deep(.el-icon) {
    font-size 25px
  }
}
</style>
