<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="区域" v-bind="validateInfos.lineId">
            <!-- <j-dict-select-tag v-model:value="formData.lineId" dictCode="" placeholder="" :disabled="disabled"/> -->
            <a-select
              v-model:value="formData.lineId"
              style="width: 300px"
              @change="changeLineValue"
              :disabled="disabled"
              placeholder="请选择所属区域"
            >
              <a-select-option v-for="(item, index) in lineSelect" :value="item.id" :key="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="站点序号" v-bind="validateInfos.sitecode">
            <a-input v-model:value="formData.sitecode" placeholder="请输入站点序号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="站点名称" v-bind="validateInfos.sitename">
            <a-input v-model:value="formData.sitename" placeholder="请输入站点名称" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <template v-if="disabled == false">
          <a-col :span="24">
            <a-form-item label="位置">
              <a><img :src="locationPng" class="dwImg" @click="mapShow" /></a>
            </a-form-item>
          </a-col>

          <EarthMapModal
            ref="earthMapModal"
            :enableTile="false"
            :visible="mapVisible"
            @closeWin="
              () => {
                mapVisible = false;
              }
            "
            @checkPosition="checkPosition"
            :hasMoveMethod="true"
            @moveChinaPosition="moveChinaPosition"
            :editTileModel="mapModel"
            initModeType="3D"
            :enable-pointer="false"
          >
          </EarthMapModal>
        </template>
        <a-col :span="24">
          <a-form-item label="经度" v-bind="validateInfos.longitude">
            <a-input-number v-model:value="formData.longitude" placeholder="请输入经度" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="纬度" v-bind="validateInfos.latitude">
            <a-input-number v-model:value="formData.latitude" placeholder="请输入纬度" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="高度" v-bind="validateInfos.height">
            <a-input-number v-model:value="formData.height" placeholder="请输入高度" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="偏航角" v-bind="validateInfos.yaw">
            <a-input-number v-model:value="formData.yaw" placeholder="请输入偏航角" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="俯仰角" v-bind="validateInfos.pitch">
            <a-input-number v-model:value="formData.pitch" placeholder="请输入俯仰角" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="翻转角" v-bind="validateInfos.roll">
            <a-input-number v-model:value="formData.roll" placeholder="请输入翻转角" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, computed, onMounted } 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 { saveOrUpdate } from '../MsCameraSite.api';
  import { Form } from 'ant-design-vue';
  import EarthMapModal from '@/views/military/modules/earthMap/scene/model/mapModel/EarthMapModal.vue';
  import locationPng from '@/assets/images/getLocation.png';

  const lineSelect: any = ref([]);
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: undefined,
    lineId: undefined,
    sitecode: '',
    sitename: '',
    longitude: undefined,
    latitude: undefined,
    height: undefined,
    yaw: undefined,
    pitch: undefined,
    roll: undefined,
  });
  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 = {
    sitecode: [{ required: true, message: '请输入站点序号!' }],
    sitename: [{ required: true, message: '请输入站点名称!' }],
    longitude: [{ required: true, message: '请输入经度!' }],
    latitude: [{ required: true, message: '请输入纬度!' }],
    lineId: [{ required: true, message: '请选择所属区域!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  onMounted(() => {
    setSelectList();
  });
  //线路选择框
  function setSelectList() {
    defHttp
      .get(
        {
          url: '/military/msMapLine/mapLineSelect',
        },
        { isTransformResponse: false }
      )
      // getAction(this.url.querySelectList, {})
      .then((res) => {
        if (res.success) {
          lineSelect.value = res.result;
        }
      });
  }

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    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 saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }
  function changeLineValue(item, option) {
    formData.lineId = option.key;
  }

  // 弹窗地图框属性
  const mapVisible = ref(false);
  const mapModel = ref();
  const mapShow = function () {
    mapModel.value = {
      custom: {
        id: formData.id,
      },
      czmObject: {
        name: formData.sitename,
        xbsjType: 'Model',
        url: '/dt/sys/common/static/' + formData.modelUrl,
        // "color": [0.52, 0.6, 0.58, 1],
        minimumPixelSize: formData.minimumPixelSize,
        // maximumScale: 0.02,
        scale: formData.scale,
        xbsjScale: formData.xyzScale ? formData.xyzScale.split(',') : [1, 1, 1],
        xbsjPosition: [window.Cesium.Math.toRadians(formData.longitude), window.Cesium.Math.toRadians(formData.latitude), formData.height],
        xbsjRotation: [
          window.Cesium.Math.toRadians(formData.yaw),
          window.Cesium.Math.toRadians(formData.pitch),
          window.Cesium.Math.toRadians(formData.roll),
        ],
        viewDistance: 150,
        distanceDisplayCondition: [1.0, 30000.0],
      },
    };

    mapVisible.value = true;
  };

  const checkPosition = function (position, rotation, fov) {
    const CMath = window.Cesium.Math;
    formData.longitude = CMath.toDegrees(position[0]);
    formData.latitude = CMath.toDegrees(position[1]);
    formData.height = CMath.toDegrees(position[2]);

    formData.yaw = CMath.toDegrees(rotation[0]);
    formData.pitch = CMath.toDegrees(rotation[1]);
    formData.roll = CMath.toDegrees(rotation[2]);

    // subObject.value.viewDistance = fov;
  };
  const earthMapModal: any = ref(null);
  // 打开地图时飞入到指定位置
  const moveChinaPosition = function () {
    earthMapModal.value.CModel.czmObject.flyTo();
    // const CMath = window.Cesium.Math;
    // window.earth.camera.position = [CMath.toRadians(formData.longitude) - 0.000001, CMath.toRadians(formData.latitude) - 0.000001, CMath.toRadians(formData.height) - 0.000001];
    // window.earth.camera.rotation = [CMath.toRadians(formData.yaw), CMath.toRadians(formData.pitch), CMath.toRadians(formData.roll)]
  };
  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }

  .dwImg {
    width: 32px;
    height: 32px;
  }
</style>
