<template>
  <div>
    <van-nav-bar
      title="应急仓库编辑"
      left-arrow
      placeholder
      @click-left="goback"
      :fixed="true"
      @click-right="bjclick"
    >
    </van-nav-bar>
    <div>
      <div class="content">
        <div>
          <van-cell-group>
            <van-field
              v-model="whdata.value.name"
              label="仓库命名"
              input-align="right"
              :readonly="isedit"
              placeholder="请输入仓库命名"
            />
            <van-field
              v-model="whdata.value.manageUnit"
              label="管理单位"
              input-align="right"
              :readonly="isedit"
              placeholder="请输入管理单位"
            />
            <van-field
              v-model="whdata.value.contactName"
              required
              :readonly="isedit"
              label="联系人"
              input-align="right"
              placeholder="请输入联系人"
            />
            <van-field
              v-model="whdata.value.contactPhone"
              required
              label="联系方式"
              :readonly="isedit"
              input-align="right"
              placeholder="请输入联系方式"
            />

            <van-field
              v-model="whdata.value.address"
              label="地址"
              :readonly="isedit"
              input-align="right"
              placeholder="请输入地址"
            >
              <template #button v-if="isedit">
                <van-button
                  size="small"
                  type="primary"
                  color="#f2f4fa"
                  @click="searchaddr"
                  ><van-icon name="search"
                /></van-button>
              </template>
            </van-field>
          </van-cell-group>
        </div>
      </div>

      <div style="padding: 15px; background: #fff; position: relative">
        <Map
          v-model:map="state.map"
          style="
            height: 240px;
            borderradius: 2px;
            boxshadow: 0px 0px 0px 1px #d9d9d9;
          "
        />
        <div v-if="isshowmove" class="mark">
          <img :src="icon_map_location" />
        </div>
        <div v-if="isedit" class="marklocation" @click="getLocation">
          <img src="../../assets/icons/incident/location.svg" />
        </div>

        <div v-if="isedit" style="position: absolute; right: 21px; top: 21px">
          <van-button type="primary" size="mini" @click="selectpoint">{{
            isshowmove ? '确定' : '选点'
          }}</van-button>
        </div>
      </div>

      <div style="padding: 30px 20px" v-if="isedit">
        <van-button
          type="primary"
          block
          style="border-radius: 30px"
          @click="dosavedata"
          >保存</van-button
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUpdated, onMounted, watch } from 'vue';
import { RouterView, useRoute, useRouter } from 'vue-router';
import icon_map_location from '@/assets/icons/home/icon_map_location@2x.png';
import {
  api_getresource,
  api_getresourcedetail,
  api_putresource,
  api_bj,
  api_isbj,
} from '@/service/warehouse';
import { api_getusergps } from '@/service/login';
import { Toast, Notify, Dialog } from 'vant';
import { BaseMediaUrl } from '@/utils';
import { upload } from '@/api/common';
import Map from '@/components/MapView';

const state = reactive({
  map: null,
  _marker: null,
  loading: false,
  postition: {
    longitude: '',
    latitude: '',
    name: '',
  },
});

const whdata = reactive({
  value: {
    name: '',
    manageUnit: '',
    contactName: '',
    contactPhone: '',
    longitude: '',
    latitude: '',
  },
});
const isedit = ref(false);
const isempt = ref(true);


onMounted(() => {
  whdata.value = JSON.parse(localStorage.getItem('cck'));
  // isedit.value = true;
  isedit.value = localStorage.getItem("cedit")=="true"?true:false;
  // debugger

  var taskid = route.query.taskid;
  if (taskid) {
    api_isbj(taskid).then((res) => {
      isbj.value = !res.data;
      console.log(isbj.value);
    });
  }

  state.postition = {
    longitude: whdata.value.longitude,
    latitude: whdata.value.latitude,
    name: whdata.value.address,
  };

  if (state.map && state._marker) {
    state._marker.remove();
    state._marker = null;
  }
  if (state.map) {
    setpoint(
      Number(whdata.value.longitude),
      Number(whdata.value.latitude),
      whdata.value.address,
    );
  }
});

const isshowmove = ref(false);
let allmark = [];

const selectpoint = () => {
  if (isshowmove.value) {
    var center = state.map.getCenter();
    getlocalname(center.lng.toFixed(6) + ',' + center.lat.toFixed(6));
  } else {
    isshowmove.value = true;
    state._marker.remove();
  }
};
const setpoint = (longitude, latitude, name) => {
  if (state._marker) {
    state._marker.remove();
  }

  var el = document.createElement('div');
  el.id = 'marker';
  el.style.backgroundImage = `url(${icon_map_location})`;
  el.style.backgroundSize = 'cover';
  el.style.width = '24px';
  el.style.height = '24px';
  el.style.borderRadius = '50%';

  const popup = new window.minemap.Popup({
    closeOnClick: false,
    closeButton: false,
    offset: [0, -15],
  }).setText(name);

  state._marker = new window.minemap.Marker(el, {
    offset: [-12, -12],
  })
    .setLngLat([longitude, latitude])
    .setPopup(popup)
    .addTo(state.map);
  state.map.flyTo({
    center: [longitude, latitude],
    zoom: 14,
    bearing: 0,
    pitch: 0,
    duration: 2000,
  });
  state._marker.togglePopup();
  whdata.value.address = name;
  whdata.value.latitude = latitude;
  whdata.value.longitude = longitude;
  isshowmove.value = false;
};

