<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { orderGoodColumns } from "./config/columns";
import { useDetail } from "/@/hooks/core/useDetail";
import BasicDescriptions from "/@/components/BasicDescriptions";
import ChooseGoodModal from "./components/ChooseGoodModal/index.vue";
import ChildGoodEditModal from "./components/ChildGoodEditModal.vue";
import { httpDetail } from "/@/api/invoiceInOut/inOutManager";
import BaseForm from "./components/BaseForm/index.vue";

import { useTask } from "/@/hooks/core";

const { title, collapses, id, isDetail } = useDetail({
  baseName: "C端无发票订单出库",
  collapseLen: 2
});

const visible = ref(false);
const detailTask = useTask();

const state = reactive({ editVisible: false, index: -1, data: {} });

const formData = ref({
  goods: [],
  month: ""
});

function handleGoodComfirm(values: any[]) {
  const ids = formData.value.goods.map(({ id }) => id);
  const list = values.filter(item => !ids.includes(item.id));
  formData.value.goods = [...list, ...formData.value.goods];
}

function handleEditGood(index: number, data: any) {
  const { id } = formData.value.goods[index];
  formData.value.goods = formData.value.goods.map(item => {
    if (item.id === id) {
      const goodNum = data.goodNum;
      const childActionNum = item.childNum
        ? Number(item.childNum) * Number(goodNum)
        : undefined;

      return { ...item, goodNum, childActionNum };
    }
    return item;
  });
}

id.value && detailTask.run(httpDetail({ id: id.value }));
</script>

<template>
  <div class="padding__container" v-loading="detailTask.loading">
    <ElTabs>
      <ElTabPane :label="title">
        <ElCollapse v-model="collapses">
          <ElCollapseItem :title="title" name="1">
            <BasicDescriptions v-if="isDetail && detailTask.data" :columns="orderGoodColumns" :data="detailTask.data" />
            <BaseForm v-else  />
          </ElCollapseItem>
        </ElCollapse>
      </ElTabPane>
    </ElTabs>

    <ChooseGoodModal v-model:visible="visible" @submit="handleGoodComfirm" />

    <ChildGoodEditModal :data="state.data" :index="state.index" v-model:visible="state.editVisible"
      @submit="handleEditGood" />
  </div>
</template>
