<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :isDetail="true"
    :showDetailBack="false"
    showFooter
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #goodsgg>
        <goodsSpecs :key="editData.id" :editdata="editData" @update="setEditData" ref="goodsRef" />
      </template>
      <template #detailed>
        <table class="detailed">
          <thead>
            <tr style="" v-show="editData.productList.length > 0">
              <th style="min-width: 60px">{{ 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
                  :title="item.name"
                  style="
                    max-width: 120px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  >{{ item.name }}</td
                >
                <td
                  ><InputNumber
                    type="number"
                    :maxlength="8"
                    :max="100000000"
                    :min="0"
                    v-model:value="item.goodsNumber"
                /></td>
                <td
                  ><Input
                    type="text"
                    :maxlength="8"
                    :max="100000000"
                    :min="0"
                    v-model:value="item.goodsSn"
                /></td>
                <td
                  ><InputNumber
                    type="number"
                    :maxlength="8"
                    :max="100000000"
                    :min="0"
                    v-model:value="item.marketPrice"
                /></td>
                <td
                  ><InputNumber
                    type="number"
                    :maxlength="8"
                    :max="100000000"
                    :min="0"
                    v-model:value="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 { Input, InputNumber } from 'ant-design-vue';
  import { formSchema } from './drawer.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import goodsSpecs from './goodsSpecs.vue';
  import { InfoApi, UpdateSaleApi, SaveSaleApi } from '/@/api/product/list';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  // import { getMenuList } from '/@/api/system/system';
  import { makeTree, TreeNode } from '/@/utils/treeUtils';
  import { categoryApi } from '/@/api/product/category';

  interface EditDataType {
    categoryName: string;
    productList: ProductListItem[];
    goodsSpecificationList?: goodsSpecificationList[];
    id: number;
  }
  interface goodsSpecificationList {
    brandName: string;
    goodsId?: number;
    goodsName: string;
    id?: number;
    picUrl: string;
    specificationId?: number;
    specificationName: string;
    uuid: string;
    val?: string | number | [];
    value: string;
  }
  interface ProductListItem {
    uuidLink: string;
    goodsNumber?: string;
    goodsSn: string;
    retailPrice: string;
    marketPrice: string;
    name?: string;
  }

  export default defineComponent({
    name: 'ProductDrawer',
    components: { BasicDrawer, BasicForm, goodsSpecs, Input, InputNumber },
    emits: ['reload', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const goodsRef = ref();
      const { createMessage } = useMessage();
      const userStore = useUserStore();
      const userinfo = computed(() => userStore.getUserInfo);
      const { t } = useI18n();

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

      const [registerForm, { resetFields, updateSchema, setFieldsValue, validate }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 18, md: 18, offset: 1 },
      });
      const [itemRegister, {}] = useForm({
        // formItemValue :validate appendSchemaByField, removeSchemaByFiled,
        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;
              },
              maxLength: 15,
              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;
        editData.value = {
          categoryName: '',
          productList: [],
          id: 0,
        };
        updateSchema({
          field: 'brandId',
          componentProps: {
            disabled: unref(isUpdate) ? true : false,
          },
        });
        if (unref(isUpdate)) {
          let res = await InfoApi(data.record.id);
          editData.value = {
            ...res,
            productList: res.productList.map((ele) => {
              console.log('editData', ele, res.goodsSpecificationList);
              ele.name = res.goodsSpecificationList.find(
                (element) => element.uuid == ele.uuidLink,
              )?.specificationName;
              return ele;
            }),
          };
          setFieldsValue({
            ...res,
            isOnSale: res.isOnSale === 1,
            listPicUrl:
              res.listPicUrl && res.listPicUrl.split('#$#').map((ele) => ele.split('?')[0]),
            primaryPicUrl:
              res.primaryPicUrl && res.primaryPicUrl.split('#$#').map((ele) => ele.split('?')[0]),
            // primaryPicUrl: res.primaryPicUrl && [encodeURI(res.primaryPicUrl.split('?')[0])],
            steamRoom: data.record?.steamRoom?.name,
          });
        }
      });
      function setEditData(value) {
        let productList = editData.value.productList || [];
        value.productList.map((ele) => {
          if (!productList.some((element) => ele.uuidLink == element.uuidLink)) {
            //判断新增
            productList.push({
              uuidLink: ele.uuidLink,
              name: ele.name,
              goodsNumber: '',
              goodsSn: '',
              marketPrice: '',
              retailPrice: '',
            });
          } else {
            //本来就有的 修改赋值
            productList.forEach((setEle) => {
              if (ele.uuidLink == setEle.uuidLink) {
                setEle.name = ele.name;
              }
            });
          }
        });
        productList = productList.filter((ele) =>
          value.productList.some((element) => element.uuidLink == ele.uuidLink),
        );
        console.log('setEditData', productList);
        editData.value = {
          ...editData.value,
          ...value,
          productList,
        };
        setFieldsValue({
          productList: productList,
        });
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增商品' : '编辑商品'));

      async function handleSubmit() {
        const { companyId, id } = userinfo.value;
        try {
          const values = await validate();
          console.log('values', values);
          let apiData = {
            ...editData.value,
            ...values,
            retailPrice:
              editData.value.productList &&
              Math.min(...editData.value.productList.map((ele) => Number(ele.retailPrice))),
            marketPrice:
              editData.value.productList &&
              Math.min(...editData.value.productList.map((ele) => Number(ele.marketPrice))),
            isOnSale: values.isOnSale ? 1 : 0,
          };

          let requresApi = isUpdate.value ? UpdateSaleApi : SaveSaleApi;
          if (!isUpdate.value) {
            apiData.createUserDeptId = companyId;
            apiData.createUserId = id;
          }
          let subData = await requresApi({
            ...apiData,
            primaryPicUrl: apiData.primaryPicUrl.join('#$#'),
            listPicUrl: apiData.listPicUrl.join('#$#'),
          });
          console.log('setFieldsValue', subData);
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          createMessage.success(t('common.optSuccess'));
          closeDrawer();
          emit('reload');
        } 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>
