<template>
  <div>
    <div>
      <n-card :bordered="false" title="后台用户">
        你可以为不同的岗位人员分配不同的用户账号，并在这里对他们进行管理
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="formParams?.id > 0 ? '编辑用户 #' + formParams?.id : '添加用户'"
      style="width: 620px"
    >
      <n-form
        :model="formParams"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="登录用户名" path="user_name">
          <n-input placeholder="登录用户名，不能重复" v-model:value="formParams.user_name" />
        </n-form-item>

        <n-form-item label="登录密码" path="password" v-if="formParams?.id === 0">
          <n-input placeholder="登录密码" v-model:value="formParams.password" />
        </n-form-item>

        <n-form-item label="姓名" path="nickname">
          <n-input placeholder="" v-model:value="formParams.nickname" />
        </n-form-item>

        <n-form-item label="绑定角色" path="role_id">
          <n-select v-model:value="formParams.role_id" :options="optionsRole" />
        </n-form-item>

        <!--        <n-form-item label="备注" path="remark">-->
        <!--          <n-input type="textarea" placeholder="请输入备注内容" v-model:value="formParams.remark" />-->
        <!--        </n-form-item>-->

        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="formParams.status" name="status">
            <n-radio-button
              v-for="status in statusOptions"
              :key="status.value"
              :value="status.value"
              :label="status.label"
            />
          </n-radio-group>
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, onMounted } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    UserList,
    RoleOption,
    UserEdit,
    ResetPassword,
  } from '@/api/system/role';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { cloneDeep } from 'lodash-es';
  import { statusOptions } from '@/enums/optionsiEnum';
  import { getRandomString } from '@/utils/character';
  import { delNullProperty } from '@/utils/array';

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = ref<any>();
  const optionsRole = ref<any>();
  const dialog = useDialog();

  const defaultState = {
    avatar: '',
    id: 0,
    nickname: '',
    roleName: '',
    role_id: null,
    status: 1,
    user_name: '',
    password: '',
  };

  const actionColumn = reactive({
    width: 200,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: function () {
              return record.role_id !== 1;
            },
          },
          // {
          //   type: 'warning',
          //   label: '重置密码',
          //   onClick: handleResetPassword.bind(null, record),
          //   ifShow: function () {
          //     return record.role_id !== 1;
          //   },
          // },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    return await UserList(delNullProperty({ ...res }));
  };

  function addTable() {
    showModal.value = true;
    formParams.value = cloneDeep(defaultState);
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        UserEdit(formParams.value)
          .then((_res) => {
            message.success('操作成功');
            setTimeout(() => {
              showModal.value = false;
              reloadTable();
            });
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    showModal.value = true;
    formParams.value = cloneDeep(record);
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    message.info('点击了删除');
  }

  function handleResetPassword(record: Recordable) {
    console.log('handleResetPassword', record);

    record.password = getRandomString(12);
    dialog.warning({
      title: '警告',
      content: '你确定要重置密码？\r\n重置成功后密码为：' + record.password + '\r\n 请先保存',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        ResetPassword(record).then((_res) => {
          message.success('操作成功');
          reloadTable();
        });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  onMounted(async () => {
    optionsRole.value = await RoleOption();
  });
</script>

<style lang="less" scoped></style>
