<script setup lang="ts">
import XSelect from '@af-mobile-client-vue3/components/core/XSelect/index.vue'
import XSignature from '@af-mobile-client-vue3/components/data/XSignature/index.vue'
import { executeStrFunctionByContext } from '@af-mobile-client-vue3/utils/runEvalFunction'
import CameraView from '@af-mobile-client-vue3/views/SafeInspection/SecurityFormItem/CameraView/index.vue'
import XMultiSelect from '@af-mobile-client-vue3/views/SafeInspection/SecurityFormItem/XMultiSelect/index.vue'
import dayjs from 'dayjs/esm/index'
import { debounce } from 'lodash-es'
import {
  Checkbox as VanCheckbox,
  CheckboxGroup as VanCheckboxGroup,
  DatePicker as VanDatePicker,
  Field as VanField,
  Image as VanImage,
  Popup as VanPopup,
  Radio as VanRadio,
  RadioGroup as VanRadioGroup,
} from 'vant'
import { computed, getCurrentInstance, onBeforeMount, onBeforeUnmount, ref, watch } from 'vue'

const props = defineProps({
  item: {
    type: Object,
    required: false,
    default() {
      return {}
    },
  },
  // 传入item数据的结构
  dataStructure: {
    type: Object,
    default() {
      return {}
    },
  },
  formType: {
    type: Object,
    default() {
      return {}
    },
  },
  // 外层整体配置对象（用于监听全局变化触发自定义函数）
  config: {
    type: Object,
    default() {
      return {}
    },
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false,
  },
  userDetail: {
    type: Object,
    required: false,
    default() {
      return {}
    },
  },
  safeConfig: {
    type: Object,
    required: false,
    default() {
      return {}
    },
  },
  // 水印配置
  watermarkConfig: {
    type: Object,
    required: false,
    default() {
      return {}
    },
  },
  // 检查人信息
  checkerInfo: {
    type: Object,
    required: false,
    default() {
      return {}
    },
  },
})
const emit = defineEmits(['valueChange', 'updateFileList', 'photoQualityChange'])
const currentVal = props.item
const dataStructure: any = {
  fieldType: 'type',
  fieldLabel: 'label',
  fieldValue: 'value',
  placeholder: 'placeholder',
  fieldOptions: 'options',
  optionsLabel: 'label',
  optionsValue: 'value',
  ...props.dataStructure,
}
const formType = {
  text: 'text', // 表单项类型
  number: 'number',
  date: 'date',
  year: 'year',
  yearMonth: 'yearMonth',
  radio: 'radio',
  checkbox: 'checkbox',
  multipleSelect: 'multipleSelect',
  select: 'selector',
  picture: 'picture',
  textarea: 'textarea',
  signature: 'signature',
  string: 'string',
  files: 'files',
  ...props.formType,
}
const checkVal = ref([])
const showPicker = ref(false)
const customFunctionStr = ref<string | null>(null)
const debouncedCustomFunc = ref<ReturnType<typeof debounce> | null>(null)
// 拍照/上传相关信息
const cameraData = ref(undefined)
// 日期选择器默认值
const datePickerDefault = ref<string[]>([])

// 监听表单类型变化，更新日期选择器默认值
const stopWatchFieldType = watch(() => currentVal[dataStructure.fieldType], (type) => {
  if (type === formType.year)
    datePickerDefault.value = [dayjs().format('YYYY')]
  else if (type === formType.yearMonth)
    datePickerDefault.value = [dayjs().format('YYYY'), dayjs().format('MM')]
  else if (type === formType.date)
    datePickerDefault.value = [dayjs().format('YYYY'), dayjs().format('MM'), dayjs().format('DD')]
  else
    datePickerDefault.value = []
}, { immediate: true })

// 监听外层整体 config 的变更，若配置了自定义函数则调用（防抖 500ms）
const stopWatchConfig = watch(() => props.config, (newConfig) => {
  if (!customFunctionStr.value || !debouncedCustomFunc.value)
    return
  debouncedCustomFunc.value(currentVal, newConfig, props.userDetail, props.safeConfig)
}, { deep: true })

const columnsType = computed(() => {
  const type = currentVal[dataStructure.fieldType]
  if (type === formType.year)
    return ['year'] as any
  if (type === formType.yearMonth)
    return ['year', 'month'] as any
  return ['year', 'month', 'day'] as any
})

