<template>
  <div class="containe">
    <div class="tableWrap">
      <a-tabs v-model:activeKey="activeKey" centered>
        <a-tab-pane key="1" tab="基本信息"><BasicInfo ref="basicInfoRef" @handleSubmit="handleSubmit" /> </a-tab-pane>
        <a-tab-pane key="2" tab="商品描述" force-render>Content of Tab Pane 2</a-tab-pane>
        <a-tab-pane key="3" tab="商品图片">Content of Tab Pane 3</a-tab-pane>
        <a-tab-pane key="4" tab="产品规格"><Product /></a-tab-pane>
      </a-tabs>
      <div class="btnWrap">
        <a-button type="primary" @click="handleAdd">提交</a-button>
        <a-button @click="handleBack">返回</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import BasicInfo from './components/basicInfo.vue';
  import * as GoodsApi from '/@/api/product/goodsApi';
  import Product from './components/product.vue';
  import { useGo } from '/@/hooks/web/usePage';
  import lodash from 'lodash';
  import { message } from 'ant-design-vue';

  const route = useRoute();
  const go = useGo();
  const basicInfoRef = ref();
  const activeKey = ref('1');
  const id = route.query.id;
  let basicInfo;

  const getInfo = () => {
    GoodsApi.getById(id).then((res) => {
      const goodsCategoryList = <number[]>[];
      res.goodsCategoryList.forEach((item) => {
        goodsCategoryList.push(item.id);
      });
      res.goodsCategoryList = goodsCategoryList;
      for (const key in basicInfo) {
        basicInfo[key] = res[key];
      }
    });
  };

  const handleAdd = () => {
    basicInfoRef.value.validate();
  };

  const handleSubmit = () => {
    const data = lodash.cloneDeep(basicInfoRef.value.formData);
    data.goodsCategoryList.forEach((item, index) => {
      data.goodsCategoryList[index] = { id: item };
    });

    let api;
    if (id) {
      data.id = id;
      api = GoodsApi.update;
    } else {
      api = GoodsApi.add;
    }
    api(data).then(() => {
      message.success('操作成功');
      handleBack();
    });
  };

  const handleBack = () => {
    go('/main/product/goods');
  };

  onMounted(() => {
    basicInfo = basicInfoRef.value.formData;
    if (id) {
      getInfo();
    }
  });
</script>

<style lang="less" scoped>
  @import url('/@/style/index.less');

  .btnWrap {
    margin-bottom: 20px;
    text-align: center;

    .ant-btn {
      margin: 0 5px;
    }
  }
</style>
