<template>
  <div>
    <BasicForm
      @register="register"
      :showResetButton="false"
      :showSubmitButton="false"
      @submit="handleSubmit"
    >
      <template #but="{ field }">
        <Icon
          size="20px"
          v-if="showBut(field, false)"
          icon="ion:remove-circle-outline"
          @click="del(field)"
        />
      </template>
      <template #parentBut="{ field }">
        <Icon
          size="28px"
          v-if="showBut(field, true)"
          icon="ion:remove-circle-outline"
          @click="parentDel(field)"
        />
      </template>
      <template #addAttribute="{ field }">
        <a-button @click="addBut(field)"> 添加属性值 </a-button>
      </template>
      <template #formFooter>
        <div>
          <a-button style="margin-right: 30px" @click="addBut">添加规格项目</a-button>
          <a-button @click="handleSubmit">生成规格明细</a-button>
        </div>
      </template>
    </BasicForm>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, onMounted } 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';

  interface valList {
    name: string;
    // picUrl: string;
    uuid: string;
  }
  interface ProductListItem {
    uuidLink: string;
    goodsNumber?: string;
    goodsSn?: string;
    retailPrice?: string;
    marketPrice?: string;
  }
  interface EditDataType {
    name: string;
    specificationId: string;
    val: valList[];
  }
  export default defineComponent({
    components: { BasicForm, Icon },
    props: {
      editdata: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['update', 'editdata'],
    setup(props, { emit }) {
      let ggList = reactive({
        goodsNumber: 1,
        specsNumber: 1,
        list: {
          1: {
            value: 1,
            list: [1],
          },
        },
      });
      let specsObj = ref({});
      onMounted(() => {
        initialize();
      });
      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: {
              maxLength: 15,
              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: 18,
            },
            componentProps: {
              maxLength: 15,
            },
          },
          // {
          //   field: 'picUrl_' + number + '_' + val,
          //   component: 'Upload',
          //   required: true,
          //   label: '规格图',
          //   colProps: {
          //     span: 10,
          //   },
          //   itemProps: {
          //     validateTrigger: 'blur',
          //   },
          //   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 [
        register,
        {
          setProps,
          setFieldsValue,
          removeSchemaByFiled,
          appendSchemaByField,
          validate,
          getFieldsValue,
        },
      ] = useForm({
        labelWidth: 120,
        schemas: addSchemas(ggList.specsNumber, ggList.goodsNumber, true),
        baseColProps: {
          span: 16,
        },
      });
      function initialize() {
        //初始化组装数据
        let goodsgg = [],
          setVlaue: {};
        if (props.editdata.guigeArr) {
          let guigeArr = JSON.parse(props.editdata.guigeArr);
          guigeArr.map((ele, index) => {
            console.log('ele', ele);
            if (index == 0) {
              if (ele.val.length == 1) {
                //不需要新增form item 可直接赋值
                setVlaue = {
                  ...setVlaue,
                  name_1: ele.specificationId,
                  goodsSn_1_1: ele.val[0].name,
                  picUrl_1_1: [ele.val[0].picUrl],
                };
              } else {
                //新增一个属性值item
                setVlaue[`name_${index}`] = ele.specificationId;
                for (var valIndex = 1; valIndex < ele.val.length; valIndex++) {
                  addBut(`add_${valIndex}`);
                  setVlaue[`goodsSn_${index}_${valIndex}`] = ele.val[valIndex].name;
                  // setVlaue[`picUrl_${index}_${valIndex}`] = ele.val[valIndex].picUrl;
                }
              }
            } else {
              setVlaue[`name_${index}`] = ele.specificationId;
              for (var valIndex = 1; valIndex < ele.val.length; valIndex++) {
                addBut(`add_${valIndex}`);
                setVlaue[`goodsSn_${index}_${valIndex}`] = ele.val[valIndex].name;
                // setVlaue[`picUrl_${index}_${valIndex}`] = ele.val[valIndex].picUrl;
              }
            }
            setFieldsValue(setVlaue);
            console.log('index', index, ele, setVlaue);
          });
          console.log('初始化数据', guigeArr, 'props', props.editdata, goodsgg);
        }
      }
      function setForm() {
        0;
      }
      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),
        );
        removeSchemaByFiled([`goodsSn_${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}`, `${item}_${ele}`];
            delList = delList.concat(child);
          });
        removeSchemaByFiled(delList);
        ggList.list;
        delete ggList.list[item];
      }
      async function addBut(val) {
        let goodsNumber = ggList.goodsNumber;
        let specsNumber = ggList.specsNumber;
        if (typeof val == 'string') {
          let number = Number(val.split('_')[1]);
          let { value, 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();
          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);
          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: EditDataType[] = [],
          productList: ProductListItem[] = [];
        console.log('ggList', ggList.list, data, ggList.specsNumber);
        for (let index = 1; index < ggList.specsNumber + 1; index++) {
          let ele = ggList.list[index];
          let name = getData[`name_${index}`];
          let val: valList[] = [];
          ele.list.map((element) => {
            val.push({
              name: getData[`goodsSn_${index}_${element}`],
              // picUrl: getData[`picUrl_${index}_${element}`][0],
              uuid: `${index}-${element}`,
            });
            productList.push({
              goodsNumber: '',
              goodsSn: '',
              marketPrice: '',
              retailPrice: '',
              uuidLink: `${index}_${element}`,
            });
          });
          console.log('ggList', val, specsObj.value);
          let item = {
            name: specsObj.value[name],
            specificationId: name,
            val,
          };
          goodsSpecificationList.push(item);
        }
        console.log('update', { goodsSpecificationList, productList });
        emit('update', { goodsSpecificationList, productList });
        // createMessage.success('click search,values:' + JSON.stringify(values));
      }
      return {
        register,
        handleSubmit,
        addSchemas,
        setProps,
        ggList,
        del,
        parentDel,
        addBut,
        showBut,
        getData,
        specsObj,
        initialize,
        setForm,
      };
    },
  });
</script>
