<template>
  <div>
    <BasicForm @register="register" @submit="handleSubmit">
      <template #but="{ field }">
        <Icon
          size="20px"
          v-if="showBut(field, false)"
          icon="ion:remove-circle-outline"
          @click="del.bind(null, field)"
        />{{ field }}
      </template>
      <template #parentBut="{ field }">
        <Icon
          size="28px"
          v-if="showBut(field, true)"
          icon="ion:remove-circle-outline"
          @click="parentDel.bind(null, field)"
        />{{ field }}
      </template>
      <template #addAttribute="{ field }">
        <a-button @click="addBut.bind(null, field)"> 添加属性值 </a-button>
      </template>
    </BasicForm>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive } from 'vue';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { uploadApi } from '/@/api/advertisement/list';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { queryAll } from '/@/api/product/list';

  export default defineComponent({
    components: { BasicForm, Icon },
    emits: ['update'],
    setup(_, { emit }) {
      let ggList = reactive({
        goodsNumber: 1,
        specsNumber: 1,
        list: {
          1: {
            value: 1,
            list: [1],
          },
        },
      });
      let specsObj = ref({});
      const addSchemas = (number = ggList.specsNumber, val = 1, type = true) => {
        console.log('addButlist', number + '_' + val, ggList);
        let parentList: FormSchema[] = [
          {
            field: 'name_' + number,
            label: '规格名',
            component: 'ApiTreeSelect',
            colProps: {
              span: 18,
            },
            required: true,
            componentProps: {
              api: queryAll,
              fieldNames: {
                label: 'name',
                key: 'id',
                value: 'id',
              },
              onChange: function (val, a) {
                specsObj.value[val] = a[0];
              },
            },
          },
          {
            field: 'parent_' + number,
            label: '',
            slot: 'parentBut',
            component: 'Input',
            colProps: {
              span: 4,
            },
          },
        ];
        let list: FormSchema[] = [
          {
            field: 'goodsSn_' + number + '_' + val,
            label: '规格值',
            component: 'Input',
            required: true,
            colProps: {
              span: 8,
            },
          },
          {
            field: 'picUrl_' + number + '_' + val,
            component: 'Upload',
            required: true,
            label: '规格图',
            colProps: {
              span: 10,
            },
            componentProps: {
              api: uploadApi,
              maxgoodsNumber: 1,
              afterFetch: function (data) {
                Reflect.set(data, 'url', data.message);
                return data;
              },
            },
          },
          {
            field: number + '_' + val,
            label: '',
            slot: 'but',
            component: 'Input',
            colProps: {
              span: 4,
            },
          },
        ];
        var concatList = parentList.concat(list);
        if (type) {
          concatList.push({
            field: 'add_' + number,
            label: '  ',
            slot: 'addAttribute',
            component: 'Input',
            colProps: {
              span: 24,
            },
          });
        }
        console.log('parentList', type, concatList, 'list', list);
        return type ? concatList : list;
      };
      const { createMessage } = useMessage();
      const [
        register,
        { setProps, removeSchemaByField, appendSchemaByField, validate, getFieldsValue },
      ] = useForm({
        labelWidth: 120,
        schemas: addSchemas(ggList.specsNumber, ggList.goodsNumber, true),
        baseColProps: {
          span: 16,
        },
        actionColOptions: {
          span: 12,
        },
      });
      function del(field) {
        let number = Number(field.split('_')[0]);
        let item = Number(field.split('_')[1]);
        let { list, value } = ggList.list[number];
        console.log(
          item,
          'number',
          number,
          list,
          value,
          'listfield',
          list.filter((ele) => ele !== item),
        );
        removeSchemaByField([`goodsSn_${field}`, `picUrl_${field}`, `${field}`]);
        ggList.list[number] = {
          value: value - 1,
          list: list.filter((ele) => ele !== value - 1),
        };
        // ggList.goodsNumber--;
      }
      function parentDel(field) {
        let item = Number(field.split('_')[1]);
        let data = ggList.list[item];
        let delList = [`name_${item}`, `parent_${item}`, `add_${item}`];
        console.log('addBut', data);
        data.list &&
          data.list.map((ele) => {
            let child = [`goodsSn_${item}_${ele}`, `picUrl_${item}_${ele}`, `${item}_${ele}`];
            delList = delList.concat(child);
          });
        removeSchemaByField(delList);
        ggList.list;
        delete ggList.list[item];
      }
      async function addBut(val) {
        let goodsNumber = ggList.goodsNumber;
        let specsNumber = ggList.specsNumber;
        if (typeof val == 'string') {
          console.log('addBut');
          let number = Number(val.split('_')[1]);
          let { value, list } = ggList.list[number];
          value++;
          console.log(
            'addBut',
            list,
            value,
            'number',
            number,
            'ggList.goodsNumber.list',
            ggList.list[number].value,
          );
          list.push(value);
          let filed = number + '_' + ggList.list[number].value;
          ggList.list[number] = {
            value,
            list,
          };
          let listSchemas = addSchemas(number, goodsNumber + 1, false).reverse();
          console.log('addButlist', filed, list, ggList);
          listSchemas.map((ele) => {
            appendSchemaByField(ele, filed);
          });
          ggList.goodsNumber = goodsNumber + 1;
        } else {
          specsNumber++;
          ggList.specsNumber = specsNumber;
          ggList.list[specsNumber] = {
            value: 1,
            list: [1],
          };
          let list = addSchemas(specsNumber, 1, true);
          console.log('addSchemasList', list, await getFieldsValue());
          list.map((ele) => {
            appendSchemaByField(ele, '');
          });
          ggList.goodsNumber = 1;
        }
      }
      function showBut(field, type) {
        let show = true;
        let item = field.split('_');
        let key = 1;
        if (type) {
          //父级
          key = Number(item[1]);
          let array = Object.keys(ggList.list || []);
          console.log('item', array);
          console.log('item', item, show, ggList.list, 'array', array);
          if (!(array && array.length > 1)) return false;
        } else {
          //子集
          key = Number(item[0]);
          if (ggList.list[key] && ggList.list[key].list && ggList.list[key].list.length == 1)
            show = false;
        }
        return show;
      }
      async function getData(val) {
        let data = await validate();
        let getData = await getFieldsValue();
        console.log('getData', val, data, getData);
      }

      async function handleSubmit() {
        let data = await validate();
        let getData = await getFieldsValue();
        let goodsSpecificationList = [],
          productList = [];
        console.log('ggList', ggList.list, data);
        for (let index = 0; index < ggList.specsNumber; index++) {
          let ele = ggList.list[index + 1];
          let name = getData[`name_${index + 1}`];
          let val = [];
          ele.list.map((element) => {
            console.log('element', getData, `picUrl_${index + 1}_${element}`);
            val.push({
              name: getData[`goodsSn_${index + 1}_${element}`],
              picUrl: getData[`picUrl_${index + 1}_${element}`][0],
              uuid: `${index + 1}-${element}`,
            });
          });
          console.log('ggList', val, specsObj.value);
          let item = {
            name: name,
            specificationId: specsObj.value[name],
            val,
          };
          goodsSpecificationList.push(item);
          productList.push({
            goodsNumber: null,
            goodsSn: null,
            marketPrice: null,
            retailPrice: null,
            uuidLink: '1-1',
          });
        }
        console.log('update', { goodsSpecificationList, productList });
        emit('update', { goodsSpecificationList, productList });
        createMessage.success('click search,values:' + JSON.stringify(values));
      }

      // const submitButtonOptions = { type: 'default', text: '生成规格明细' } as UseButtonProps;
      // const resetButtonOptions = { text: '添加规格项目', onClick: addBut } as UseButtonProps;

      return {
        register,
        handleSubmit,
        addSchemas,
        setProps,
        ggList,
        del,
        parentDel,
        addBut,
        showBut,
        getData,
        specsObj,
      };
    },
  });
</script>
