<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :isDetail="true"
    showFooter
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #goodsgg>
        <goodsSpecs @update="setEditData" ref="goodsRef" />
      </template>
      <template #detailed>
        <table class="detailed">
          <thead>
            <tr style="">
              <th style="min-width: 130px">{{ editData.categoryName }}</th>
              <th>库存</th>
              <th>规格编码</th>
              <th>市场价</th>
              <th>销售价</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in editData.productList" :key="item.uuidLink">
              <template v-if="editData.productList">
                <td>{{ item.uuidLink }}</td>
                <td><input type="text" id="name" v-model="item.goodsNumber" /></td>
                <td><input type="text" id="age" v-model="item.goodsSn" /></td>
                <td><input type="text" id="school" v-model="item.marketPrice" /></td>
                <td><input type="text" id="school" v-model="item.retailPrice" /></td>
              </template>
            </tr>
          </tbody>
        </table>
      </template>
      <!-- <template #formItem>
        <BasicForm @register="itemRegister" @submit="handleSubmit">
          <template #add="{ field }">
            <a-button v-if="Number(field) === 0" @click="add">+</a-button>
            <a-button v-if="field > 0" @click="del.bind(null, field)">-</a-button>
          </template>
        </BasicForm>
      </template> -->
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './drawer.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import goodsSpecs from './goodsSpecs.vue';
  import { InfoApi, UpdateSaleApi } from '/@/api/product/list';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { getMenuList } from '/@/api/system/system';
  import { makeTree, TreeNode } from '/@/utils/treeUtils';
  import { categoryApi } from '/@/api/product/category';

  interface EditDataType {
    categoryName: string;
    productList: ProductListItem[];
  }

  interface ProductListItem {
    uuidLink: string;
    goodsNumber?: string;
    goodsSn: string;
    retailPrice: string;
    marketPrice: string;
  }

  export default defineComponent({
    name: 'ProductDrawer',
    components: { BasicDrawer, BasicForm, goodsSpecs },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const goodsRef = ref();
      const { createMessage } = useMessage();
      const { t } = useI18n();

      let editData = ref<EditDataType>({
        categoryName: '',
        productList: [],
      });

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 18, md: 18, offset: 1 },
      });
      const [itemRegister, {}] = useForm({
        // formItemValue :validate appendSchemaByField, removeSchemaByField,
        schemas: [
          {
            field: 'goodsId',
            label: '规格名',
            component: 'ApiTreeSelect',
            componentProps: {
              api: async (params) => {
                const res = (await categoryApi(params)) as any as TreeNode[];
                const treeData = makeTree(res);
                return treeData;
              },
              fieldNames: {
                label: 'name',
                key: 'id',
                value: 'id',
              },
            },
          },
          {
            field: 'goodsSn',
            component: 'Input',
            label: '字段0',
            colProps: {
              span: 8,
            },
            required: true,
          },
          {
            field: '0',
            component: 'Input',
            label: ' ',
            colProps: {
              span: 8,
            },
            slot: 'add',
          },
        ],
        labelWidth: 100,
        actionColOptions: { span: 24 },
      });
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        console.log('setFieldsValue', data.record);
        if (unref(isUpdate)) {
          let res = await InfoApi(data.record.id);
          editData.value = res;
          console.log('setFieldsValueres', res);
          setFieldsValue({
            ...res,
            listPicUrl: [encodeURI(res.listPicUrl.split('?')[0])],
            primaryPicUrl: [encodeURI(res.primaryPicUrl.split('?')[0])],
            steamRoom: data.record?.steamRoom?.name,
          });
        }
      });
      function setEditData(value) {
        console.log('setEditData', value);
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增商品' : '编辑商品'));

      async function handleSubmit() {
        try {
          const values = await validate();
          console.log('values', values);
          let subData = await UpdateSaleApi({
            ...editData.value,
            ...values,
          });
          console.log('setFieldsValue', subData);
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          createMessage.success(t('common.optSuccess'));
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        goodsRef,
        registerDrawer,
        registerForm,
        itemRegister,
        getTitle,
        editData,
        handleSubmit,
        setEditData,
      };
    },
  });
</script>

<style scoped lang="less">
  :deep(.detailed) {
    .title {
      display: flex;
      span,
      input,
      div {
        flex-grow: 1;
      }
      input {
        display: inline-block;
      }
      .name {
        flex-grow: 2;
      }
    }
    tr {
      th {
        font-weight: 500;
      }
    }
  }
</style>
