<template>
  <div>
    <BasicModal
      :showOkBtn="false"
      :showCancelBtn="false"
      v-bind="$attrs"
      @register="registerDrawer"
      :title="getTitle"
      width="1000px"
      @cancel="handleCancel"
      destroy-on-close
    >
      <div class="step-form-form">
        <a-steps :current="current">
          <a-step title="选择流转方式" />
          <a-step title="完善配置参数" />
        </a-steps>
      </div>
      <div>
        <div v-show="current === 0">
          <TransferConfigMode
            :save-content="handleSubmit"
            ref="refTransferConfigMode"
            @next="handleNext"
          />
        </div>
        <div v-show="current === 1">
          <TransferConfigParams
            ref="refTransferConfigParams"
            :getModeSelect="getModeSelectVal"
            @prevSon="handlePrev"
          />
        </div>
      </div>
      <div style="float: right" v-if="isViewStatus">
        <Button type="primary" @click="handleSubmit" v-show="current === 1" class="mr-2"
          >确认</Button
        >
        <Button type="default" @click="handleCancel" class="mr-2">取消</Button>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, unref, getCurrentInstance } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Steps } from 'ant-design-vue';
  import TransferConfigMode from './cpns/transferConfigMode.vue';
  import TransferConfigParams from './cpns/transferConfigParams.vue';
  import { postAddConvertApi } from '/@/api/datamanager/dataManagerApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Button } from '/@/components/Button';
  import { add } from '/@/components/Form/src/componentMap';
  import TransferModal from '/@/components/Form/src/components/TransferModal.vue';
  import TransferTableModal from '/@/components/Form/src/components/TransferTableModal.vue';

  add('TransferModal', TransferModal);
  add('TransferTableModal', TransferTableModal);

  export default defineComponent({
    name: 'ConfigDrawer',
    components: {
      BasicModal,
      [Steps.name]: Steps,
      [Steps.Step.name]: Steps.Step,
      TransferConfigMode,
      TransferConfigParams,
      Button,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isViewStatus = ref(false);
      const { createMessage } = useMessage();
      const { proxy } = getCurrentInstance() as any;
      let allPostForm: any = reactive({});
      const getNameObj = reactive({
        name: '',
      });
      const getTypeObj = reactive({
        type: '',
        remark: '',
      });
      const additionalInfoV = {
        additionalInfo: {
          description: '',
        },
      };
      const getSonFormValue: any = ref({});
      const getModeSonFormValue: any = ref({});
      const refTransferConfigParams = ref(null);
      const refTransferConfigMode = ref(null);
      const getModeSelectVal = ref({});
      const isUpdate: any = ref(true);
      const getTitle = ref('');
      const current = ref(0);
      const editPostId = ref('');
      let isEdit = ref(true);
      let noEditObj: any = reactive({});
      const editType = reactive({
        type: '',
        configuration: {},
        name: '',
        additionalInfo: {},
      });
      const editNextType = reactive({
        type: '',
        configuration: {},
        name: '',
        remark: '',
        datasourceType: '',
        datasourceContent: {},
      });
      const editTypeFunc = (d) => {
        editType.type = d.type;
        editType.configuration = d.configuration;
        editType.name = d.name;
        editType.additionalInfo = d.additionalInfo;
      };

      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        isUpdate.value = data?.isUpdate;
        current.value = 0;
        setModalProps({ confirmLoading: false });
        function commonViewOrEditFunc() {
          editPostId.value = data.record.id;
          editNextType.type = data.record.type;
          editNextType.configuration = data.record;
          editNextType.name = data.record.name;
          editNextType.remark = data.record.remark;
          editNextType.datasourceType = data.record.datasourceType;
          editNextType.datasourceContent = data.record.datasourceContent;
          editNextType.convertConfigId = data.record.id;

          proxy.$refs.refTransferConfigMode.setStepOneFieldsValueFunc(editNextType);
        }
        if (!unref(isUpdate)) {
          isEdit.value = false;
        } else {
          isEdit.value = true;
        }
        if (isEdit.value) {
          noEditObj = {
            name: data.record?.name,
            remark: data.record?.remark,
            type: data.record?.type,
            id: data.record.id,
            configuration: data.record?.configuration,
          };
        }
        switch (unref(isUpdate)) {
          case 'view':
            commonViewOrEditFunc();
            isViewStatus.value = false;
            getTitle.value = '查看流转配置';
            break;
          case true:
            commonViewOrEditFunc();
            isViewStatus.value = true;
            getTitle.value = '编辑流转配置';
            break;
          case false:
            proxy.$refs.refTransferConfigMode?.customResetStepOneFunc();
            isViewStatus.value = true;
            getTitle.value = '新增流转配置';
            break;
        }
      });
      const handleCancel = () => {
        defineClearFunc();
        closeModal();
      };
      const defineClearFunc = () => {
        proxy.$refs.refTransferConfigMode?.customResetStepOneFunc();
        proxy.$refs.refTransferConfigParams?.clearSonValueDataFunc();
      };
      const handleNext = (args) => {
        current.value++;
        getModeSelectVal.value = args;
        if (unref(isUpdate)) {
          isEdit.value = false;
          try {
            if (editNextType.type == 'org.thingsboard.rule.engine.kafka.TbKafkaNode') {
              editTypeFunc(editNextType.configuration);
            } else if (editNextType.type == 'org.thingsboard.rule.engine.mqtt.TbMqttNode') {
              editTypeFunc(editNextType.configuration);
            } else if (editNextType.type == 'org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode') {
              editTypeFunc(editNextType.configuration);
            } else if (editNextType.type == 'org.thingsboard.rule.engine.rest.TbRestApiCallNode') {
              editTypeFunc(editNextType.configuration);
            }
            proxy.$refs.refTransferConfigParams.editSonValueDataFunc(editType);
          } catch (e) {
            return e;
          }
        } else {
          proxy.$refs.refTransferConfigParams.editSonValueDataFunc({});
        }
      };
      const handlePrev = () => {
        current.value--;
        if (unref(isUpdate)) {
          isEdit.value = true;
          noEditObj = {
            name: editNextType?.name,
            remark: editNextType?.remark,
            type: editNextType?.type,
            id: editPostId?.value,
            configuration: editNextType?.configuration?.configuration,
          };
        }
      };

      const commonFunc = () => {
        try {
          additionalInfoV.additionalInfo.description =
            getSonFormValue.value.configuration.description;
          delete getSonFormValue.value.configuration.description;
          delete getSonFormValue.value.configuration.type;
          delete getSonFormValue.value?.configuration?.name;
        } catch (e) {
          return e;
        }
      };
      const addOrEditFunc = async () => {
        if (!unref(isUpdate)) {
          proxy.$refs.refTransferConfigParams.clearSonValueValidateFunc();
        }
        getModeSonFormValue.value = await proxy.$refs.refTransferConfigMode.getSonValueFunc();
        getSonFormValue.value = await proxy.$refs.refTransferConfigParams.getSonValueDataFunc();

        if (getModeSonFormValue.value?.type == 'org.thingsboard.rule.engine.kafka.TbKafkaNode') {
          getTypeObj.type = 'org.thingsboard.rule.engine.kafka.TbKafkaNode';
        } else if (
          getModeSonFormValue.value?.type == 'org.thingsboard.rule.engine.mqtt.TbMqttNode'
        ) {
          getTypeObj.type = 'org.thingsboard.rule.engine.mqtt.TbMqttNode';
        } else if (
          getModeSonFormValue.value?.type == 'org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode'
        ) {
          getTypeObj.type = 'org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode';
        } else if (
          getModeSonFormValue.value?.type == 'org.thingsboard.rule.engine.rest.TbRestApiCallNode'
        ) {
          getTypeObj.type = 'org.thingsboard.rule.engine.rest.TbRestApiCallNode';
        }
        getTypeObj.remark = getModeSonFormValue.value.remark;
        getNameObj.name = getSonFormValue.value?.configuration?.name;
        commonFunc();
        const id: any = {
          id: unref(isUpdate) ? editPostId.value : '',
        };
        Object.assign(
          allPostForm,
          getTypeObj,
          getSonFormValue.value,
          getNameObj,
          id,
          additionalInfoV.additionalInfo.description ? additionalInfoV : {},
          {
            datasourceType: getModeSonFormValue.value.datasourceType,
            datasourceContent: getModeSonFormValue.value.datasourceContent,
          }
        );
        if (!unref(isUpdate)) {
          delete allPostForm.id;
        }
      };
      const setConfiguration = (record: Recordable) => {
        const type = Reflect.get(record, 'type');
        const configuration = Reflect.get(record, 'configuration');
        const clientProperties = Reflect.get(configuration, 'clientProperties');
        !clientProperties && (record.configuration.clientProperties = {});

        if (
          type === 'org.thingsboard.rule.engine.mqtt.TbMqttNode' ||
          type === 'org.thingsboard.rule.engine.kafka.TbKafkaNode' ||
          type === 'org.thingsboard.rule.engine.rest.TbRestApiCallNode'
        ) {
          Reflect.deleteProperty(configuration, 'clientProperties');
        }

        if (type === 'org.thingsboard.rule.engine.kafka.TbKafkaNode') {
          const otherProperties = Reflect.get(configuration, 'otherProperties');
          configuration.kafkaHeadersCharset = 'UTF-8';
          !otherProperties && (record.configuration.otherProperties = {});
        }

        if (type === 'org.thingsboard.rule.engine.rabbitmq.TbRabbitMqNode') {
          configuration.exchangeNamePattern = configuration.exchangeNamePattern || '';
          configuration.routingKeyPattern = configuration.routingKeyPattern || '';
        }
      };

      const handleSubmit = async (closeModalAfterSuccess = true) => {
        try {
          closeModalAfterSuccess && setModalProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await addOrEditFunc();
            if (allPostForm.name == undefined) {
              return createMessage.error('请填写配置参数名称');
            }
            //验证属性新增了必填
            const isApiHeaders =
              allPostForm?.configuration?.headers ||
              allPostForm?.configuration?.otherProperties ||
              allPostForm?.configuration?.clientProperties;
            if (isApiHeaders && Object.keys(isApiHeaders).includes('')) {
              return createMessage.error('请填写属性');
            }
            if (isApiHeaders && Object.values(isApiHeaders).includes('')) {
              return createMessage.error('请填写属性');
            }
            setConfiguration(allPostForm);
            const res = await postAddConvertApi(allPostForm);
            if (res) {
              closeModalAfterSuccess && closeModal();
              closeModalAfterSuccess && createMessage.success('数据流转新增成功');
              setTimeout(() => {
                emit('success');
              }, 500);
              closeModalAfterSuccess && defineClearFunc();
            }
          } else {
            await addOrEditFunc();
            if (!isEdit.value) {
              //验证属性新增了必填
              const isApiHeaders =
                allPostForm?.configuration?.headers ||
                allPostForm?.configuration?.otherProperties ||
                allPostForm?.configuration?.clientProperties;
              if (isApiHeaders && Object.keys(isApiHeaders).includes('')) {
                return createMessage.error('请填写属性');
              }
              if (isApiHeaders && Object.values(isApiHeaders).includes('')) {
                return createMessage.error('请填写属性');
              }
            }
            Object.assign(noEditObj, getTypeObj, {
              datasourceType: allPostForm.datasourceType,
              datasourceContent: allPostForm.datasourceContent,
            });
            setConfiguration(allPostForm);
            setConfiguration(noEditObj);
            const res = await postAddConvertApi(isEdit.value ? noEditObj : allPostForm);
            if (res) {
              closeModalAfterSuccess && closeModal();
              closeModalAfterSuccess && createMessage.success('数据流转编辑成功');
              setTimeout(() => {
                emit('success');
              }, 500);
              closeModalAfterSuccess && defineClearFunc();
            }
          }
        } catch {
        } finally {
          setModalProps({ confirmLoading: false });
        }
      };
      return {
        handleCancel,
        registerDrawer,
        handleSubmit,
        getTitle,
        current,
        handleNext,
        handlePrev,
        getModeSelectVal,
        refTransferConfigParams,
        refTransferConfigMode,
        isViewStatus,
      };
    },
  });
</script>
