<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="AddSourceForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="锅炉房" v-bind="validateInfos.name" id="HeatsourcestationForm-sourceId" name="sourceId">
                <a-select ref="dictSelect"
                          placeholder="请选择换热站"
                          v-model:value="formData.name"
                          style="width: 250px"
                          @focus="focus"
                          @change="handleChange">
                  <a-select-option :value="item.heatStationId" v-for="item in heatstation" :key="item.id">{{item.heatStationName}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="经度" id="HeatsourcestationForm-longitude" name="longitude">
                <a-input v-model:value="formData.longitude" placeholder="请输入经度"  allow-clear :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="纬度" id="HeatsourcestationForm-latitude" name="latitude">
                <a-input v-model:value="formData.latitude" placeholder="请输入纬度"  allow-clear :disabled="true"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="描述" id="HeatsourcestationForm-description" name="description">
                <a-input v-model:value="formData.description" placeholder="请输入描述"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import {ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, unref} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { addMarkinfo,heatstationlist } from '../Markinfo.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const dictSelect = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    name: '',
    stationName: '',
    longitude: '',
    latitude: '',
    description: '',
    delFlag: '0',
    typeFlag: 2,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    name: [{ required: true, message: '请选择换热站!'},],
  });
  //注册表单
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  function edit(record) {
    nextTick(() => {
      getHeatsource();
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(key=='longitude'){
          key = "lng"
        }
        if(key=='latitude'){
          key = "lat"
        }
        if(record.hasOwnProperty(key)){
          if(key=='lng'){
            tmpData["longitude"] = record["lng"]
          }
          if(key=='lat'){
            tmpData["latitude"] = record["lat"]
          }
        }
      })
      //赋值
      Object.assign(formData, tmpData)
    });
  }

  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    let model = formData;
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await addMarkinfo(model)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok',model);
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  const heatstation = ref();
  async function getHeatsource(){
    heatstation.value = await heatstationlist();
  }

  async function handleChange(value){
    const selectedItem = heatstation.value.find(item => item.heatStationId === value);
    if (selectedItem) {
      formData["stationName"] = selectedItem.heatStationName;
    }else{
      formData["stationName"] = "";
    }
  }

  defineExpose({
    edit,
    submitForm,
  });

</script>
<style lang="less">
  .antd-modal-form {
    padding: 14px;
  }
</style>
