<template>
  <div>
    <n-card
      :bordered="true"
      title="玩家材料列表"
      class="proCard mt-2"
      size="small"
      :segmented="{ content: true }"
    >
      <template #header-extra>
        <n-space>
          <!--          <n-button strong secondary type="info" @click="showModal">材料对照表</n-button>-->
          <n-button strong secondary type="success" @click="openUpdatePlayerMaterial"
            >玩家材料添加</n-button
          >
        </n-space>
      </template>
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="formRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <n-data-table
        :columns="columns"
        :data="data"
        :pagination="paginationReactive"
        show-size-picker
        :loading="loading"
        ref="actionRef"
      />
    </n-card>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      title="玩家道具添加"
      style="width: 620px"
    >
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="选择类型" path="type">
          <n-select
            v-model:value="formParams.type"
            placeholder="选择类型"
            :options="options"
            @update:value="handleMaterialTypeChange"
          />
        </n-form-item>
        <n-form-item label="选择道具" path="id">
          <n-select
            v-model:value="formParams.id"
            placeholder="选择道具"
            :options="materialOptions"
            @update:value="handleMaterialChange"
          />
        </n-form-item>
        <n-form-item label="数量" path="num">
          <n-input-number
            placeholder="请输入数量"
            v-model:value="formParams.num"
            :max="99999999"
            :min="-99999999"
          />
        </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>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted, h } from 'vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { useMessage, FormItemRule, SelectOption, NButton } from 'naive-ui';
  import { filterArray, findIndex, objDalEmpty } from '@/utils/array';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { getAllMaterials, addMaterial } from '@/api/account/list';
  import { typeMaps } from '@/convert/material/map';
  interface Props {
    userId?: number | string;
    userInfo?: any;
  }

  const props = withDefaults(defineProps<Props>(), {
    userId: 0,
    userInfo: userInfoObj,
  });

  // 装备查询数据
  const data = ref();
  const originalData = ref();
  const loading = ref(false);
  const message = useMessage();

  const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 30, 40, 100],
    showSizePicker: true,
    onChange: (page: number) => {
      paginationReactive.page = page;
    },
    onUpdatePageSize: (pageSize: number) => {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
    },
  });

  const rules = {
    id: {
      trigger: ['blur', 'input'],
      validator(rule: FormItemRule, value: number) {
        if (value == undefined) {
          return true;
        }
        if (!/^\d*$/.test(value)) {
          return new Error('GID只能是数字');
        }
        return true;
      },
    },
    equipId: {
      trigger: ['blur', 'input'],
      validator(rule: FormItemRule, value: number) {
        if (value == undefined) {
          return true;
        }
        if (!/^\d*$/.test(value)) {
          return new Error('装备ID只能是数字');
        }
        return true;
      },
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'id',
      component: 'NInput',
      label: '材料id',
      componentProps: {
        placeholder: '请输入材料id',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const actionRef = ref();

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

  const options = ref(typeMaps);

  const materialOptions = ref([]);

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  function openUpdatePlayerMaterial() {
    showModal.value = true;
  }

  const formRef: any = ref(null);
  let formParams = reactive<any>({
    type: null,
    id: null,
    num: 1,
  });
  function confirmForm(e) {
    e.preventDefault();

    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));
        formParams.id = Number(formParams.id);
        if (formParams.id == null || formParams.id <= 0) {
          message.error('请先选择一个材料');
          return;
        }

        if (formParams.num == null || formParams.num == 0) {
          message.error('输入的数量是无效的');
          return;
        }

        addMaterial({
          ...{ user_id: Number(props.userId), id: formParams.id, count: formParams.num },
        })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });

        setTimeout(() => {
          showModal.value = false;
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleMaterialTypeChange(value: string, _option: SelectOption) {
    formParams.type = value;
    formParams.id = null;
    materialOptions.value = [];
    for (let i = 0; i < allMaterials.value[value].length; i++) {
      materialOptions.value.push({
        label:
          allMaterials.value[value][i].ItemName + '(' + allMaterials.value[value][i].ItemId + ')',
        value: allMaterials.value[value][i].ItemId,
      });
    }
  }

  function handleMaterialChange(value: string, option: SelectOption) {
    formParams.id = value;
  }

  function handleSubmit(values: Recordable) {
    values = objDalEmpty(values);
    // 如果没有搜索条件，则重置
    if (Object.keys(values).length === 0) {
      handleReset({});
      return;
    }
    data.value = filterArray(values, originalData.value);
  }

  function handleReset(_: Recordable) {
    loadDataTable({});
  }

  const idsMap = ref<any>([]);
  function genMaps() {
    idsMap.value = [];
    for (let i = 0; i < options.value.length; i++) {
      if (allMaterials.value[options.value[i].value] !== undefined) {
        let lists = allMaterials.value[options.value[i].value];
        for (let i2 = 0; i2 < lists.length; i2++) {
          idsMap.value.push({
            value: lists[i2].ItemId,
            label: lists[i2].ItemName,
            pid: lists[i2].ItemType,
          });
        }
      }
    }
  }

  const columns = [
    {
      title: '材料ID',
      key: 'id',
      width: 160,
    },
    {
      title: '材料名称',
      key: 'name',
      width: 160,
      render: (rows, _) => {
        let index = findIndex(rows.id, idsMap.value);
        if (index === false) {
          return `-`;
        }
        return idsMap.value[index].label == undefined ? '--' : idsMap.value[index].label;
      },
    },
    {
      title: '持有数量',
      key: 'count',
      width: 160,
    },
    {
      title: '操作',
      key: 'actions',
      render(row) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: 'small',
            onClick: () => play(row),
          },
          { default: () => '添加' }
        );
      },
      width: 160,
    },
  ];

  function play(row) {
    showModal.value = true;
    let index = findIndex(row.id, idsMap.value);
    if (index === false || idsMap.value[index] === undefined) {
      message.error('材料读取异常');
      return;
    }
    handleMaterialTypeChange(idsMap.value[index].pid, null);
    formParams.id = row.id;
  }

  const allMaterials = ref<any>(null);
  type Item = {
    id: number;
    count: number;
  };

  const loadDataTable = async (_) => {
    loading.value = true;
    if (allMaterials.value === null) {
      allMaterials.value = await getAllMaterials({});
      genMaps();
    }
    let lists: Item[] = [];
    Object.keys(props.userInfo.materials).forEach((key) => {
      lists.push({
        id: Number(key),
        count: props.userInfo.materials[key],
      });
    });

    data.value = lists;
    originalData.value = lists;

    loading.value = false;
  };

  onMounted(async () => {
    if (props.userId < 1) {
      console.log('传入用户信息不正确，props.userId：', props.userId);
      return;
    }
    await loadDataTable({});
  });

  const fatherRefresh = () => {
    loadDataTable({});
  };

  defineExpose({ fatherRefresh });
</script>