function safeParseJson(jsonStr: any): any {
  if (typeof jsonStr !== 'string')
    return null
  try {
    return JSON.parse(jsonStr)
  }
  catch (e) {
    return null
  }
}
// selVal：组件返回值，selObj：选中的列表(单选/多选/下拉框/下多选拉框 有值 其他类型此参数为undefined)
function confirm(selVal, selObj) {
  // 如果是只读状态，阻止值的变更
  if (props.readonly)
    return

  switch (currentVal[dataStructure.fieldType]) {
    case formType.date:
    case formType.year:
    case formType.yearMonth:
      currentVal.value = selVal.selectedValues.join('-')
      selVal = currentVal.value
      showPicker.value = false
      break
    case formType.radio:
      selObj = currentVal[dataStructure.fieldOptions].filter((optRow) => {
        return optRow[dataStructure.optionsValue] === selVal
      })
      break
    case formType.checkbox:
      selObj = currentVal[dataStructure.fieldOptions].filter((optRow) => {
        return selVal.includes(optRow[dataStructure.optionsValue])
      })
      break
    case formType.multipleSelect:
      currentVal.value = selVal.join(',')
      break
    case formType.select:
      currentVal[dataStructure.fieldValue] = selVal
      break
    case formType.picture:
    case formType.files:
      // 对于拍照/上传类型，更新文件列表并触发文件更新事件
      currentVal[dataStructure.fieldValue] = selVal
      emit('updateFileList', selVal, currentVal)
      break
    default:
      selVal = currentVal.value
  }
  // 切换数据项, 隐患图片重置
  if ('f_defect_paths' in currentVal) {
    currentVal.f_defect_paths = []
  }
  emit('valueChange', selVal, selObj, currentVal)
}
onBeforeMount(() => {
  // 初始化读取 f_data 并提取自定义函数
  if (dataStructure.redundantData && currentVal[dataStructure.redundantData]) {
    const extra = safeParseJson(currentVal[dataStructure.redundantData])
    cameraData.value = extra
    if (extra && typeof extra.f_custom_function === 'string' && extra.f_custom_function.trim().length > 0) {
      customFunctionStr.value = extra.f_custom_function.replace(/&gt;/g, '>')
      // 创建防抖函数（500ms）
      debouncedCustomFunc.value = debounce((ctx: any, cfg: any, userDetail: any, safeConfig: any) => {
        try {
          executeStrFunctionByContext(getCurrentInstance(), customFunctionStr.value as string, [ctx, cfg, userDetail, safeConfig])
          emit('valueChange', null, null, ctx)
        }
        catch (err) {
          console.log(err)
          // 静默失败
        }
      }, 500)
      // 初始化时立即执行一次自定义函数
      try {
        executeStrFunctionByContext(getCurrentInstance(), customFunctionStr.value, [currentVal, props.config, props.userDetail, props.safeConfig])
        emit('valueChange', null, null, currentVal)
      }
      catch (err) {
        console.log(err)
      }
    }
  }
})

/** 提供给每个VanField的自定义属性，用于AI识别跳转时精确定位表单项 */
const fieldAttrs = computed(() => ({
  'data-field-name': currentVal[dataStructure.fieldLabel] || '',
}))

const datePickerMinDate = computed(() => {
  return dayjs().add(-100, 'year').endOf('day').toDate()
})
const datePickerMaxDate = computed(() => {
  return dayjs().add(100, 'year').endOf('day').toDate()
})
// 组件卸载时清理：取消防抖函数、清除实例引用、停止 watch
onBeforeUnmount(() => {
  if (debouncedCustomFunc.value?.cancel) {
    debouncedCustomFunc.value.cancel()
    debouncedCustomFunc.value = null
  }
  // 停止所有 watch，防止内存泄漏
  stopWatchFieldType()
  stopWatchConfig()
})
</script>

