<template>
  <div>
    <TitleComponent data="基本信息">
      <template #extra>
        <Button @click="comeBack" style="margin-left: 10px">返回</Button>
      </template>
    </TitleComponent>
    <Form layout="vertical" :model="form" ref="formRef">
      <Row :gutter="24">
        <Col :span="12">
          <FormItem label="设备名称" name="name" :rules="{ required: true, message: '请输入设备名称' }">
            <Input v-model:value="form.name" />
          </FormItem>
        </Col>
        <Col :span="12">
          <FormItem label="产品名称" name="productId" :rules="{ required: true, message: '请选择产品名称' }">
            <Select :disabled="props.childData?.id" @change="selectChange" v-model:value="form.productId">
              <SelectOption v-for="i in productList" :key="i.id" :value="i.id">{{ i.name }}</SelectOption>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="24" v-if="visible">
        <Col :span="24"><EdgeMap :productList="productList" @close="comeBack" @get-edge-map="getEdgeMapData" /></Col>
      </Row>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, provide, reactive, ref } from 'vue';
  import { getEdgeMap, getProductListNoPage, removeEdgeMap } from '../../../../../../api/device/instance';
  import EdgeMap from '../EdgeMap/index.vue';
  import { useInstanceStore } from '@jdlinker/func';
  import { storeToRefs } from 'pinia';
  import { TitleComponent } from '@jdlinker/ui';
  // @ts-ignore
  import { Button, Col, Form, FormItem, Row, Select, SelectOption, Input } from 'linker-ui-components';

  const instanceStore = useInstanceStore();
  const { current } = storeToRefs(instanceStore);
  const props = defineProps(['childData']);
  const form = reactive({
    name: '',
    productId: ''
  });
  const formRef = ref();
  const emit = defineEmits(['closeChildSave']);
  const productList = ref();
  const visible = ref(false);
  /**
   * 获取产品列表
   */
  const getProductList = async () => {
    const res = await getProductListNoPage({
      terms: [{ column: 'accessProvider', value: 'edge-child-device' }]
    });
    if (res.status === 200) {
      productList.value = res.result;
      getEdgeMapData();
    }
  };
  /**
   * 获取映射数据
   */
  const getEdgeMapData = () => {
    if (props.childData?.id) {
      current.value.parentId = props.childData.id;
      form.name = props.childData?.name;
      form.productId = props.childData?.productId;
      selectChange(form.productId);
      if (current.value.metadata) {
        const metadata = current.value.metadata;
        if (metadata && metadata.length !== 0) {
          getEdgeMap(current.value.id, {
            deviceId: props.childData.id,
            query: {}
          }).then((res) => {
            if (res.status === 200) {
              // console.log(res.result)
              //合并物模型
              const array = res.result[0]?.reduce((x: any, y: any) => {
                const metadataId = metadata.find((item: any) => item.metadataId === y.metadataId);
                if (metadataId) {
                  Object.assign(metadataId, y);
                } else {
                  x.push(y);
                }
                return x;
              }, metadata);
              //删除物模型
              current.value.metadata = array.filter((item: any) => item.metadataName);
              const delList = array.filter((a: any) => !a.metadataName).map((b: any) => b.id);
              //删除后解绑
              if (delList && delList.length !== 0) {
                removeEdgeMap(current.value.id, {
                  deviceId: props.childData.id,
                  idList: [...delList]
                });
              }
            }
          });
        }
      }
      visible.value = true;
    } else {
      current.value.parentId = '';
    }
  };
  /**
   * 根据产品id获取对应映射列表
   * @param e 产品id
   */
  const selectChange = (e: any) => {
    if (e) {
      visible.value = true;
    }
    const item = productList.value.filter((i: any) => i.id === e)[0];
    current.value.metadata = JSON.parse(item?.metadata || '{}')?.properties?.map((i: any) => ({
      metadataType: 'property',
      metadataName: `${i.name}(${i.id})`,
      metadataId: i.id,
      name: i.name
    }));
  };
  onMounted(() => {
    getProductList();
  });

  const validate = async () => {
    return formRef.value.validateFields();
  };
  provide('validate', validate);
  const comeBack = () => {
    emit('closeChildSave');
  };
</script>
<style lang="less" scoped></style>
