<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: 10 }"
        :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="type">
            <n-select
              v-model:value="formParams.type"
              placeholder="选择类型"
              :options="typeOptions"
              @update:value="handleMaterialTypeChange"
            />
          </n-form-item>

          <n-form-item label="关联ID" path="mid">
            <n-input-number v-model:value="formParams.mid" clearable :showButton="false" />
          </n-form-item>

          <n-form-item label="操作数量" path="nums">
            <n-input-number
              v-model:value="formParams.nums"
              :max="99999999"
              :min="-99999999"
              clearable
            />
          </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>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { SelectOption, useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getRetrofitList, RetrofitDelete, RetrofitEdit } from '@/api/echarts/rechargeList';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';

  const typeOptions = ref([
    {
      value: 1,
      label: '材料',
    },
    // {
    //   value: 2,
    //   label: '装备',
    // },
    // {
    //   value: 3,
    //   label: '钻石',
    // },
    // {
    //   value: 4,
    //   label: '金币',
    // },
  ]);

  interface Props {
    groupId?: number | string;
  }
  const props = withDefaults(defineProps<Props>(), { groupId: 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 = {
      groupId: 0,
      id: 0,
      name: '',
      type: null,
      mid: null,
      status: '1',
      nums: 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.groupId = props.groupId;
        RetrofitEdit(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: '',
    type: null,
    mid: null,
    status: statusValue.value,
    nums: 0,
    groupId: props.groupId,
  });

  const params = ref({
    id: 0,
    name: '',
    type: null,
    mid: null,
    status: statusValue.value,
    nums: 0,
    groupId: props.groupId,
  });

  function handleMaterialTypeChange(value: string, _option: SelectOption) {
    console.log('value:' + value);

    if (value == '3') {
      formParams.value.mid = 1002;
      console.log(111);
    } else if (value == '4') {
      formParams.value.mid = 1001;
      console.log(222);
    } else {
      formParams.value.mid = null;
      console.log(333);
    }
  }

  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: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  function handleEdit(record: Recordable) {
    console.log('handleEdit', record);
    showModal.value = true;
    modalTitle.value = '编辑配装 ID：' + record.id;
    formParams.value = {
      id: record.id,
      name: record.name,
      type: record.type,
      status: record.status.toString(),
      mid: record.mid,
      nums: record.nums,
      groupId: record.groupId,
    };
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.warning({
      title: '警告',
      content: '你确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        RetrofitDelete(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 getRetrofitList({ ...res, ...{ groupId: props.groupId } });
    return dataSource.value;
  };

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

  function reloadTable() {
    actionRef.value.reload();
  }
</script>

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