<template>
  <div>
    <vxe-modal
      title="查看"
      :z-index="zIndex"
      :value="isShow"
      @input="e => $emit('update:isShow', e)"
      size="mini"
      :loading="loading"
      :id="id.toString()"
      :lock-view="false"
      :lock-scroll="false"
      :mask="false"
      :min-height="300"
      resize
      :fullscreen="$store.getters.device === 'mobile'"
      show-zoom
      draggable
      storage
      :padding="false"
      :position="$store.getters.device === 'mobile' ? {} : pos">
      <div :style="$store.getters.device === 'desktop' ? 'max-height: 60vh' : '' ">
        <DesktopForm
          device="mobile"
          ref="mobileForm"
          :config="config"
          :is-first-node="false"
          :sub-form="subConfig"
          :fields="fields"
          :original-form="form"
          :readable="config.customModel ? config.customModel.fields.map(i => i.id) : []"
          :writeable="[]"
          :needFlowTitle="false"
          :logs="config.logs"
        ></DesktopForm>
      </div>
    </vxe-modal>
  </div>
</template>

<script>
import {
  fieldConfig,
  view,
} from "@/api/flow";
import DesktopForm from "@/views/flow/DesktopForm.vue";
import { PopupManager } from 'element-ui/lib/utils/popup'

export default {
  components: {
    DesktopForm
  },
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String,Number],
      default: ""
    },
    pos: {
      type: Object,
      default: () => ({ top: 0, left: 0 })
    }
  },
  data() {
    return {
      zIndex: PopupManager.nextZIndex(),
      loading: false,
      form: {},
      subConfig: new Map(),
      config: {},
      fields: [],
    }
  },
  methods: {
    generateForm(object, fields, relation = false, pname) {
      fields.forEach((field) => {
        if (field.type === "relation") {
          object[field.name] = [{}];

          this.generateForm(
            object[field.name][0],
            this.subConfig.get(field.sub_custom_model_id)?.customModel?.fields,
            true,
            field.name
          );
        } else {
          object[field.name] = "";
        }
      });
    },
    async getConfig() {
      this.loading = true
      try {
        const res = await view(this.id);
        let { fields } = res?.customModel;
        fields = fields.filter(i => i.show_in_list)
        this.fields = fields
        let subFormRequest = [];
        const getSubForm = async (id) => {
          subFormRequest.push(fieldConfig(id));
        };
        for (let j = 0;j < fields.length;j++) {
          let field = fields[j]
          if (field.sub_custom_model_id) {
            await getSubForm(field.sub_custom_model_id);
          }
        }
        const subConfigs = await Promise.all(subFormRequest);
        subConfigs.forEach((sub) => {
          if (sub.customModel?.id) {
            this.subConfig.set(sub.customModel?.id, sub);
          }
        });
        this.config = res;
        this.generateForm(this.form, fields);
        this.form = Object.assign({}, this.form);
        const { data } = res?.flow;
        for (let key in data) {
          try {
            let jsonObj = JSON.parse(data[key]);
            jsonObj.forEach(item => {
              // 遍历对象中的每个键值对
              for (const key in item) {
                if (typeof item[key] === 'string') {
                  try {
                    // 尝试解析字符串为 JSON 对象
                    const parsedValue = JSON.parse(item[key]);
                    // 如果解析成功，替换原始字符串
                    item[key] = parsedValue;
                  } catch (e) {
                    // 如果解析失败，继续保持原始字符串
                  }
                }
              }
            })
            if (this.form.hasOwnProperty(key)) {
              this.form[key] = jsonObj;
            }
          } catch (err) {
            if (this.form.hasOwnProperty(key)) {
              if (data[key] instanceof Array) {
                if (data[key].length > 0 && data[key][0].hasOwnProperty('url')) {
                  this.form[key] = data[key].map(i => ({
                    name: i.original_name,
                    url: i.url,
                    response: i,
                  }))
                } else {
                  this.form[key] = ''
                }
              }
              this.form[key] = data[key];
            }
          }
        }
        this.loading = false
      } catch (err) {
        console.error(err);
        this.$message.error("配置失败");
        this.loading = false
      }
    }
  },
  computed: {},
  watch: {
    id(newVal) {
      if (!!newVal) {
        this.getConfig()
      }
    },
    isShow(newVal) {
      if (newVal) {
        this.zIndex = PopupManager.nextZIndex()
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>
