<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="userForm"
        :rules="userRules"
        :label-width="80"
        label-placement="left"
        require-mark-placement="left"
        :disabled="disabled"
      >
        <template v-for="(item,index) in getFormOptions" :key="index">
          <n-form-item :label="item.label" :path="item.key">
            <UploadOss
              v-if="item.type === 'oss'"
              :ref="el=>{ossRefs[item.refIndex] = el}"
              :default-list="userForm[item.file]"
              @upload-status="handleUploadStatus"
            />
            <n-input v-if="item.type === 'input'" v-model:value="userForm[item.key]" v-bind="item.props" />
            <n-select v-if="item.type === 'select'" v-model:value="userForm[item.key]" v-bind="item.props" />
            <div v-if="item.type === 'map'" id="mapContainer" class="map" />

            <n-input v-if="item.type === 'inputStart'" v-model:value="userForm[item.key]" disabled v-bind="item.props">
              <template #suffix>
                <n-button quaternary type="info" style="padding-right: 0;" @click="showStart = true">去标记
                  <n-icon size="20" color="rgba(42, 130, 228, 1)">
                    <LocationSharp />
                  </n-icon>
                </n-button>
              </template>
            </n-input>

            <n-input v-if="item.type === 'inputEnd'" v-model:value="userForm[item.key]" disabled v-bind="item.props">
              <template #suffix>
                <n-button quaternary type="info" style="padding-right: 0;" @click="showEnd = true">去标记
                  <n-icon size="20" color="rgba(42, 130, 228, 1)">
                    <LocationSharp />
                  </n-icon>
                </n-button>
              </template>
            </n-input>

            <n-date-picker
              v-if="item.type === 'datetime'"
              v-model:formatted-value="userForm[item.key]"
              v-bind="item.props"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :is-date-disabled="isDateDisabled"
              style="width: 100%;"
            />
            <n-radio-group v-if="item.type === 'radio'" v-model:value="userForm[item.key]" :name="item.key">
              <n-space>
                <n-radio v-for="(cItem,cIndex) in item.options" :key="`${item.key}_${cIndex}`" :value="cItem.value"> {{
                  cItem.label }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
        </template>
      </n-form>
    </template>
  </Modal>

  <n-modal
    v-if="showStart"
    v-model:show="showStart"
    :mask-closable="false"
    preset="dialog"
    title=""
    positive-text="确定"
    @positive-click="userForm.patrolLocation = startVal"
    @negative-click="showStart = false"
  >
    <map-comp v-if="showStart" @mapEmit="startHandle" />
  </n-modal>

  <n-modal
    v-if="showEnd"
    v-model:show="showEnd"
    :mask-closable="false"
    preset="dialog"
    title=""
    positive-text="确定"
    @positive-click="userForm.endValue = endVal"
    @negative-click="showEnd = false"
  >
    <map-comp v-if="showEnd" @mapEmit="endHandle" />
  </n-modal>

</template>

<script>
import { form, getPilotList, getEquipment, getEquipmentMount } from '../tools/form.js'
import { defineComponent, ref, reactive, computed, toRefs } from 'vue'
import Modal from '@/components/Modal/index.vue'
import UploadOss from '@/components/UploadOss/index.vue'
import { taskAdd, taskEdit } from '@/api/task'
import { LocationSharp } from '@vicons/ionicons5'
// import AMapLoader from '@amap/amap-jsapi-loader'
import MapComp from './MapComp.vue'
import GMap from '@/utils/map/GMap'
import dayjs from 'dayjs'

export default defineComponent({
  name: 'UserModal',
  components: { Modal, UploadOss, MapComp, LocationSharp },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'create'
    },
    data: {
      type: Object,
      default: () => null
    }
  },
  emits: {
    'update:visible': null,
    'reload': null
  },
  setup(props, { emit }) {
    const MODAL_TYPE = {
      'create': '新建任务',
      'preview': '任务详情',
      'update': '编辑任务'
    }
    getPilotList()
    getEquipment()
    getEquipmentMount()
    const { formItem, userForm, userRules } = form
    const formRef = ref()
    const ossRefs = ref([])
    const data = reactive({
      userForm: {
        ...userForm,
        ...props.data
      },
      userRules: {
        ...userRules
      },
      disabled: props.type === 'preview'
    })
    const getModalOptions = computed(() => {
      return {
        show: props.visible,
        title: MODAL_TYPE[props.type],
        negativeText: '取消',
        positiveText: '确认'
      }
    })

    const getFormOptions = computed(() => {
      return {
        ...formItem
      }
    })

    function handleUploadStatus(status) {
      data.userForm.imageStatus = status
    }

    let Gmap = null
    let geocoder = null
    let AMaps = null
    let startMarker = null
    let endMarker = null
    // 地图
    GMap.then((AMap) => {
      AMaps = AMap
      // 坐标求地址
      geocoder = new AMap.Geocoder()

      if (props.type === 'update') { // 打开编辑
        Gmap = new AMap.Map('mapContainer', {
          zoom: 13,
          center: [data.userForm.startLongitude, data.userForm.startLatitude]
        })

        startMarker = new AMap.Marker({
          position: new AMap.LngLat(data.userForm.startLongitude, data.userForm.startLatitude),
          icon: '//vdata.amap.com/icons/b18/1/2.png',
          title: '起点'
        })
        endMarker = new AMap.Marker({
          position: new AMap.LngLat(data.userForm.endLongitude, data.userForm.endLatitude),
          icon: '//vdata.amap.com/icons/b18/1/2.png',
          title: '终点'
        })

        // 将创建的点标记添加到已有的地图实例：
        Gmap.add([startMarker, endMarker])

        // 起点赋值
        geocoder.getAddress([data.userForm.startLongitude, data.userForm.startLatitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            data.userForm.patrolLocation = result.regeocode.formattedAddress
          }
        })

        // 终点赋值
        geocoder.getAddress([data.userForm.endLongitude, data.userForm.endLatitude], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            data.userForm.endValue = result.regeocode.formattedAddress
          }
        })
      } else {
        Gmap = new AMap.Map('mapContainer', {
          zoom: 13,
          center: [118.773319, 31.828123]
        })
      }

      // 添加缩放工具
      const toolbar = new AMap.ToolBar()
      Gmap.addControl(toolbar)
    }).catch(e => console.log(e))

    // 地图辅助参数
    const showStart = ref(false)
    const showEnd = ref(false)

    const startVal = ref(null)
    const endVal = ref(null)

    // 起点地图 确定事件
    const startHandle = ({ lng, lat }) => {
      geocoder.getAddress([lng, lat], function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          startVal.value = result.regeocode.formattedAddress
          data.userForm.startLongitude = String(lng)
          data.userForm.startLatitude = String(lat)
        }
      })
      if (startMarker) Gmap.remove(startMarker)
      startMarker = new AMaps.Marker({
        title: '起点',
        icon: '//vdata.amap.com/icons/b18/1/2.png'
      })
      startMarker.setMap(Gmap)
      startMarker.setPosition([lng, lat])
      Gmap.setCenter(startMarker.getPosition())
    }
    // 终点地图 确定事件
    const endHandle = ({ lng, lat }) => {
      geocoder.getAddress([lng, lat], function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
          endVal.value = result.regeocode.formattedAddress
          data.userForm.endLongitude = String(lng)
          data.userForm.endLatitude = String(lat)
        }
      })
      if (endMarker) Gmap.remove(endMarker)
      endMarker = new AMaps.Marker({
        title: '终点',
        icon: '//vdata.amap.com/icons/b18/1/2.png'
      })
      endMarker.setMap(Gmap)
      endMarker.setPosition([lng, lat])
      Gmap.setCenter(endMarker.getPosition())
    }

    function handleConfirm() {
      formRef.value?.validate(async(errors) => {
        if (!errors) {
          const params = {
            ...data.userForm,
            taskStartTime: String(data.userForm.taskStartTime)
          }

          if (params.taskCode) {
            /* 编辑 */
            taskEdit(params)
              .then(res => {
                if (res.code === 0) {
                  emit('reload')
                  handleClose()
                }
              })
          } else {
            /* 新增 */
            taskAdd(params)
              .then(res => {
                if (res.code === 0) {
                  emit('reload')
                  handleClose()
                }
              })
          }
        } else {
          $message.error('请完善必填信息')
        }
      })
    }

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }

    const isDateDisabled = number => {
      return number < dayjs().startOf('minute')
    }
    return {
      ...toRefs(data),
      formRef,
      ossRefs,
      getModalOptions,
      getFormOptions,
      handleUploadStatus,
      handleConfirm,
      handleClose,
      showStart,
      showEnd,
      startVal,
      endVal,
      startHandle,
      endHandle,
      isDateDisabled
    }
  }
})
</script>
<style scoped lang='scss'>
.map {
  width: 100%;
  height: 155px;
  margin-bottom: 10px;
}
</style>