const searchaddr = () => {
  isshowmove.value = false;
  fetch(
    `https://minedata.cn/service/lbs/search/v1/keywords?keywords=${whdata.value.address}&city=宿迁&citylimit=true&page_idx=1&page_size=10&key=${window.key}`,
  )
    .then((res) => res.json())
    .then((data) => {
      // console.log(data.pois)
      var clearallmark = () => {
        state._marker.remove();
        if (allmark.length > 0) {
          allmark.map((item) => {
            item.remove();
          });
          allmark = [];
        }
      };
      clearallmark();
      var top = [];
      var bottom = [];
      data.pois.map((item) => {
        if (top.length < 1) {
          top = [
            Number(item.location.split(',')[0]),
            Number(item.location.split(',')[1]),
          ];
          bottom = [
            Number(item.location.split(',')[0]),
            Number(item.location.split(',')[1]),
          ];
        }
        var el = document.createElement('div');
        el.id = 'marker';
        el.style.backgroundImage = `url(${icon_map_location})`;
        el.style.backgroundSize = 'cover';
        el.style.width = '24px';
        el.style.height = '24px';
        el.style.borderRadius = '50%';
        el.onclick = () => {
          clearallmark();
          setpoint(
            Number(item.location.split(',')[0]),
            Number(item.location.split(',')[1]),
            item.name,
          );
        };

        const popup = new window.minemap.Popup({
          closeOnClick: false,
          closeButton: false,
          offset: [0, -15],
        }).setText(item.name);

        var mark = new window.minemap.Marker(el, {
          offset: [-12, -12],
        })
          .setLngLat([
            Number(item.location.split(',')[0]),
            Number(item.location.split(',')[1]),
          ])
          .setPopup(popup)
          .addTo(state.map);
        allmark.push(mark);
        mark.togglePopup();
        if (top[0] < Number(item.location.split(',')[0])) {
          top[0] = Number(item.location.split(',')[0]);
        }
        if (top[1] > Number(item.location.split(',')[1])) {
          top[1] = Number(item.location.split(',')[1]);
        }
        if (bottom[0] > Number(item.location.split(',')[0])) {
          bottom[0] = Number(item.location.split(',')[0]);
        }
        if (bottom[1] < Number(item.location.split(',')[1])) {
          bottom[1] = Number(item.location.split(',')[1]);
        }
      });
      state.map.fitBounds([top, bottom]);
    });
};

const getlocalname = (location) => {
  fetch(
    `https://minedata.cn/service/lbs/reverse/v1/regeo?location=${location}&key=${window.key}`,
  )
    .then((res) => res.json())
    .then((data) => {
      setpoint(
        Number(location.split(',')[0]),
        Number(location.split(',')[1]),
        data.regeocodes[0].formatted_address,
      );
    });
};
const getLocation = () => {
  api_getusergps().then((res) => {
    var lat = null;
    var lon = null;
    var iserror = false;
    try {
      lat = res.result[0].lat;
      lon = res.result[0].lon;
      if (lat == null || lat == undefined) iserror = true;
    } catch (e) {
      iserror = true;
    }
    if (!iserror) {
      //  debugger
      var location = `${lon},${lat}`;
      getlocalname(location);
      //  setpoint(lon,lat,data.regeocodes[0].formatted_address)
    } else {
      Notify({
        type: 'danger',
        message: 'App不支持地理定位。',
      });
    }
  });
};

const goback = () => {
  try {
    uni.navigateBack();
  } catch (E) {}
  window.history.back();
};
const dosavedata = () => {
  Toast.loading({
    message: '加载中...',
    duration: 0,
    forbidClick: true,
  });
  var data = whdata.value;
  api_putresource(data)
    .then((res) => {
      Toast.clear();
      setTimeout(() => {
        Toast('保存成功');
      }, 1000);

      // Notify({ type: 'success', message: '保存成功'});
      getdata();
    })
    .catch((ee) => {
      Toast.clear();
    });
};

const isbj = ref(true);

const route = useRoute();

</script>

<style lang="scss">
.content label,
.content span {
  font-size: 15px;
  font-family: PingFangSC, PingFangSC-Regular;
  color: #333333;
}
.bjbtn {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  font-size: 13px;
  font-weight: 500;
  background: #bb0000;
  padding: 3px 8px;
  border-radius: 2px;
}
.content {
  .cell-header {
    font-family: PingFangSC, PingFangSC-Regular;
    font-weight: 400;
    line-height: 42px;
    padding: 0px 15px;
    span {
      font-size: 12px;
    }
    div {
      font-size: 14px;
      color: #0b33a8;
    }
  }
}
.mark {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  img {
    width: 24px;
    height: 24px;
  }
}
.marklocation {
  img {
    width: 24px;
    height: 24px;
  }
  position: absolute;
  bottom: 10%;
  right: 20px;
}
</style>
