<template>
  <a-modal
    v-model:open="visible"
    title="编辑电站"
    width="80vw"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      class="max-h-[70vh] overflow-y-auto pr-4"
    >
      <a-row :gutter="16">
        <template v-for="(col, index) in formColumns" :key="index">
          <!-- 分组标题 -->
          <template v-if="col.isTitle">
            <a-col :span="24">
              <div class="form-group-title">{{ col.name }}</div>
            </a-col>
          </template>
          <!-- 表单字段 -->
          <a-col v-else :span="8">
            <a-form-item
              :label="col.name"
              :name="col.filed"
              :rules="getRules(col)"
            >
              <a-form-item-rest>
                <!-- 输入框 -->
                <a-input
                  v-if="col.type === 'input'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请输入${col.name}`"
                />
                <!-- 数字 -->
                <a-input-number
                  v-else-if="col.type === 'number'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请输入${col.name}`"
                  :precision="col.toFixed"
                  style="width: 100%"
                />
                <!-- 日期 -->
                <a-date-picker
                  v-else-if="col.type === 'date'"
                  v-model:value="formData[col.filed]"
                  :format="col.format || 'YYYY-MM-DD'"
                  :value-format="col.format || 'YYYY-MM-DD'"
                  :placeholder="`请选择${col.name}`"
                  style="width: 100%"
                />
                <!-- 下拉选择 - 所属集团 -->
                <a-select
                  v-else-if="col.type === 'select' && col.filed === 'topHynm'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请选择${col.name}`"
                  allow-clear
                  show-search
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="item in topHynmList"
                    :key="item.hycd"
                    :label="item.hynm"
                    :value="item.hycd"
                  >
                    {{ item.hynm }}
                  </a-select-option>
                </a-select>
                <!-- 下拉选择 - 所属公司 -->
                <a-select
                  v-else-if="col.type === 'select' && col.filed === 'hynm'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请选择${col.name}`"
                  allow-clear
                  show-search
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="item in hycdList"
                    :key="item.hycd"
                    :label="item.hynm"
                    :value="item.hycd"
                  >
                    {{ item.hynm }}
                  </a-select-option>
                </a-select>
                <!-- 下拉选择 - 开发方式 -->
                <a-select
                  v-else-if="col.type === 'select' && col.filed === 'dvtpName'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请选择${col.name}`"
                  allow-clear
                >
                  <a-select-option
                    v-for="item in dvtpList"
                    :key="item.value"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
                <!-- 下拉选择 - 其他 -->
                <a-select
                  v-else-if="col.type === 'select'"
                  v-model:value="formData[col.filed]"
                  :placeholder="`请选择${col.name}`"
                  allow-clear
                >
                  <!-- 这里可以根据需要添加选项 -->
                </a-select>
                <!-- 默认输入框 -->
                <a-input
                  v-else
                  v-model:value="formData[col.filed]"
                  :placeholder="`请输入${col.name}`"
                />
              </a-form-item-rest>
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { BasicColumns } from '@/components/MapModal/column.config';
import { updatePowerInfo } from '@/api/DataQueryMenuModule';

const props = defineProps<{
  open: boolean;
  record?: any;
  topHynmList?: any[];
  hycdList?: any[];
}>();

const emit = defineEmits(['update:open', 'success']);

const visible = computed({
  get: () => props.open,
  set: val => emit('update:open', val)
});

const formRef = ref();
const confirmLoading = ref(false);
const formData = ref<any>({});

// 开发方式选项
const dvtpList = ref<any[]>([
  { label: '堤坝式', value: '0' },
  { label: '引水式', value: '1' },
  { label: '混合式', value: '2' }
]);

// 处理 BasicColumns，将 visible: false 的作为分组标题
const formColumns = computed(() => {
  return BasicColumns.filter(col => col.filed !== '' && col.type !== '').map(
    col => ({
      ...col,
      isTitle: !col.visible
    })
  );
});

// 获取表单验证规则
const getRules = (col: any) => {
  const rules: any[] = [];
  // 根据需要添加验证规则
  if (col.type === 'number') {
    rules.push({
      type: 'number',
      message: `${col.name}必须是数字`
    });
  }
  return rules;
};
const filterOption = (inputValue: string, option: any) => {
  const label = option.label || '';
  const keyword = inputValue || '';
  return label.includes(keyword);
};
// 将值中的"-"转换为null
const convertDashToNull = (obj: any) => {
  const result: any = {};
  for (const key in obj) {
    if (obj[key] === '-' || obj[key] === '') {
      result[key] = null;
    } else {
      result[key] = obj[key];
    }
  }
  return result;
};

// 监听 record 变化，填充表单
watch(
  () => props.record,
  newRecord => {
    if (newRecord) {
      formData.value = convertDashToNull({ ...newRecord });
    }
  },
  { deep: true }
);

const handleOk = async () => {
  try {
    await formRef.value?.validateFields();
    confirmLoading.value = true;

    // 提交时将"-"和空值转换为null
    const submitData = convertDashToNull(formData.value);

    const res = await updatePowerInfo(submitData);
    if (res?.code === 200 || res?.success) {
      message.success('编辑成功');
      visible.value = false;
      emit('success');
    } else {
      message.error(res?.msg || '编辑失败');
    }
  } catch (error) {
    console.error('验证失败:', error);
  } finally {
    confirmLoading.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
  formRef.value?.resetFields();
};
</script>

<style scoped lang="scss">
.form-group-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 12px 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 16px;
}
</style>
