<template>
  <ATablePage
    ref="tablePage"
    v-bind="tablePageProps">
    <template #simpleFormItem="formData">
      <ElFormItem>
        <ElInput
          v-model="formData.nickname"
          placeholder="姓名"/>
      </ElFormItem>
      <ElFormItem>
        <ElInput
          v-model="formData.phone"
          placeholder="手机号"/>
      </ElFormItem>
    </template>
    <template #columns>
      <ElTableColumn label="头像" prop="avatar" width="60">
        <template #default="{row}">
          <ElImage :preview-src-list="Strings.isBlank(row.avatar)?[]:[AppApi.fileUrl(row.avatar)]" :src="Strings.isBlank(row.avatar)?Avatar:AppApi.fileUrl(row.avatar)" class="avatar" preview-teleported>
            <template #error>
              <ElIcon>
                <ElIconPicture/>
              </ElIcon>
            </template>
          </ElImage>
        </template>
      </ElTableColumn>

      <ElTableColumn label="姓名" prop="nickname"/>
      <ElTableColumn label="联系电话" prop="phone"/>
      <!-- <ElTableColumn label="登录手机号" prop="account.phone"/> -->
      <ElTableColumn label="用户名" prop="account.username"/>
      <ElTableColumn label="微信标识" prop="account.wechatOpenid" width="180"/>
      <ElTableColumn label="已授权客户端" prop="account.clientCode" width="130">
        <template #default="{row}">
          <ElCheckboxGroup v-model="row.account.clients" @change="clientChangeHandler($event,row)">
            <ElCheckbox v-for="client in  ClientUtil.clients" :key="client.val" :disabled="row.id == '1' && client.val === 1" :label="client.txt" :value="client.val"/>
          </ElCheckboxGroup>
        </template>
      </ElTableColumn>
      <ElTableColumn label="是否禁用" prop="account.disabled" width="100">
        <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="180"/>
    </template>
    <UserForm ref="userForm" :research="research"/>
    <BindRole ref="bindRole"/>
  </ATablePage>
</template>
<script lang="ts" setup>
import UserApi from '@/pages/sys/user/user-api.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 Strings from '@/common/utils/strings.ts'
import Avatar from '@/assets/images/avatar.png'
import ATablePage, {
  type ATablePageInstance,
  buildTablePageProps,
} from '@/components/a-page/a-table-page/ATablePage.tsx'

const userFormIns = useTemplateRef<InstanceType<typeof UserForm>>('userForm')
const bindRoleIns = useTemplateRef<InstanceType<typeof BindRole>>('bindRole')
const tablePageIns = useTemplateRef<ATablePageInstance>('tablePage')
const tablePageProps = buildTablePageProps<UserTypes.SearchUserParam, UserTypes.SearchUserResult>({
  pageLayout: {
    enableHighForm: false,
  },
  searchForm: {
    simpleForm: {
      colCount: 2,
    },
    paging(param) {
      return UserApi.paging(param)
        .then(res => {
          (res.data?.records ?? []).map(it => {
            it.account.clients = ClientUtil.getClients(it.account.clientCode!).map(it => it.val)
            return it
          })
          return res
        })
    },
  },
  toolBar: {
    leftTools: [
      {
        icon: 'Plus',
        label: '新建',
        action() {
          userFormIns.value?.open()
        },
      },
    ],
  },
  table: {
    actionColumn: {
      tableActions: [
        {
          tooltip: '编辑',
          icon: 'Edit',
          type: 'success',
          action({row}) {
            userFormIns.value?.open(row)
          },
        },
        {
          tooltip: '权限',
          icon: 'gongnengquanxian',
          type: 'warning',
          action({row}) {
            bindRoleIns.value?.open(row.id!)
          },
        },
        {
          tooltip: '重置密码',
          icon: 'zhongzhimima',
          type: 'danger',
          confirm: {
            title: '确定重置密码？',
          },
          show({row}) {
            return row.id != '1'
          },
          action({row}) {
            if (row.id == '1') {
              ElMessage.error('不能修改管理员')
              return
            }
            UserApi.resetPasswd(row.id!)
              .then((res) => {
                ElMessage.success(res.msg)
              })
          },
        },
      ],
    },
  },
})

function research() {
  tablePageIns.value?.doSearch()
}

function clientChangeHandler(clients: CheckboxValueType[], data: UserTypes.SearchUserResult) {
  UserApi.bindClient(data.id!, clients as number[])
    .then(() => {
      ElMessage.success('修改成功')
      research()
    })
}

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

</script>
<style lang="stylus" scoped>
.avatar {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

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