<template>
  <div>
    <BasicForm
      @register="register"
      @submit="handleSubmit"
      @reset="handleReset"
      :rules="rules"
      ref="actionRef"
    >
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
    <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="openUpdatePlayerEquip"
            >添加装备
          </n-button>
          <n-button strong secondary type="success" @click="openUpdatePlayerMaterial"
            >添加套装
          </n-button>
        </n-space>
      </template>
      <n-data-table
        :columns="equipmentColumns"
        :data="data"
        :pagination="paginationReactive"
        :loading="loading"
        ref="actionRef"
        style="white-space: pre-line"
      />
    </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="equipments">
          <n-select
            v-model:value="formParams.equipments"
            placeholder="选择套装"
            :options="options"
            @update:value="handleMaterialTypeChange"
            :render-option="renderOption"
          />
        </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="showAddEquip"
      :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="装备Id" path="equipments">
          <n-input-number
            v-model="equipInfo.equipId"
            :default-value="null"
            :min="0"
            @change="showEquipInfo"
          />
          <div :style="'display: ' + (equipInfo.equipId > 0 ? 'block' : 'none')">
            <span v-if="equipInfo.equipName === ''">(未找到对应装备)</span>

            <span v-else>
              (名称:{{ equipInfo.equipName }}&nbsp; 装备等级:{{ equipInfo.equipLevel }}&nbsp;
              装备星级:{{ equipInfo.equipStar }}&nbsp;)
            </span>
          </div>
        </n-form-item>
        <n-form-item label="数量" path="equipments">
          <n-input-number v-model:value="equipInfo.equipCount" :step="1" :min="1" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showAddEquip = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmAddEquipForm"
            >添加</n-button
          >
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, onMounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { useMessage, FormItemRule, NTooltip, SelectOption } from 'naive-ui';
  import { filterArray, findIndex, objDalEmpty } from '@/utils/array';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import { genEquipmentTableColumns } from '@/convert/equipment/equipment';
  import { equipmentColumns } from '@/convert/equipment/map';
  import { addEquipment, getAllEquipments } from '@/api/account/list';
  import { getAdminTemplate, TemplateYanYv } from '@/utils/admin';
  import { getWearRoles } from '@/convert/role/roles';
  interface Props {
    userId?: number | string;
    userInfo?: any;
  }

  // eslint-disable-next-line vue/require-valid-default-prop
  const props = withDefaults(defineProps<Props>(), {
    userId: 0,
    userInfo: userInfoObj,
  });
  const showModal = ref(false);
  const showAddEquip = ref(false);
  const formBtnLoading = ref(false);
  const equipInfo = ref({
    equipId: 0,
    equipCount: 1,
    equipName: '',
    equipLevel: 0,
    equipStar: 0,
    equipDes: '',
    allEquipments: {},
  });

  function showEquipInfo(value) {
    equipInfo.value.equipId = value;
    let info = equipInfo.value.allEquipments[equipInfo.value.equipId];
    if (info != undefined) {
      equipInfo.value.equipName = info.name;
      equipInfo.value.equipLevel = info.level;
      equipInfo.value.equipStar = info.star;
      equipInfo.value.equipDes = info.description;
    } else {
      equipInfo.value.equipName = '';
      equipInfo.value.equipLevel = 0;
      equipInfo.value.equipStar = 0;
      equipInfo.value.equipDes = '';
    }
  }

  function openUpdatePlayerMaterial() {
    showModal.value = true;
  }

  function openUpdatePlayerEquip() {
    showAddEquip.value = true;
  }

  const message = useMessage();

  let formParams = reactive({
    equipments: null,
  });

  const options = ref([
    {
      value: 0,
      label: '史诗套装',
    },
    {
      value: 1,
      label: '神话套装',
    },
    {
      value: 2,
      label: '稀有套装',
    },
  ]);

  const finalChoice = ref([
    [10504001, 10404001, 10104001, 20104001, 30104001, 40104001, 50104001, 60104001],
    // [
    //   10506070, 10406070, 10106070, 20306070, 20206070, 20106070, 30306070, 30206070, 30106070,
    //   40306070, 40206070, 40106070, 50306070, 50206070, 50106070, 60306070, 60206070, 60106070,
    // ],
    [
      10106001, 10406001, 10506001, 30106001, 30206001, 30306001, 20106001, 20206001, 20306001,
      20406001, 20506001, 40106001, 40206001, 40306001, 40406001, 40506001, 50106001, 50206001,
      50306001, 50406001, 50506001, 60106001, 60206001, 60306001,
    ],
    [10103001, 10403001, 10503001, 20103001, 30103001, 40103001, 50103001, 60103001],
  ]);

  function renderOption({ node, option }: { node: VNode; option: SelectOption }) {
    return h(NTooltip, null, {
      trigger: () => node,
      default: () =>
        option.label + '中包含以下装备：' + JSON.stringify(finalChoice.value[option.value]),
    });
  }

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

  const formRef: any = ref(null);

  function confirmForm(e) {
    e.preventDefault();

    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));

        if (formParams.equipments === null) {
          message.error('请先选择一个材料');
          return;
        }

        const index = findIndex(formParams.equipments, options.value);

        addEquipment({
          ...{
            user_id: Number(props.userId),
            name: options.value[index].label,
            equipments: finalChoice.value[formParams.equipments],
          },
        })
          .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;
    });
  }

  function confirmAddEquipForm(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
      if (!errors) {
        addEquipment({
          ...{
            user_id: Number(props.userId),
            id: equipInfo.value.equipId,
            count: equipInfo.value.equipCount,
          },
        })
          .then((res) => {
            console.log('_res:' + JSON.stringify(res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });
        setTimeout(() => {
          showAddEquip.value = false;
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

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

  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: 'GID',
      componentProps: {
        placeholder: '请输入GID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'equipId',
      component: 'NInput',
      label: '装备ID',
      componentProps: {
        placeholder: '请输入装备ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'name',
      component: 'NInput',
      label: '装备名称',
      componentProps: {
        placeholder: '请输入装备名称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    // {
    //   field: 'wear',
    //   component: 'NSelect',
    //   label: '状态',
    //   componentProps: {
    //     placeholder: '请选择状态',
    //     options: [
    //       {
    //         label: '全部',
    //         value: '',
    //       },
    //       {
    //         label: '已穿戴',
    //         value: true,
    //       },
    //       {
    //         label: '未穿戴',
    //         value: false,
    //       },
    //     ],
    //     onUpdateValue: (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,
  });

  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 wearRoles = getWearRoles(props.userInfo.roles);
  const loadDataTable = async (_) => {
    loading.value = true;
    let lists = genEquipmentTableColumns(
      props.userInfo.equipments,
      props.userInfo.bodyParts,
      wearRoles
    );
    data.value = lists;
    originalData.value = lists;

    loading.value = false;
  };

  onMounted(async () => {
    if (props.userId < 1) {
      console.log('传入用户信息不正确，props.userId：', props.userId);
      return;
    }
    await loadDataTable({});
    getAllEquipments({})
      .then((res) => {
        equipInfo.value.allEquipments = res.list;
      })
      .catch((e: Error) => {
        message.error(e.message ?? '操作失败');
      });

    if (getAdminTemplate() === TemplateYanYv) {
      finalChoice.value = [
        [10404001, 10104001, 20104001, 30104001, 40104001, 50104001, 60104001],
        [
          10106001, 10406001, 20106001, 20206001, 20306001, 30106001, 30206001, 30306001, 40106001,
          40206001, 40306001, 50106001, 50206001, 50306001, 60106001, 60206001, 60306001,
        ],
        [10103001, 10403001, 20103001, 30103001, 40103001, 50103001, 60103001],
      ];
    }
  });

  const fatherRefresh = () => {
    console.log('fatherRefresh...equipment');
    loadDataTable({});
  };
  defineExpose({ fatherRefresh });
</script>
