<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal } from '@vben/common-ui';
import { MdiDelete, MdiDetail, MdiEdit } from '@vben/icons';
import { useUserStore } from '@vben/stores';
import { parseQueryValues } from '@vben/utils';

import { ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteCustomerApi, getCustomerListApi } from '#/api/user';
import { $t } from '#/locales';

import CustomerForm from './form.vue';

// 获取用户信息
const userStore = useUserStore();

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'usersname',
      label: '用户名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
    },
    // {
    //   component: 'Input',
    //   fieldName: 'scqyinfomc',
    //   label: '生产企业',
    //   componentProps: {
    //     placeholder: $t('ui.placeholder.input'),
    //     allowClear: true,
    //   },
    // },
    {
      component: 'Input',
      fieldName: 'usersphone',
      label: '用户手机号',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        allowClear: true,
      },
    },
    // {
    //   component: 'Select',
    //   fieldName: 'usersnature',
    //   label: '用户性质',
    //   // 设置默认值 - 当为代理商且非管理员时默认为购机者
    //   defaultValue: userStore.isDLSNotAdmin ? '购机者' : undefined,
    //   // 如果是代理商且非管理员，禁用该字段
    //   disabled: userStore.isDLSNotAdmin,
    //   componentProps: {
    //     placeholder: $t('ui.placeholder.select'),
    //     allowClear: true,
    //     options: [
    //       { label: '购机者', value: '购机者' },
    //       { label: '经销商', value: '经销商' },
    //     ],
    //   },
    // },
  ],
  wrapperClass: 'grid-cols-1 md:grid-cols-3 lg:grid-cols-5',
};

const gridOptions: VxeGridProps<any> = {
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
  height: 'auto',
  exportConfig: {},
  pagerConfig: {},
  rowConfig: {
    isHover: true,
  },
  stripe: true,

  proxyConfig: {
    response: {
      result: 'Data',
      total: 'Total',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        // 构建查询参数
        const queryParams: any = {
          pageindex: page.currentPage,
          rows: page.pageSize,
          usersnature: '购机者',
          ...parseQueryValues(formValues),
        };

        // 如果是代理商且非管理员，添加上级用户id查询条件
        if (userStore.isDLSNotAdmin && userStore.userInfo?.workeruserid) {
          queryParams['userssuperiorid.value'] =
            userStore.userInfo.workeruserid;
        }

        return await getCustomerListApi(queryParams);
      },
    },
  },

  columns: [
    { title: '序号', type: 'seq', width: 50 },
    // { title: '用户id', field: 'usersid', sortable: true },
    // { title: '微信openid', field: 'usersopenid', sortable: true },
    { title: '用户名称', field: 'usersname', sortable: true },
    { title: '用户性质', field: 'usersnature', sortable: true, width: 120 },
    { title: '用户类型', field: 'userstype', sortable: true, width: 120 },
    { title: '生产企业', field: 'scqyinfomc', sortable: true, width: 120 },
    // { title: '用户证件号码', field: 'usersidcardnumber' },
    // { title: '用户开户银行名称', field: 'usersbankname' },
    // { title: '用户开户银行账号', field: 'usersbanknumber' },
    { title: '用户手机号', field: 'usersphone', sortable: true, width: 200 },
    { title: '用户地址', field: 'usersaddress', sortable: true },
    { title: '用户邮箱', field: 'usersemail', sortable: true },
    // { title: '用户联系手机号', field: 'userscontactphone' },
    // { title: '用户联系邮箱', field: 'userscontactemail' },
    // { title: '用户联系地址', field: 'userscontactaddress' },
    {
      title: '操作',
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      width: 150,
    },
  ],
};

const gridEvents: VxeGridListeners<any> = {
  cellDblclick: ({ row }) => {
    handleDetail(row);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions,
  formOptions,
});

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  closeOnClickModal: false,
  closeOnPressEscape: false,
  connectedComponent: CustomerForm,
});

/* 创建 */
function handleCreate() {
  modalApi.setState({ showCancelButton: true });
  modalApi.setData({ formType: 'create' }).open();
}

/* 编辑 */
function handleEdit(row: any) {
  modalApi.setState({ showCancelButton: true });
  modalApi.setData({ formType: 'edit', row }).open();
}

/* 详情 */
function handleDetail(row: any) {
  modalApi.setState({ showCancelButton: false });
  modalApi.setData({ formType: 'detail', row }).open();
}

function handleFinish() {
  gridApi.reload();
}

/* 删除 */
async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm('确认要删除该客户吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await deleteCustomerApi({ 'usersid.value': row.usersid });
    ElMessage.success('删除成功');
    gridApi.reload();
  } catch (error) {
    console.error(error);
  }
}
</script>

<template>
  <Grid
    table-title="客户列表"
    style="height: calc(var(--vben-content-height) - 72px)"
  >
    <template #toolbar-tools>
      <el-button
        type="primary"
        @click="handleCreate"
        v-if="!userStore.isDLSNotAdmin"
      >
        新增
      </el-button>
    </template>
    <template #action="{ row }">
      <el-tooltip class="box-item" effect="dark" content="详情" placement="top">
        <el-button
          round
          @click="() => handleDetail(row)"
          :icon="MdiDetail"
          class="!p-2"
        />
      </el-tooltip>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="编辑"
        placement="top"
        v-if="!userStore.isDLSNotAdmin"
      >
        <el-button
          round
          @click="() => handleEdit(row)"
          :icon="MdiEdit"
          class="!p-2"
        />
      </el-tooltip>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="删除"
        placement="top"
        v-if="!userStore.isDLSNotAdmin"
      >
        <el-button
          round
          @click="() => handleDelete(row)"
          :icon="MdiDelete"
          class="!p-2"
        />
      </el-tooltip>
    </template>
  </Grid>
  <Modal @finish="handleFinish" />
</template>
