<template>
  <div>
    <n-card :bordered="false" class="proCard" title="兑换码批次">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="formRef2"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable"> 生成兑换码</n-button>
        </template>
      </BasicTable>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        preset="dialog"
        :title="title"
        style="width: 620px"
      >
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          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="cdk">
            <n-input placeholder="不填随机生成，填了只能生成一个" v-model:value="formParams.cdk" />
          </n-form-item>

          <n-form-item label="生成数量" path="num">
            <n-input-number
              placeholder="生成兑换码的数量"
              v-model:value="formParams.num"
              :min="1"
            />
          </n-form-item>

          <n-form-item label="服务器" path="server_ids">
            <n-select
              multiple
              v-model:value="formParams.server_ids"
              :options="serverOptions"
              @update:value="handleUpdateValue"
            />
          </n-form-item>

          <n-form-item label="兑换码类型" path="type_id">
            <n-space>
              <n-radio
                :checked="checkedValueRef === 1"
                value="1"
                name="type_id"
                @change="handleChange"
                :disabled="disabled"
              >
                全部玩家
              </n-radio>
              <n-radio
                :checked="checkedValueRef === 2"
                value="2"
                name="type_id"
                @change="handleChange"
                :disabled="disabled"
              >
                指定玩家
              </n-radio>
            </n-space>
          </n-form-item>

          <n-form-item label="openid" path="openid" :hidden="delaySendShow">
            <n-input placeholder="指定玩家openid" v-model:value="formParams.openid" />
          </n-form-item>

          <n-form-item label="可用次数" path="times">
            <n-input-number
              placeholder="生成兑换码可以使用的次数"
              :min="1"
              v-model:value="formParams.times"
            />
          </n-form-item>

          <n-form-item label="兑换材料" path="ext">
            <n-dynamic-input
              v-model:value="formParams.ext"
              preset="pair"
              key-placeholder="材料ID"
              value-placeholder="兑换数量"
            />
          </n-form-item>

          <n-form-item label="兑换装备" path="equipment">
            <n-input
              type="textarea"
              placeholder="请填写装备ID 多个用,隔开（英文逗号）"
              v-model:value="formParams.equipment"
            />
          </n-form-item>
          <n-form-item label="过期时间" path="expired_at">
            <n-date-picker
              type="datetime"
              placeholder="请选择兑换码过期时间"
              v-model:value="formParams.expired_at"
            />
          </n-form-item>

          <n-form-item label="生成人" path="operator">
            <n-input v-model:value="formParams.operator" :disabled="!active"/>
          </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-modal
        v-model:show="editModal"
        :show-icon="false"
        preset="dialog"
        :title="title"
        style="width: 620px"
      >
        <n-form
          :model="editFormParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-form-item label="兑换材料" path="ext">
            <n-dynamic-input
              v-model:value="formParams.ext"
              preset="pair"
              key-placeholder="材料ID"
              value-placeholder="兑换数量"
            />
          </n-form-item>

          <n-form-item label="兑换装备" path="equipment">
            <n-input
              type="textarea"
              placeholder="请填写装备ID 多个用,隔开（英文逗号）"
              v-model:value="formParams.equipment"
            />
          </n-form-item>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (editModal = 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 { useRouter } from 'vue-router';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { Add, List, BatchInvalid } from '@/api/cdk/cdk';
  import { columns } from './columns';
  import { useMessage, useDialog } from 'naive-ui';
  const formRef2 = ref({});
  const dialog = useDialog();
  import RetrofitModal from './modal/exchangeRecord.vue';
  import {useUserStoreWidthOut} from "@/store/modules/user";
  import {defRangeShortcuts} from "@/utils/dateUtil";
  const useUserStore = useUserStoreWidthOut();
  const serverOptions = useUserStore.config.server_option;
  const rules = {
    content: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮件内容',
    },
    title: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮件标题',
    },
    sender: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入发件人',
    },
    recievers: {
      required: true,
      trigger: ['blur', 'input'],
      message: '没有设置收件人',
    },
    key: {
      trigger: ['blur', 'input'],
      message: '请输入key',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'sn',
      component: 'NInput',
      label: '批次编号',
      componentProps: {
        placeholder: '请输入批次编号',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'name',
      component: 'NInput',
      label: '批次名称',
      componentProps: {
        placeholder: '请输入批次编号',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'created_at',
      component: 'NDatePicker',
      label: '生成日期',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];
  const title = ref('');
  const disabled = ref(false);
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const editModal = ref(false);

  const formBtnLoading = ref(false);

  interface FormParams {
  id: number | null;
  name: string;
  cdk: string;
  num: number | null;
  type_id: number;
  openid: string;
  times: number | null;
  expired_at: Date | null;
  operator: string;
  ext: { key: number; value: number; }[] | [];
  keys: string;
  equipment: string;
  server_ids: number[] | null;
}
  const resetFormParams:FormParams = {
    id: null,
    name: '',
    cdk: '',
    num: null,
    type_id: 1,
    openid: '',
    times: null,
    expired_at: null,
    operator: '',
    ext: [],
    keys: '',
    equipment: '',
    server_ids: null,
  };

  const formParams = ref(resetFormParams);
  const editFormParams = ref(resetFormParams);

  const params = ref({
    pageSize: 10,
  });

  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      let actions:{}[] = [];
      if (record.type_id == 1) {
        actions.push({
          label: '兑换码列表',
          onClick: handleRedeemCodeList.bind(null, record),
        });
      } else if (record.type_id == 2) {
        actions.push({
          label: '兑换记录',
          onClick: handleConf.bind(null, record),
        });
      }

      if (record.status == 1) {
        actions.push({
          label: '批次作废',
          color: '#CD1E1EFF',
          onClick: handleBatchInvalid.bind(null, record),
          disabled: record.status === 2
        });
      } else if (record.status == 2) {
        actions.push({
          label: '批次开启',
          onClick: handleBatchOpen.bind(null, record),
        });
      }
              
      // {
      //   label: '编辑',
      //   onClick: handleEdit.bind(null, record),
      // },

      return h(TableAction as any, {
        style: 'button',
        actions,
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const checkedValueRef = ref(1);
  const delaySendShow = ref(true);

  //兑换码列表
  const router = useRouter();
  function handleRedeemCodeList(record: Recordable) {
    router.push({
      name: 'cdk-redeemCodeList',
      params: {sn: record.sn},
    });
  } 
  
  //批次作废
  function handleBatchInvalid(record: Recordable) {
    console.log('handleInvalid', record);
    dialog.info({
      title: '提示',
      content: '确认作废该批次？',
      positiveText: '确认',
      negativeText: '取消',
      maskClosable: false,
      onPositiveClick: () => {
        BatchInvalid({sn:record.sn,status:2})
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('操作成功');
            setTimeout(() => {
              reloadTable();
            });
          })
          .catch((_e: Error) => {
            /*            message.error(e.message ?? '操作失败');*/
          });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  function handleBatchOpen(record: Recordable) {
    console.log('handleInvalid', record);
    dialog.info({
      title: '提示',
      content: '确认开启该批次？',
      positiveText: '确认',
      negativeText: '取消',
      maskClosable: false,
      onPositiveClick: () => {
        BatchInvalid({ sn: record.sn, status: 1 })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('操作成功');
            setTimeout(() => {
              reloadTable();
            });
          })
          .catch((_e: Error) => {
            /*            message.error(e.message ?? '操作失败');*/
          });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  //兑换记录
  const RetrofitModalRef = ref();
  const groupId = ref(0);
  function handleConf(record: Recordable) {
    console.log('handleConf', record);
    openUserModal(record.id);
  }

  function openUserModal(id) {
    groupId.value = id;
    const { openDrawer } = RetrofitModalRef.value;
    openDrawer();
  }

  function handleChange(e: Event) {
    checkedValueRef.value = Number((e.target as HTMLInputElement).value);
    if (checkedValueRef.value === 2) {
      delaySendShow.value = false;
    } else {
      delaySendShow.value = true;
    }
    formParams.value.type_id = checkedValueRef.value;
  } 
  
  function addTable() {
    title.value = '生成兑换码';
    showModal.value = true;

    formParams.value.name = '';
    formParams.value.cdk = '';
    formParams.value.num = null;
    formParams.value.type_id = 1;
    checkedValueRef.value = 1;
    delaySendShow.value = true;
    formParams.value.openid = '';
    formParams.value.times = null;
    formParams.value.expired_at = null;
    formParams.value.operator = useUserStore.getUserInfo.nickname;
    formParams.value.ext = [];
    formParams.value.keys = '';
    formParams.value.equipment = '';
    formParams.value.server_ids = null;

    formBtnLoading.value = false;
  }


  const loadDataTable = async (res) => {
    console.log('loadDataTable res：' + JSON.stringify(res));
    console.log('loadDataTable formParams：' + JSON.stringify(formParams.value));
    console.log('loadDataTable params：' + JSON.stringify(params.value));
    return await List({ ...formParams, ...params.value, ...res });
  };

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

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

  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        formBtnLoading.value = true;
        // 转换材料格式
        let material: { id: number; count: number; }[] = [];
        if (formParams.value.ext.length !== 0) {
          for (let i = 0; i < formParams.value.ext.length; i++) {
            material[i] = {
              id: parseInt(formParams.value.ext[i].key),
              count: parseInt(formParams.value.ext[i].value),
            };
          }
        }

        let equipment = formParams.value.equipment.trim().split(',');

        let equipmentInt:number[] = [];
        if (equipment.length > 0 && equipment[0] != '') {
          for (let i = 0; i < equipment.length; i++) {
            const parsedInt = parseInt(equipment[i]);
            if (!isNaN(parsedInt) && parsedInt > 0) {
              equipmentInt.push(parsedInt);
            }
          }
        }

        console.log('material:' + JSON.stringify(material));
        console.log('equipmentInt:' + JSON.stringify(equipmentInt));
        if (material.length == 0 && equipmentInt.length == 0) {
          message.error('请至少添加一个兑换材料或兑换装备');
          formBtnLoading.value = false;
          return;
        }

        console.log(
          'formParams:' +
            JSON.stringify({
              ...formParams.value,
              ...{ materials: { material: material, equipment: equipmentInt } },
            })
        );

        Add({
          ...formParams.value,
          ...{ materials: { material: material, equipment: equipmentInt } },
        })
          .then((_res) => {
            message.success('操作成功');
            formBtnLoading.value = false;
            setTimeout(() => {
              showModal.value = false;
              reloadTable();
            });
          })
          .catch((_error) => {
            // message.error(error.toString());
            formBtnLoading.value = false;
          });
      } else {
        message.error('请填写完整信息');
        formBtnLoading.value = false;
      }
    });
  }

  function handleEdit(record: Recordable) {
    title.value = '编辑兑换码';
    editModal.value = true;
    console.log(record)
    editFormParams.value.id = record.id;
    const award = JSON.parse(record.award)
    console.log(award)
    if (Array.isArray(award.material)) {
      award.material.forEach((item,i) => {
        editFormParams.value.ext[i] = { key: item.id, value: item.count };
      });
    }
    
    editFormParams.value.equipment = award.equipment.join(',');
    formBtnLoading.value = false;
  }

  function handleSubmit(values: Recordable) {
    params.value = { ...values, pageSize: 10 };
    console.log('handleSubmit values：' + JSON.stringify(values));
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = { ...values, pageSize: 10 };
    reloadTable();
  }
 



  function handleUpdateValue(value: string, _option) {
    let arr = value.toString().split(',');
    if (arr.length > 1 && arr.includes('0')) {
      message.error('选择全服时不能再选择其他服务器');
      return;
    }
  }
</script>

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