<!-- 用户编辑弹窗 -->
<template>
  <a-drawer
    :width="700"
    :visible="visible"
    :confirm-loading="loading"
    :maxable="maxAble"
    :title="'成员管理'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    :footer="null"
  >
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="userId"
      :columns="columns"
      :datasource="datasource"
      v-model:selection="selection"
      :where="defaultWhere"
      cache-key="proSystemUserTable"
    >
      <template #toolbar>
        <a-space>
          <!--          <UserMerchantClerk @select="onSelect" />-->
          <a-input
            allow-clear
            v-model="userId"
            @change="getUserId"
            placeholder="请输入用户ID"
          />
          <a-button type="primary" class="ele-btn-icon" @click="save">
            <template #icon>
              <plus-outlined />
            </template>
            <span>添加</span>
          </a-button>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'nickname'">
          <a-tooltip :title="`ID：${record.userId}`">
            <a-avatar
              :size="30"
              :src="`${record.user?.avatar}`"
              style="margin-right: 4px"
            >
              <template #icon>
                <UserOutlined />
              </template>
            </a-avatar>
            {{ record.user?.nickname }}
          </a-tooltip>
        </template>
        <template v-if="column.key === 'username'">
          {{ record.user?.username }}
        </template>
        <template v-if="column.key === 'phone'">
          {{ record.user?.phone }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a class="ele-text-danger" @click="remove(record)">移除</a>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </a-drawer>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, EleProTable } from 'ele-admin-pro';
  import type {
    MerchantClerk,
    MerchantClerkParam
  } from '@/api/merchant/clerk/model';
  import {
    ColumnItem,
    DatasourceFunction
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { UserOutlined } from '@ant-design/icons-vue';
  import {
    addMerchantClerk,
    pageMerchantClerks,
    removeMerchantClerk
  } from '@/api/merchant/clerk';
  // import UserMerchantClerk from '@/components/UserChoose/index.vue';

  const useForm = Form.useForm;

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: MerchantClerk | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: '姓名',
      key: 'nickname',
      dataIndex: 'nickname'
    },
    {
      title: '登录账号',
      key: 'username',
      dataIndex: 'username'
    },
    {
      title: '手机号',
      key: 'phone',
      dataIndex: 'phone'
    },
    {
      title: '操作',
      key: 'action',
      align: 'center'
    }
  ]);

  // 默认搜索条件
  const defaultWhere = reactive({
    username: '',
    nickname: ''
  });

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    where = {};
    where.merchantCode = props.data?.merchantCode;
    return pageMerchantClerks({ ...where, ...orders, page, limit });
  };
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  /* 搜索 */
  const reload = (where?: MerchantClerkParam) => {
    tableRef?.value?.reload({ where: where });
  };

  // 用户信息
  const clerk = reactive<MerchantClerk>({
    clerkId: undefined,
    // 商户名称
    merchantName: '',
    // 商户编号
    merchantCode: '',
    // 店员真实姓名
    realName: '',
    // 用户id
    userId: undefined,
    // 昵称
    nickname: '',
    // 登录账号
    username: '',
    // 创建时间
    createTime: ''
  });

  // 请求状态
  const loading = ref(true);
  // 是否显示最大化切换按钮
  const maxAble = ref(true);
  // 选项卡位置
  const { resetFields } = useForm(clerk);
  // 选中用户
  const userId = ref(undefined);

  // const onSelect = (user) => {
  //   userId.value = user.userId;
  // };
  const getUserId = (e) => {
    userId.value = e.target.value;
  };

  // 添加门店成员
  const save = () => {
    const data = {
      merchantCode: props.data?.merchantCode,
      userId: userId.value
    };
    addMerchantClerk(data)
      .then((msg) => {
        message.success(msg);
        reload();
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  /* 删除单个 */
  const remove = (row: MerchantClerk) => {
    console.log(row);
    const hide = message.loading('请求中..', 0);
    removeMerchantClerk(row.clerkId)
      .then(() => {
        hide();
        message.success('移除成功');
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          loading.value = false;
          assignObject(clerk, props.data);
          reload();
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 100px;
  }
  .important {
    font-weight: bold;
  }
</style>
