<template>
  <a-modal
    :title="isEdit ? '编辑倾斜摄影' : '新增倾斜摄影'"
    v-model:open="modalVisible"
    :confirm-loading="localLoading"
    width="600px"
    :destroy-on-close="true"
    ok-text="保存"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      name="edit_form"
      :labelCol="{ span: 5 }"
    >
      <a-form-item label="倾斜影像名称" name="stnm">
        <a-input
          v-model:value="formData.stnm"
          style="width: 100%"
          placeholder="请输入倾斜影像名称"
        />
      </a-form-item>
      <a-form-item label="所在河段" name="hbrvcd">
        <a-select
          v-model:value="formData.hbrvcd"
          show-search
          style="width: 100%"
          placeholder="请选择所在河段"
          :options="riverOptions"
          :filter-option="filterOption"
          :disabled="isEdit"
          @change="handleRiverSelect"
        />
      </a-form-item>
      <a-form-item label="所属电站" name="rstcd">
        <a-select
          v-model:value="formData.rstcd"
          show-search
          style="width: 100%"
          placeholder="请选择所属电站"
          :options="ennmOptions"
          :filter-option="filterOption"
          :disabled="isEdit"
        />
        <!-- <a-input
          v-model:value="formData.ennm"
          style="width: 100%"
          placeholder="请输入所属电站"
        /> -->
      </a-form-item>
      <a-form-item label="倾斜影像URL" name="url">
        <a-input
          v-model:value="formData.url"
          style="width: 100%"
          placeholder="请输入倾斜影像URL"
        />
      </a-form-item>
      <a-form-item label="模型坐标" name="location">
        <a-textarea
          v-model:value="formData.location"
          :rows="4"
          style="width: 100%"
          placeholder="请输入模型坐标"
        />
      </a-form-item>
      <a-form-item label="模型精度" name="accuracy">
        <a-input-number
          v-model:value="formData.accuracy"
          style="width: 100%"
          placeholder="请输入模型精度"
          :min="0"
        />
      </a-form-item>
      <a-form-item label="边界范围" name="boundary">
        <a-textarea
          v-model:value="formData.boundary"
          :rows="4"
          style="width: 100%"
          placeholder="请输入边界范围"
        />
      </a-form-item>
      <a-form-item label="模型高度" name="height">
        <a-input-number
          v-model:value="formData.height"
          style="width: 100%"
          placeholder="请输入模型高度"
          :min="0"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          v-model:value="formData.comments"
          :rows="4"
          style="width: 100%"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import dayjs from 'dayjs';
import { getEngInfoDropdown } from '@/api/select';
interface Props {
  visible: boolean;
  initialValues?: any | null;
  loading?: boolean;
  riverOptions?: any[];
}
const localLoading = ref(false);
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  initialValues: null,
  loading: false,
  riverOptions: () => []
});

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

const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'cancel'): void;
  (e: 'ok', values: any): void;
}>();

const formRef = ref();

const defaultFormData = reactive({
  id: undefined,
  stnm: undefined,
  hbrvcd: undefined,
  rstcd: undefined,
  url: undefined,
  location: undefined,
  accuracy: undefined,
  boundary: undefined,
  height: undefined,
  comments: undefined
});
const formData: any = reactive({ ...defaultFormData });

const rules: Record<string, Rule[]> = {
  stnm: [{ required: true, message: '请输入倾斜影像名称', trigger: 'blur' }],
  hbrvcd: [{ required: true, message: '请输入所在河段', trigger: 'blur' }],
  rstcd: [{ required: true, message: '请输入所属电站', trigger: 'blur' }],
  url: [{ required: true, message: '请输入倾斜影像URL', trigger: 'blur' }],
  location: [{ required: true, message: '请输入模型坐标', trigger: 'blur' }]
};

const isEdit = computed(() => !!props.initialValues);

const handleOk = async () => {
  try {
    await formRef.value.validate();
    const ennmItem = ennmOptions.value.find(item => item.value == formData.rstcd);
    const riverItem = props.riverOptions.find(item => item.value == formData.hbrvcd);
    const submitValues = {
      ...formData,
      ennm: ennmItem?.ennm || '',
      hbrvcdName: riverItem?.label || '',
      captureDate: formData.captureDate
        ? dayjs(formData.captureDate).format('YYYY-MM-DD')
        : undefined,
    };

    emit('ok', submitValues);
  } catch (error) {
    console.error('Validate Failed:', error);
    message.error('请检查表单填写是否正确');
  }
};

const initForm = () => {
  if (props.initialValues) {
    const values = props.initialValues;
    Object.keys(formData).forEach(key => {
      if (values.hasOwnProperty(key)) {
        if (key === 'captureDate' && values[key]) {
          formData[key] = dayjs(values[key]);
        } else {
          formData[key] = values[key];
        }
      }
    });
  } else {
    resetForm();
  }
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, defaultFormData);
};

const handleCancel = () => {
  emit('update:visible', false);
  emit('cancel');
  resetForm();
};
// 搜索过滤
const filterOption = (inputValue: string, option: any) => {
  const label = option.label || option.name || '';
  const reachcdName = option.reachcdName || '';
  const keyword = inputValue || '';

  return label.indexOf(keyword) !== -1 || reachcdName.indexOf(keyword) !== -1;
};
const ennmOptions = ref([]);
const handleRiverSelect = async (value: any) => {
  let res: any = await getEngInfoDropdown({ reachcd: value });
  if (res?.data?.length > 0) {
    res.data.forEach((item: any) => {
      item.value = item.stcd;
      item.label = item.ennm;
    });
    ennmOptions.value = res.data;
  } else {
    ennmOptions.value = [];
  }
};
watch(
  () => props.visible,
  newVisible => {
    if (newVisible) {
      initForm();
      handleRiverSelect('');
    }
  },
  { immediate: false }
);

defineExpose({
  localLoading
});
</script>

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