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

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

import { onMounted, ref } from 'vue';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getDictListApi } from '#/api/dict';
import {
  deleteProductApi,
  editProductApi,
  getProductAndScqyListApi,
} from '#/api/product';
import { $t } from '#/locales';

import AddLinkModal from './add-link-modal.vue';
import ProductDetail from './detail.vue';
import ProductForm from './form.vue';

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

// 新增关联组件ref
const addLinkModalRef = ref<InstanceType<typeof AddLinkModal>>();
const detailModalRef = ref<InstanceType<typeof ProductDetail>>();

const jjlxOptions = ref<any[]>([]);
const cplbOptions = ref<any[]>([]);

onMounted(async () => {
  try {
    const [jjlxRes, cplbRes] = await Promise.all([
      getDictListApi({ groupname: 'product_jjlx', rows: 999, pageindex: 1 }),
      getDictListApi({ groupname: 'product_cplb', rows: 999, pageindex: 1 }),
    ]);

    jjlxOptions.value = (jjlxRes.Data || []).map((item: any) => ({
      label: item.title,
      value: item.substance,
    }));
    cplbOptions.value = (cplbRes.Data || []).map((item: any) => ({
      label: item.title,
      value: item.substance,
    }));
  } catch (error) {
    console.error('获取字典数据失败', error);
  }
});

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: true,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  schema: [
    {
      component: 'Input',
      fieldName: 'productsname',
      label: '产品名称',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'productsmodel',
      label: '产品型号',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'productsjjlx',
      label: '机具类型',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        clearable: true,
        options: jjlxOptions,
      },
    },
    {
      component: 'Input',
      fieldName: 'scqyinfomc',
      label: '生产企业',
      componentProps: {
        placeholder: $t('ui.placeholder.input'),
        clearable: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'productscategory',
      label: '产品类别',
      componentProps: {
        placeholder: $t('ui.placeholder.select'),
        clearable: true,
        options: cplbOptions,
      },
    },
  ],
  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,
          ...formValues,
        };

        // 如果是经销商且不是管理员，添加经销商筛选条件
        if (userStore.isDLSNotAdmin) {
          queryParams.productsmerchantid =
            userStore.userInfo?.workeruserid || '';
        }

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

  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { title: '产品名称', field: 'productsname', sortable: true },
    { title: '产品型号', field: 'productsmodel', sortable: true },
    { title: '机具类型', field: 'productsjjlx', sortable: true },
    {
      title: '产品类别',
      field: 'productscategory',
      sortable: true,
    },
    { title: '生产企业', field: 'scqyinfomc', sortable: true },
    // { title: '产品sn号', field: 'productssn' },
    // { title: '品目', field: 'productspm', sortable: true },
    // { title: '一级分类', field: 'productsfl1', sortable: true },
    // { title: '二级分类', field: 'productsfl2', sortable: true },
    // { title: '分档名称', field: 'productsfdmc', sortable: true },
    // { title: '分档编号', field: 'productsfdbh', sortable: true },
    {
      title: '产品原价',
      field: 'productsprice',
      formatter: formatMoney,
      sortable: true,
    },
    {
      title: '中央补贴金额',
      field: 'productszybt',
      formatter: formatMoney,
      sortable: true,
    },
    {
      title: '特殊县中央补贴金额',
      field: 'productstsxzybt',
      formatter: formatMoney,
      sortable: true,
    },
    { title: '创建时间', field: 'productsdate' },
    {
      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: ProductForm,
});

/* 创建 */
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) {
  detailModalRef.value?.openDetailModal(row);
}

function formatMoney(row: any) {
  return row.cellValue ? row.cellValue.toFixed(2) : '0.00';
}

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

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

/* 移除关联 */
async function handleRemoveLink(row: any) {
  try {
    await ElMessageBox.confirm(
      '确认要移除关联吗?移除后，小程序商城中，客户将无法购买该产品，请谨慎操作',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    );

    const productsmerchantidArr = row.productsmerchantid.split(',');

    const productsmerchantid = productsmerchantidArr.filter(
      (item: any) => item !== userStore.userInfo?.workeruserid,
    );

    const newProductsmerchantid = productsmerchantid.join(',');
    await editProductApi({
      'productsid.value': row.productsid,
      productsmerchantid: newProductsmerchantid || '',
    } as any);

    ElMessage.success('取消关联成功');
    gridApi.reload();
  } catch {}
}

/* 新增关联 */
function handleAddLink() {
  addLinkModalRef.value?.open();
}

/* 新增关联完成回调 */
function handleAddLinkFinish() {
  gridApi.reload();
}
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="产品列表">
      <template #toolbar-tools>
        <!--区别： 新增- 新增产品， 新增关联-新增产品和经销商关联 -->
        <el-button
          type="primary"
          @click="handleCreate"
          v-if="!userStore.isDLSNotAdmin"
        >
          新增
        </el-button>
        <el-button
          type="primary"
          @click="handleAddLink"
          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
          v-if="!userStore.isDLSNotAdmin"
          class="box-item"
          effect="dark"
          content="编辑"
          placement="top"
        >
          <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>
        <el-tooltip
          class="box-item"
          effect="dark"
          content="移除关联"
          placement="top"
          v-if="userStore.isDLSNotAdmin"
        >
          <el-button
            round
            @click="() => handleRemoveLink(row)"
            :icon="MdiDelete"
            class="!p-2"
          />
        </el-tooltip>
      </template>
    </Grid>
    <Modal @finish="handleFinish" />

    <!-- 新增关联弹窗组件 -->
    <AddLinkModal ref="addLinkModalRef" @finish="handleAddLinkFinish" />
    <!-- 详情弹窗组件 -->
    <ProductDetail ref="detailModalRef" />
  </Page>
</template>
