<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :customRow="customRow"
        tool-class="ele-toolbar-form"
        class="sys-org-table"
        v-model:selection="selection"
      >
        <template #toolbar>
          <search
            @search="reload"
            :selection="selection"
            @add="openEdit"
            @remove="removeBatch"
            @batchMove="openMove"
          />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userStatus'">
            <a-tag v-if="record.isDelete === 1" color="red">已删除</a-tag>
            <a-tag v-else color="green">正常</a-tag>
          </template>
          <template v-if="column.key === 'money'">
            {{ record.money }}
          </template>
          <template v-if="column.key === 'action'">
            <a @click="openEdit(record)" class="ele-text-primary">
              <EditOutlined/>
              编辑
            </a>
            <a-divider type="vertical"/>
            <a-popconfirm
              title="确定要删除此分销商用户吗？"
              @confirm="remove(record)"
              placement="topRight"
            >
              <a class="ele-text-danger">
                <DeleteOutlined/>
                删除
              </a>
            </a-popconfirm>
          </template>
        </template>
      </ele-pro-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <ShopDealerUserEdit v-model:visible="showEdit" :data="current" @done="reload"/>
  </a-page-header>
</template>

<script lang="ts" setup>
import {createVNode, ref} from 'vue';
import {message, Modal} from 'ant-design-vue';
import {
  ExclamationCircleOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue';
import type {EleProTable} from 'ele-admin-pro';
import {toDateString} from 'ele-admin-pro';
import type {
  DatasourceFunction,
  ColumnItem
} from 'ele-admin-pro/es/ele-pro-table/types';
import Search from './components/search.vue';
import {getPageTitle} from '@/utils/common';
import ShopDealerUserEdit from './components/shopDealerUserEdit.vue';
import {pageShopDealerUser, removeShopDealerUser, removeBatchShopDealerUser} from '@/api/shop/shopDealerUser';
import type {ShopDealerUser, ShopDealerUserParam} from '@/api/shop/shopDealerUser/model';

// 表格实例
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

// 表格选中数据
const selection = ref<ShopDealerUser[]>([]);
// 当前编辑数据
const current = ref<ShopDealerUser | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示批量移动弹窗
const showMove = ref(false);
// 加载状态
const loading = ref(true);

// 表格数据源
const datasource: DatasourceFunction = ({
                                          page,
                                          limit,
                                          where,
                                          orders,
                                          filters
                                        }) => {
  if (filters) {
    where.status = filters.status;
  }
  where.type = 0;
  return pageShopDealerUser({
    ...where,
    ...orders,
    page,
    limit
  });
};

// 表格列配置
const columns = ref<ColumnItem[]>([
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    align: 'center',
    width: 80,
    fixed: 'left'
  },
  {
    title: '用电户号',
    dataIndex: 'qrcode',
    key: 'qrcode',
    align: 'center',
    width: 120
  },
  {
    title: '单位名称',
    key: 'userInfo',
    align: 'left',
    width: 200,
    fixed: 'left',
    customRender: ({record}) => {
      return `${record.realName || ''} (${record.mobile || ''})`;
    }
  },
  {
    title: '电量',
    key: 'money',
    align: 'center',
    width: 180
  },
  {
    title: '供电局',
    key: 'money4',
    align: 'center'
  },
  {
    title: '供电分局',
    key: 'money3',
    align: 'center'
  },
  {
    title: '供电所',
    key: 'money2',
    align: 'center'
  },
  {
    title: '渠道负责人',
    key: 'comments',
    align: 'center'
  },
  {
    title: '状态',
    key: 'userStatus',
    align: 'center',
    width: 100,
    customRender: ({record}) => {
      if (record.isDelete === 1) {
        return {type: 'tag', props: {color: 'red'}, children: '已删除'};
      }
      return {type: 'tag', props: {color: 'green'}, children: '正常'};
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    width: 120,
    sorter: true,
    ellipsis: true,
    customRender: ({text}) => text ? toDateString(text, 'yyyy-MM-dd') : '-'
  },
  {
    title: '操作',
    key: 'action',
    width: 220,
    fixed: 'right',
    align: 'center',
    hideInSetting: true
  }
]);

/* 搜索 */
const reload = (where?: ShopDealerUserParam) => {
  selection.value = [];
  tableRef?.value?.reload({where: where});
};

/* 打开编辑弹窗 */
const openEdit = (row?: ShopDealerUser) => {
  current.value = row ?? null;
  showEdit.value = true;
};

/* 打开批量移动弹窗 */
const openMove = () => {
  showMove.value = true;
};

/* 删除单个 */
const remove = (row: ShopDealerUser) => {
  if (!row.id) {
    message.error('删除失败：缺少必要参数');
    return;
  }

  const hide = message.loading('正在删除分销商用户...', 0);
  removeShopDealerUser(row.id)
    .then((msg) => {
      hide();
      message.success(msg || '删除成功');
      reload();
    })
    .catch((e) => {
      hide();
      message.error(e.message || '删除失败');
    });
};

/* 批量删除 */
const removeBatch = () => {
  if (!selection.value.length) {
    message.error('请至少选择一条数据');
    return;
  }

  const validIds = selection.value.filter(d => d.id).map(d => d.id);
  if (!validIds.length) {
    message.error('选中的数据中没有有效的ID');
    return;
  }

  Modal.confirm({
    title: '批量删除确认',
    content: `确定要删除选中的 ${validIds.length} 条分销商用户记录吗？此操作不可恢复。`,
    icon: createVNode(ExclamationCircleOutlined),
    maskClosable: true,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: () => {
      const hide = message.loading(`正在删除 ${validIds.length} 条记录...`, 0);
      removeBatchShopDealerUser(validIds)
        .then((msg) => {
          hide();
          message.success(msg || `成功删除 ${validIds.length} 条记录`);
          selection.value = [];
          reload();
        })
        .catch((e) => {
          hide();
          message.error(e.message || '批量删除失败');
        });
    }
  });
};

/* 查询 */
const query = () => {
  loading.value = true;
};

/* 自定义行属性 */
const customRow = (record: ShopDealerUser) => {
  return {
    // 行点击事件
    onClick: () => {
      // console.log(record);
    },
    // 行双击事件
    onDblclick: () => {
      openEdit(record);
    }
  };
};
query();
</script>

<script lang="ts">
export default {
  name: 'ShopDealerUser'
};
</script>

<style lang="less" scoped>
.sys-org-table {
  :deep(.ant-table-thead > tr > th) {
    background-color: #fafafa;
    font-weight: 600;
  }

  :deep(.ant-table-tbody > tr:hover > td) {
    background-color: #f8f9fa;
  }
}

.detail-item {
  p {
    margin: 4px 0;
    color: #666;
  }

  strong {
    color: #1890ff;
    font-size: 14px;
  }
}

.ele-text-primary {
  color: #1890ff;

  &:hover {
    color: #40a9ff;
  }
}

.ele-text-info {
  color: #13c2c2;

  &:hover {
    color: #36cfc9;
  }
}

.ele-text-danger {
  color: #ff4d4f;

  &:hover {
    color: #ff7875;
  }
}
</style>