<template>
  <VanField
    v-if="currentVal[dataStructure.fieldType] === formType.text || currentVal[dataStructure.fieldType] === formType.string"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    center
    :name="currentVal[dataStructure.fieldLabel]"
    :label="currentVal[dataStructure.fieldLabel]"
    :placeholder="currentVal[dataStructure.placeholder]"
    :required="props.item.checkmust === 'true'"
    :readonly="props.readonly"
    :rules="[{ required: props.item.checkmust === 'true', message: `请输入${props.item.itemname}` }]"
    @blur="confirm"
  />
  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.number"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    center
    :label="currentVal[dataStructure.fieldLabel]"
    type="number"
    :placeholder="currentVal[dataStructure.placeholder]"
    :required="props.item.checkmust === 'true'"
    :readonly="props.readonly"
    :rules="[{ required: props.item.checkmust === 'true', message: `请输入${props.item.itemname}` }]"
    @blur="confirm"
  />
  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.date || currentVal[dataStructure.fieldType] === formType.year || currentVal[dataStructure.fieldType] === formType.yearMonth"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    center
    is-link
    :readonly="props.readonly || true"
    name="datePicker"
    :label="currentVal[dataStructure.fieldLabel]"
    :placeholder="currentVal[dataStructure.placeholder]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请输入${props.item.itemname}` }]"
    @click="!props.readonly && (showPicker = true)"
  />
  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.textarea"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    type="textarea"
    center
    :readonly="props.readonly"
    name="textarea"
    :label="currentVal[dataStructure.fieldLabel]"
    :placeholder="currentVal[dataStructure.placeholder]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请输入${props.item.itemname}` }]"
    style="display: flex; flex-direction: column; align-items: flex-start; color: #336BF1;"
    @blur="confirm"
  />

  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.radio"
    v-bind="fieldAttrs"
    center
    name="radio"
    :label="currentVal[dataStructure.fieldLabel]"
    label-align="top"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请选择${props.item.itemname}` }]"
  >
    <template #input>
      <VanRadioGroup v-model="currentVal[dataStructure.fieldValue]" class="sec-radio" direction="horizontal" :disabled="props.readonly" @change="confirm">
        <VanRadio v-for="(opt, index) in currentVal[dataStructure.fieldOptions]" :key="index" class="checkbox-sty" :name="opt[dataStructure.optionsLabel]" :value="opt[dataStructure.optionsValue]">
          {{ opt[dataStructure.optionsLabel] }}
        </VanRadio>
      </VanRadioGroup>
    </template>
  </VanField>
  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.checkbox"
    v-bind="fieldAttrs"
    center
    name="checkboxGroup"
    :label="currentVal[dataStructure.fieldLabel]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请选择${props.item.itemname}` }]"
  >
    <template #input>
      <VanCheckboxGroup v-model="checkVal" direction="horizontal" :disabled="props.readonly" @change="confirm">
        <VanCheckbox v-for="(opt, index) in currentVal[dataStructure.fieldOptions]" :key="index" class="checkbox-sty" :name="opt[dataStructure.optionsValue]" shape="square">
          {{ opt[dataStructure.optionsLabel] }}
        </VanCheckbox>
      </VanCheckboxGroup>
    </template>
  </VanField>

  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.signature"
    v-bind="fieldAttrs"
    center
    name="signature"
    :label="currentVal[dataStructure.fieldLabel]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请选择${props.item.itemname}` }]"
  >
    <template #input>
      <div class="signature-demo">
        <XSignature
          v-model="currentVal[dataStructure.fieldValue]"
          :show-button-after-signed="true"
          :show-preview="true"
          :disabled="props.readonly"
        />
        <div v-if="currentVal[dataStructure.fieldValue]" class="preview">
          <h5>预览签名</h5>
          <VanImage v-if="currentVal[dataStructure.fieldValue]" :src="currentVal[dataStructure.fieldValue]" />
        </div>
      </div>
    </template>
  </VanField>

  <XMultiSelect
    v-else-if="currentVal[dataStructure.fieldType] === formType.multipleSelect"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    center
    name="multipleSelect"
    :label="currentVal[dataStructure.fieldLabel]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请选择${props.item.itemname}` }]"
    :placeholder="currentVal[dataStructure.placeholder]"
    :columns="currentVal[dataStructure.fieldOptions]"
    :disabled="props.readonly"
    @confirm="confirm"
  />

  <XSelect
    v-else-if="currentVal[dataStructure.fieldType] === formType.select"
    v-model="currentVal[dataStructure.fieldValue]"
    v-bind="fieldAttrs"
    :placeholder="currentVal[dataStructure.placeholder]"
    :columns="currentVal[dataStructure.fieldOptions]"
    center
    name="select"
    :option="{ text: dataStructure.optionsLabel, value: dataStructure.optionsValue }"
    :label="currentVal[dataStructure.fieldLabel]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请选择${props.item.itemname}` }]"
    :readonly="props.readonly"
    @confirm="confirm"
  />

  <VanField
    v-else-if="currentVal[dataStructure.fieldType] === formType.picture || currentVal[dataStructure.fieldType] === formType.files"
    v-bind="fieldAttrs"
    center
    name="picture"
    :label="currentVal[dataStructure.fieldLabel]"
    :required="props.item.checkmust === 'true'"
    :rules="[{ required: props.item.checkmust === 'true', message: `请上传${props.item.itemname}的图片` }]"
  >
    <template #input>
      <CameraView
        upload-mode="server"
        :image-list="(currentVal[dataStructure.fieldValue] as any[])"
        authority="admin"
        :attr="{
          addOrEdit: 'addOrEdit',
          acceptCount: (cameraData?.f_number ?? 3),
          uploadImage: !props.readonly && (cameraData?.f_upload === '是'),
          watermark: {
            ...props.watermarkConfig,
            userName: props.checkerInfo?.name || '',
          },
        }"
        :disabled="props.readonly"
        @update-file-list="confirm"
        @photo-quality-change="(type) => emit('photoQualityChange', type)"
      />
    </template>
  </VanField>
  <!--  {{ currentVal }} -->
  <VanPopup v-model:show="showPicker" position="bottom">
    <VanDatePicker v-model="datePickerDefault" :columns-type="columnsType" :min-date="datePickerMinDate" :max-date="datePickerMaxDate" @confirm="confirm" @cancel="showPicker = false" />
  </VanPopup>
  <slot :item="currentVal" />
</template>

<style scoped lang="less">
.signature-demo {
  padding: 16px;
  .preview {
    margin-top: 20px;
    h5 {
      margin: 0 0 10px;
      font-size: 16px;
      color: #323233;
    }
    img {
      max-width: 100%;
      border: 1px solid #ebedf0;
      border-radius: 8px;
    }
  }
}

.checkbox-sty {
  padding: 3px;
}
.sec-radio {
  --van-radio-disabled-label-color: black;
  --van-radio-disabled-icon-color: black;
  :deep(.van-radio__icon--disabled .van-icon) {
    border-color: var(--van-radio-disabled-background);
  }
  gap: 10px;
  margin: 5px 0;
}
</style>
