<script setup lang="tsx">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { NButton } from 'naive-ui';
import {
  delActivity,
  fetchAddActivity,
  fetchEditActivity,
  fetchGetActivityList
} from '@/service/api/operation/coupon-manage';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';
import { useTable } from '@/components/zt/Table/hooks/useTable';
const router = useRouter();
const isLimitReceiveNum = ref(false);
const isLimitInventory = ref(false);

const [registerModalTable, { refresh }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'activityId',
        component: 'NInput',
        label: '券ID'
      },
      {
        field: 'activityName',
        component: 'NInput',
        label: '名称'
      },
      {
        field: 'promotionType',
        component: 'NSelect',
        componentProps: {
          options: [
            { label: '满减券', value: 1 },
            { label: '立减券', value: 2 }
          ]
        },
        label: '类型'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '优惠券列表',
    minHeight: 400
  }
});

const [
  registerModalForm,
  {
    openModal: openModalForm,
    setFieldsValue: setModalFormValue,
    getFieldsValue: getModalFormValue,
    closeModal: closeModalForm,
    setSubLoading
  }
] = useModalFrom({
  modalConfig: {
    title: '优惠券',
    isShowHeaderText: true
  },
  formConfig: {
    schemas: [
      {
        field: 'id',
        label: 'ID',
        show: false,
        component: 'NInput'
      },

      {
        field: 'activityName',
        component: 'NInput',
        label: '活动名称',
        required: true,
        componentProps: {
          maxlength: 20
        }
      },
      {
        field: 'promotionType',
        component: 'NRadioGroup',
        label: '类型',
        required: true,
        defaultValue: 1,
        componentProps: {
          options: [
            {
              label: '满减券',
              value: 1
            },
            {
              label: '立减券',
              value: 2
            }
          ]
        }
      },
      {
        field: 'amountMoney',
        component: 'NInputNumber',
        label: '门槛（元）',
        required: true,
        ifShow: ({ model }) => model.promotionType === 1,
        componentProps: {
          min: 0,
          max: 1000,
          precision: 0
        }
      },
      {
        field: 'discountMoney',
        component: 'NInputNumber',
        label: '面额（元）',
        rules: { validator: validateDiscountMoney, trigger: 'input' },
        componentProps: {
          min: 0,
          max: 1000,
          precision: 0
        }
      },
      {
        field: 'inventory',
        component: 'NInputNumber',
        label: '总量（张）',
        required: true,
        render: ({ model, field }) => {
          return (
            <div class="flex items-center">
              <n-input-number
                v-model:value={model[field]}
                min={1}
                max={100000}
                disabled={isLimitInventory.value}
                clearable
              />
              <n-checkbox
                class="ml-6px"
                checked={isLimitInventory.value}
                onUpdateChecked={(val: any) => (isLimitInventory.value = val)((model[field] = 99999))}
              >
                不限制
              </n-checkbox>
            </div>
          );
        }
      },
      {
        field: 'limitReceiveNum',
        component: 'NInputNumber',
        label: '每人限领（张）',
        required: true,
        render: ({ model, field }) => {
          return (
            <div class="flex items-center">
              <n-input-number
                v-model:value={model[field]}
                min={1}
                max={model.inventory || 100000}
                disabled={isLimitReceiveNum.value}
                clearable
              />
              <n-checkbox
                class="ml-6px"
                checked={isLimitReceiveNum.value}
                onUpdateChecked={(val: any) => (isLimitReceiveNum.value = val)((model[field] = 99999))}
              >
                不限制
              </n-checkbox>
            </div>
          );
        }
      },
      {
        field: 'businessType',
        component: 'NRadioGroup',
        label: '使用限制',
        required: true,
        defaultValue: 'XSB',
        componentProps: {
          options: [
            {
              label: '星闪豹',
              value: 'XSB'
            }
          ]
        }
      },
      {
        field: 'expirationDate',
        component: 'NInputNumber',
        label: '券使用有效期',
        required: true,
        componentProps: {
          min: 0,
          max: 100000
        },
        render: ({ model, field }) => {
          return (
            <div class="flex items-center">
              领取后 <n-input-number v-model:value={model[field]} min={0} max={10000} clearable /> 天有效
            </div>
          );
        }
      }
    ],
    labelWidth: 120,
    layout: 'horizontal',
    gridProps: {
      cols: '1',
      itemResponsive: true
    }
  }
});

