<!-- FormBox.vue -->
<template>
	<div>
		<div v-if="dialog">
			<el-dialog 
        :close-on-click-modal="false" 
        draggable 
        :title="dialogTitle" 
        v-model="dialogVisible" 
        width="1000px"
        top="10vh"
        @close="handleDialogClose"
      >
				<el-card :body-style="cardBodyStyle">
					<el-form v-if="formItems && formItems.length > 0" :model="formData" label-width="auto"
						label-position="right">
						<div v-for="(itemList, indexList) in formList" :key="indexList">
							<el-row style="margin-bottom: 5px;" :gutter="10">
								<el-col v-for="(item, index) in itemList" :key="index" :span="item.span">
									<el-form-item :label="item.label" :prop="item.prop">
										<!--文本-->
										<el-input v-if="item.type === 'input'" v-model="formData[item.prop]" clearable
											placeholder="请输入" style="width:100%; ">
											<template #append v-if="item.searchButton==true||item.searchButton=='1'?true:false">
												<el-button @click="emit(item.searchCallback)">
													<el-icon>
														<Search />
													</el-icon></el-button>
											</template>
										</el-input>
										<!-- 下拉 -->
										<el-select v-if="item.type === 'select'" v-model="formData[item.prop]" clearable
											style="width:100%; ">
											<el-option v-for="(option,i) in item.options" :key="i"
												:value="option[item.optionValue?item.optionValue:'value']"
												:label="option[item.optionLabel?item.optionLabel:'label']" />
										</el-select>
										<!-- 单选 -->
										<el-radio-group v-if="item.type === 'radio'" v-model="formData[item.prop]"
											style="width:100%; ">
											<el-radio v-for="(option,i) in item.options" :key="i"
												:label="option[item.optionValue?item.optionValue:'value']">
												{{option[item.optionLabel?item.optionLabel:'label']}}
											</el-radio>
										</el-radio-group>
										<!--日期-->
										<el-date-picker v-if="item.type === 'date'" v-model="formData[item.prop]"
											type="date" clearable value-format="YYYY-MM-DD" format="YYYY-MM-DD"
											style="width:100%; " />
										<!--日期范围-->
										<el-date-picker v-if="item.type === 'daterange'" v-model="formData[item.prop]"
											type="daterange" clearable range-separator="至" start-placeholder="开始日期"
											end-placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD"
											style="width:100%; "></el-date-picker>
										<!--日期时间范围-->
										<el-date-picker v-if="item.type === 'datetimerange'" v-model="formData[item.prop]"
											type="daterange" range-separator="至" start-placeholder="开始时间"
											end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
											format="YYYY-MM-DD HH:mm:ss" style="width: 350px; " />
										<!--文本-->
										<el-input v-if="item.type === 'textarea'" type="textarea" v-model="formData[item.prop]" clearable
											placeholder="请输入" style="width:100%; " :rows="4"/>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>

				<template #footer>
					<div class="dialog-footer">
						<el-button type="success" @click="handleSave">保存</el-button>
						<el-button type="danger" @click="handleClose">取消</el-button>
					</div>
				</template>
			</el-dialog>
		</div>
		<!-- 非弹窗模式省略... -->
	</div>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  onMounted,
  watch,
  nextTick
} from 'vue'
import { Search } from '@element-plus/icons-vue'

const {
  proxy
} = getCurrentInstance()

import style from '@/tools/style'
const cardBodyStyle = ref(style.card)

// Props
const props = defineProps({
  formData: {
    type: Object,
    default: () => ({})
  },
  formName: {
    type: String,
    default: () => ''
  },
  dialog: {
    type: Boolean,
    default: () => false
  },
  title: {
    type: String,
    default: '编辑'
  }
})

// Emits
const emit = defineEmits(['save', 'update:dialog', 'close'])

// 响应式数据
const formItems = ref([])
const formList = ref([])
const dicTypes = ref([])
const urls = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('编辑')

// 监听 dialog prop 变化
watch(() => props.dialog, (newVal) => {
  console.log('FormBox dialog prop changed:', newVal)
  dialogVisible.value = newVal
  if (newVal) {
    dialogTitle.value = props.formData?.id ? '编辑客户' : '新增客户'
  }
}, { immediate: true })

// 监听内部 dialogVisible 变化
watch(dialogVisible, (newVal) => {
  console.log('FormBox dialogVisible changed:', newVal)
  emit('update:dialog', newVal)
  if (!newVal) {
    emit('close')
  }
})

onMounted(() => {
  if (props.formName) {
    getMenuForm()
  }
})

// 获取表单配置
const getMenuForm = () => {
  var url = 'framework/MenuForm/queryMenuForm'
  var param = {
    menuId: localStorage.getItem('menuId'),
    formType: '录入',
    formName: props.formName
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      formItems.value = response.data.data
      init()
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

// 初始化表单布局
const init = async () => {
  var colsCount = 4
  var length = Math.ceil(formItems.value.length / colsCount)
  var arr = []
  for (var i = 0; i < length; i++) {
    arr.push([])
  }
  var col = 0
  formItems.value.forEach((item, index) => {
    col = Math.floor(index / colsCount)
	if(item.formType == "录入" && item.type != 'textarea'){
		item.span = 12
	}else if (item.type == 'datetimerange') {
      item.span = 12
    } else if(item.type == 'textarea'){
		item.span = 24
	} else {
      item.span = 6
    }
	
    if ((item.type == 'select' || item.type == 'radio') && item.dicType && item.dicType != null &&
      item.dicType != '') {
      dicTypes.value.push(item.dicType)
    }

    if ((item.type == 'select' || item.type == 'radio') && item.url && item.url != null && item.url != '') {
      urls.value.push({
        'url': item.url,
        'param': item.param,
        'optionLabel': item.optionLabel,
        'optionValue': item.optionValue,
      })
    }
    arr[col].push(item)
  })
  formList.value = arr

  if (dicTypes.value.length > 0) {
    getDic()
  }
  
  if (urls.value.length > 0) {
    for (var item of urls.value) {
      await getOption(item)
    }
  }
}

// 获取字典数据
const getDic = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(dicTypes.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      for (let key in response.data.data) {
        for (var item of formItems.value) {
          if ((item.type == 'select' || item.type == 'radio') && item.dicType && item.dicType != null && item.dicType != '') {
            if (key == item.dicType) {
              item.options = response.data.data[key]
              item.optionLabel = 'dicName'
              item.optionValue = 'dicCode'
            }
          }
        }
      }
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

// 获取选项数据
const getOption = (item) => {
  return new Promise((resolve) => {
    var url = item.url
    var param = item.param
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        for (var form of formItems.value) {
          if (form.url == item.url) {
            form.options = response.data.data
            form.optionLabel = item.optionLabel
            form.optionValue = item.optionValue
          }
        }
        resolve()
      } else {
        ElMessage.error('操作失败！' + response.data.msg)
        resolve()
      }
    }).catch(() => {
      resolve()
    })
  })
}

// 保存
const handleSave = () => {
  console.log('保存表单数据:', props.formData)
  emit('save', props.formData)
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}

// 弹窗关闭事件
const handleDialogClose = () => {
  dialogVisible.value = false
}

// 暴露给父组件的方法
const open = () => {
  dialogVisible.value = true
}

const close = () => {
  dialogVisible.value = false
}

defineExpose({
  open,
  close
})
</script>

<style>
.search-bar {
  display: flex;
  flex-direction: row;
}

.search-bar .form {
  display: flex;
  flex-direction: row;
}

.search-bar .button {
  display: flex;
  flex-direction: row;
}
</style>