<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :flex-height="false"
        :pagination="{ pageSize: userId > 0 ? 10 : 15 }"
        :resizeHeightOffset="-500"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建模板
          </n-button>
        </template>
      </BasicTable>

      <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="modalTitle">
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="模板名称" path="name">
            <n-input placeholder="请输入名称" v-model:value="formParams.name" />
          </n-form-item>
          <n-form-item label="备注" path="remark">
            <n-input type="textarea" placeholder="请输入备注" v-model:value="formParams.remark" />
          </n-form-item>

          <n-form-item label="排序" path="sort">
            <n-input v-model:value="formParams.sort" type="text" placeholder="越小越靠前" />
          </n-form-item>

          <n-form-item label="状态" path="status">
            <n-radio-group v-model:value="formParams.status">
              <n-space>
                <n-radio label="正常" value="1" />
                <n-radio label="禁用" value="2" />
              </n-space>
            </n-radio-group>
          </n-form-item>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>

    <RetrofitModal ref="RetrofitModalRef" :groupId="groupId" />
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    getRetrofitGroupList,
    RetrofitGroupDelete,
    RetrofitGroupEdit,
  } from '@/api/echarts/rechargeList';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import RetrofitModal from './modal/modal.vue';
  interface Props {
    userId?: number | string;
  }
  const props = withDefaults(defineProps<Props>(), { userId: 0 });
  const message = useMessage();

  const modalTitle = ref('新建模板');
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const rules = {
    name: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入名称',
    },
  };
  function addTable() {
    showModal.value = true;
    modalTitle.value = '新建模板';
    formParams.value = {
      id: 0,
      name: '',
      remark: '',
      status: '1',
      sort: 0,
    };
  }

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams.value:' + JSON.stringify(formParams.value));
        formParams.value.status = Number(formParams.value.status);
        formParams.value.sort = Number(formParams.value.sort);
        RetrofitGroupEdit(formParams.value)
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('操作成功');
          })
          .catch((_e: Error) => {
            // message.error(e.message ?? '操作失败');
          });
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  const dialog = useDialog();
  const statusValue = ref('1');
  const actionRef = ref();
  const formParams = ref({
    id: 0,
    name: '',
    remark: '',
    status: statusValue.value,
    sort: 0,
  });

  const params = ref({
    id: 0,
    name: '',
    remark: '',
    status: statusValue.value,
    sort: 0,
  });

  const formRef = ref({});
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '管理配装',
            onClick: handleConf.bind(null, record),
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  function handleConf(record: Recordable) {
    console.log('handleConf', record);
    openUserModal(record.id);
  }

  function handleEdit(record: Recordable) {
    console.log('handleEdit', record);
    showModal.value = true;
    modalTitle.value = '编辑模板 ID：' + record.id;
    formParams.value = {
      id: record.id,
      name: record.name,
      remark: record.remark,
      status: record.status.toString(),
      sort: record.sort,
    };
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.warning({
      title: '警告',
      content: '你确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        RetrofitGroupDelete(record)
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('操作成功');
            reloadTable();
          })
          .catch((e: Error) => {
            // message.error(e.message ?? '操作失败');
          });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  const dataSource = ref({
    successful_order: 0,
    transaction_money: 0,
  });

  const loadDataTable = async (res) => {
    dataSource.value = await getRetrofitGroupList({ ...res });
    return dataSource.value;
  };

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  const RetrofitModalRef = ref();
  const groupId = ref(0);
  function openUserModal(id) {
    groupId.value = id;
    const { openDrawer } = RetrofitModalRef.value;
    openDrawer();
  }
</script>

<style lang="less" scoped></style>