const tableColumns: NaiveUI.TableColumn<Api.goods.ShopCategory>[] = [
  {
    title: '券ID',
    align: 'center',
    key: 'activityId'
  },
  {
    title: '活动名称',
    align: 'center',
    key: 'activityName'
  },
  {
    title: '类型',
    align: 'center',
    key: 'promotionType',
    render: row => {
      return row.promotionType === 1 ? '满减券' : '无门槛券';
    }
  },
  {
    title: '门槛（元）',
    align: 'center',
    key: 'amountMoney'
  },
  {
    title: '面额（元）',
    align: 'center',
    key: 'discountMoney'
  },
  {
    title: '总量（张）',
    align: 'center',
    key: 'inventory',
    render: row => {
      return <div>{row.inventory || '不限制'}</div>;
    }
  },
  {
    title: '未发放（张）',
    align: 'center',
    key: 'inventoryActual',
    render: row => {
      return <div>{row.inventoryActual === -1 ? '-' : row.inventoryActual}</div>;
    }
  },
  {
    title: '每人限领（张）',
    align: 'center',
    key: 'limitReceiveNum',
    render: row => {
      return <div>{row.limitReceiveNum || '不限制'}</div>;
    }
  },
  {
    title: '券使用有效期',
    align: 'center',
    key: 'expirationDate'
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'updateTime'
  },
  {
    title: '操作',
    key: 'op',
    fixed: 'right',
    align: 'center',
    width: 230,
    render: row => (
      <div class="flex-center gap-8px">
        {
          <NButton type="primary" size="small" ghost onClick={() => handleRecord(row)}>
            查看领取情况
          </NButton>
        }
        {
          <NButton type="primary" size="small" ghost onClick={() => edit(row)}>
            编辑
          </NButton>
        }
        <NButton type="primary" size="small" ghost onClick={() => del(row)}>
          删除
        </NButton>
      </div>
    )
  }
];

function handleRecord(row: any) {
  if (!row.activityId) {
    window.$message?.error('订单异常');
  }
  router.push({
    path: '/operation/coupon-issuance',
    query: {
      activityId: row.activityId
    }
  });
}

// async function validatePrice(_: any, value: any) {
//   const form = await getModalFormValue();
//   if (value <= form.discountMoney) {
//     console.log(1111111);

//     return; // 验证通过时返回undefined
//   }

//   throw new Error('应小于等于面额'); // 验证失败时抛出错误
// }
async function validateDiscountMoney(_: any, value: any) {
  const form = await getModalFormValue();
  if (value <= form.amountMoney || form.promotionType === 2) {
    return; // 验证通过时返回undefined
  }
  throw new Error('需要小于等于门槛金额。数值范围0-1000，整数'); // 验证失败时抛出错误
}

async function edit(row: Api.goods.ShopCategory) {
  if (row.inventoryActual < row.inventoryTotal) {
    window.$dialog?.info({
      title: '提示',
      content: '已有人领取，不允许修改',
      positiveText: '确定'
    });
    return;
  }
  openModalForm(row);
  // setModalProps({ title: `修改${Number(row.level)}级分类` });
  setModalFormValue(row);
}
function add(row: Api.goods.ShopCategory) {
  openModalForm();
  console.log(row, 'row-key');
  // updateSchema({ field: 'iconUrl', required: true });
  // setModalProps({ title: `新增二级分类` });
  // setModalFormValue({ parentName: row.name, name: '', parentId: row.id });
}
function del(row: Api.goods.ShopCategory) {
  if (row.inventoryActual < row.inventoryTotal) {
    window.$dialog?.info({
      title: '提示',
      content: '已有人领取，不允许删除',
      positiveText: '确定'
    });
    return;
  }
  window.$dialog?.info({
    title: '删除活动',
    content: '你确定要删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { error } = await delActivity(row.id);
      if (!error) {
        refresh();
      }
    }
  });
}

async function handleSubmit() {
  const form = await getModalFormValue();
  setSubLoading(false);
  if (isLimitInventory.value) {
    form.inventory = 0;
  }
  if (isLimitReceiveNum.value) {
    form.limitReceiveNum = 0;
  }
  if (!form.id) {
    const { error } = await fetchAddActivity(form);
    if (error) {
      return;
    }
  } else {
    // 修改
    const { error } = await fetchEditActivity(form);
    if (error) {
      return;
    }
  }
  closeModalForm();
  refresh();
}
</script>

<template>
  <LayoutTable>
    <ZTable
      :show-table-action="false"
      :columns="tableColumns"
      :api="fetchGetActivityList"
      @register="registerModalTable"
      @add="add"
    ></ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
