<template>
  <component
    :class="{ 'w-full': ['number', 'time', 'date', 'month', 'select', 'treeSelect'].includes(record.componentCode) && !record.width }"
    :is="componentItem"
    v-if="componentItem"
    v-bind="{ ...cmpProps, ...asyncProps }"
    :record="record"
    :readonly="props.readonly"
    :isDesgin="props.isDesgin"
    :formRef="props.formRef"
    :formConfig="props.formConfig"
    @onClick="onClick"
    @onChange="onChange"
    @onBlur="onBlur"
    @onInput="onInput"
    @onFocus="onFocus"
    :formData="props.formData"
    :style="record.width ? { width: record.width } : {}"
    v-model:value="props.formData[record.fieldCode]"
  >
    <span v-if="['button'].includes(record.componentCode)">{{ record.label }}</span>
  </component>
</template>

<script setup name="FormItemComponent">
import { computed, onMounted } from 'vue';
import { omit } from 'lodash-es';
import { componentMap } from '../element/index';
import { handleAsyncOptions } from '../utils/index';
import { asyncComputed } from '@vueuse/core';
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store/modules/user';
import Request from '@/utils/request/request-util';

const props = defineProps({
  // 表单数据
  formData: {
    type: Object,
    default: () => ({})
  },
  //当前item
  record: {
    type: Object,
    required: true
  },
  formConfig: {
    type: Object,
    required: true
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  // 是否是设计
  isDesgin: {
    type: Boolean,
    default: false
  },
  // ref
  formRef: {
    type: Object,
    default: null
  }
});

const emits = defineEmits(['onClick', 'onChange', 'onBlur', 'onInput', 'onFocus']);

const { info } = storeToRefs(useUserStore());

const userBaseInfo = computed(() => {
  let userOrgInfo = info.value?.userOrgInfoList?.find(item => item.mainFlag);
  return {
    userId: info.value?.userId,
    userName: info.value?.realName,
    companyId: userOrgInfo?.companyId,
    companyName: userOrgInfo?.companyName,
    orgId: userOrgInfo?.orgId,
    orgName: userOrgInfo?.deptName
  };
});

// 获取当前组件
const componentItem = computed(() => componentMap[props.record.componentCode]);

/**
 * 处理异步属性，异步属性会导致一些属性渲染错误，如defaultValue异步加载会导致渲染不出来，故而此处只处理options，treeData，同步属性在cmpProps中处理
 */
const asyncProps = asyncComputed(async () => {
  let { options, treeData } = props.record.props ?? {};
  if (options) options = await handleAsyncOptions(options);
  if (treeData) treeData = await handleAsyncOptions(treeData);
  return {
    options,
    treeData
  };
});
/**
 * 处理同步属性
 */
const cmpProps = computed(() => {
  let disabled = false;
  let { ...attrs } = omit(props.record.formItemSelect, ['options', 'treeData']) ?? {};
  if (props.record.itemEditFlag) {
    disabled = false;
  } else {
    disabled = true;
  }
  return { ...attrs, disabled };
});

const onClick = record => {
  emits('onClick', record);
};
const onChange = record => {
  emits('onChange', record);
};
const onBlur = record => {
  emits('onBlur', record);
};
const onFocus = record => {
  emits('onFocus', record);
};
const onInput = record => {
  emits('onInput', record);
};

onMounted(() => {
  loadDefaultValue();
});

const loadDefaultValue = () => {
  const { formItemDataLoad, componentCode } = props.record;
  let codeList = ['input', 'phone', 'email', 'idcard'];

  if (formItemDataLoad && codeList.includes(componentCode)) {
    const { dataLoadType, apiRequestParamList, apiUrl, httpMethod, staticData, userInfoFieldName } = formItemDataLoad;

    if (dataLoadType == 1) {
      // 静态数据
      props.formData[props.record.fieldCode] = staticData;
    } else if (dataLoadType == 2) {
      // api调用
      if (apiUrl && httpMethod) {
        let params = {};
        apiRequestParamList?.forEach(item => {
          params[item.paramName] = item.paramValue;
        })
        Request[httpMethod](apiUrl, params).then(res => {
          props.formData[props.record.fieldCode] = res.data;
        })
      }
    } else if (dataLoadType == 3) {
      // 当前用户信息
      if (userInfoFieldName == '1') {
        props.formData[props.record.fieldCode] = userBaseInfo.value.userName;
      } else if (userInfoFieldName == '2') {
        props.formData[props.record.fieldCode] = userBaseInfo.value.companyName;
      } else if (userInfoFieldName == '3') {
        props.formData[props.record.fieldCode] = userBaseInfo.value.orgName;
      }
    }
  }
};
</script>

<style></style>
