<template>
  <div v-loading="isLoading" style="height: 100%">
    <div class="df main">
      <div class="left">
        <div id="map-container" class="map-container"></div>
        <div class="df aic tabs">
          <div
            @click="changeVoyageType(0)"
            :class="
              status == 0
                ? 'currentbtn radio-btns left-radius'
                : 'radio-btns left-radius'
            "
          >
            全部航次
          </div>
          <div
            style="border-left: none"
            @click="changeVoyageType(1)"
            :class="status == 1 ? 'currentbtn radio-btns' : 'radio-btns'"
          >
            装货中
          </div>

          <div
            style="border-left: none"
            @click="changeVoyageType(2)"
            :class="status == 2 ? 'currentbtn radio-btns' : 'radio-btns'"
          >
            运输中
          </div>
          <div
            style="border-left: none"
            @click="changeVoyageType(3)"
            :class="
              status == 3
                ? 'currentbtn radio-btns right-radius'
                : 'radio-btns right-radius '
            "
          >
            卸货中
          </div>
        </div>
        <div class="df aic filter">
          <div class="mr10 ml24">装货港</div>
          <el-select
            style="width: 120px"
            v-model="postData.loadPortId"
            placeholder="装货港"
            size="small"
            @change="getIndexData(1)"
            filterable
            clearable
          >
            <el-option
              v-for="item in loadPortOptions"
              :key="item"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
          <div class="mr10 ml24">卸货港</div>
          <el-select
            style="width: 120px"
            v-model="postData.discPortId"
            placeholder="卸货港"
            size="small"
            @change="getIndexData(1)"
            filterable
            clearable
          >
            <el-option
              v-for="item in discPortOptions"
              :key="item"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
          <div class="mr10 ml24">到港状态</div>
          <el-select
            style="width: 120px"
            v-model="postData.isArrived"
            placeholder="到港状态"
            size="small"
            @change="getIndexData(1)"
          >
            <el-option label="已到港" :value="0" />
            <el-option label="未到港" :value="1" />
          </el-select>
          <div class="mr10 ml24">航次状态</div>
          <el-select
            style="width: 120px"
            v-model="postData.abnormalStatus"
            placeholder="航次状态"
            size="small"
            @change="getIndexData(1)"
          >
            <el-option label="正常" :value="0" />
            <el-option label="异常" :value="1" />
          </el-select>
          <div class="mr10 ml24">货种</div>
          <el-select
            style="width: 100px"
            v-model="postData.cargoId"
            placeholder="货种"
            size="small"
            @change="getIndexData(1)"
            filterable
            clearable
          >
            <el-option
              v-for="item in cargoOptions"
              :key="item"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
          <div @click="resetFilter" class="all ml24">全部</div>
        </div>
      </div>
      <div class="right">
        <div class="df jcfe">
          <el-popover placement="bottom" :width="100" trigger="hover">
            <template #reference>
              <div class="export">导出报告</div>
            </template>
            <div
              style="
                display: flex;
                flex-direction: column;
                height: 180px;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div>
                <el-button
                  type="primary"
                  size="small"
                  v-auth="'DOWNLOADVOYAGELIST'"
                  @click="showExportModal('航次列表')"
                >
                  导出航次列表
                </el-button>
              </div>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  v-auth="'MULTDOWNLOADSHIPTRACK'"
                  @click="showExportModal('航次跟踪')"
                >
                  导出航次跟踪
                </el-button>
              </div>
              <div>
                <el-button
                  type="primary"
                  size="small"
                  @click="showExportModal('卸货记录')"
                  v-auth="'MULTDOWNLOADDISCHARGE'"
                >
                  导出卸货记录
                </el-button>
              </div>
              <div>
                <el-button
                  v-auth="'DOWNLOADFYDI'"
                  type="primary"
                  size="small"
                  @click="downloadFYDI"
                >
                  下载FYDI指数
                </el-button>
              </div>
            </div>
          </el-popover>
          <el-dialog
            v-model="exportModalVisable"
            :title="exportModalTitle"
            :close-on-click-modal="false"
            @close="isLoadingZip = false"
            width="200px"
          >
            <div class="df aic jcsb">
              <div
                v-if="exportModalTitle != '航次列表' || cargoOwnerId == 7"
                class="df aic"
              >
                <div class="mr20">请选择月份:</div>
                <el-date-picker
                  v-model="currentMonth"
                  type="month"
                  placeholder="请选择年月"
                  value-format="YYYYMM"
                  :disabled="isLoadingZip"
                />
              </div>
              <div></div>
              <el-button
                type="primary"
                @click="exportZip"
                :loading="isLoadingZip"
              >
                导出{{ exportModalTitle }}
              </el-button>
            </div>
          </el-dialog>
        </div>
        <div class="data">
          <div class="df">
            <div class="shu"></div>
            <div class="right-title">数据统计</div>
          </div>
          <div class="df data-line">
            <div class="icon">船</div>
            <div>
              <div class="data-title">总航次数</div>
              <div class="df">
                <div class="num">3205</div>
                <div class="unit">次</div>
              </div>
            </div>
          </div>
          <div class="df data-line">
            <div class="icon">锚</div>
            <div>
              <div class="data-title">总实际装载吨数</div>
              <div class="df">
                <div class="num">12303.33</div>
                <div class="unit">吨</div>
              </div>
            </div>
          </div>
          <div class="df data-line">
            <div class="icon">卸货</div>
            <div>
              <div class="data-title">总已完成卸货吨位</div>
              <div class="df">
                <div class="num">345233.2</div>
                <div class="unit">吨</div>
              </div>
            </div>
          </div>
          <div class="df data-line">
            <div class="icon">剩余</div>
            <div>
              <div class="data-title">总剩余卸货吨位</div>
              <div class="df">
                <div class="num">328192.33</div>
                <div class="unit">吨</div>
              </div>
            </div>
          </div>
        </div>
        <div class="pie">
          <div class="shu"></div>
          <div class="right-title">卸货占比</div>
        </div>
      </div>
    </div>
    <div class="df old" style="background: #f4f5f6">
      <div>
        <div class="right-top">
          <div class="cards card-1">
            <div>总航次数</div>
            <div>{{ indexData.totalVoyageNum }}</div>
          </div>
          <div class="cards card-2">
            <div>总实际装载吨位</div>
            <div>{{ indexData.totalLoadTons }}</div>
          </div>
          <div class="cards card-3">
            <div>总已完成卸货吨位</div>
            <div>{{ indexData.finshDiscTons }}</div>
          </div>
          <div class="cards card-4">
            <div>总剩余卸货吨位</div>
            <div>{{ indexData.unfinshDiscTons }}</div>
          </div>
        </div>
        <div id="pie" class="card-5">
          <div>饼图</div>
          <div>卸货</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, computed, onMounted, inject } from "vue";
import { ElNotification } from "element-plus";
import store from "../../store";
import router from "../../router";

import md5 from "md5";
import api from "../../apis/fetch";
import downloadBlobFile from "../../utils/downloadBlobFile";
import url from "../../apis/config";
let map = ref({});
let cargoOwnerId = localStorage.userId;
let echarts = inject("ec");

function initMap() {
  map.value = new AMap.Map("map-container", {
    zoom: 9, //级别
    zooms: [4, 9],
    center: [120.563757, 31.891174], //中心点坐标
    mapStyle: "amap://styles/f48d96805f5fa7f5aada657c5ee37017",
    zoomEnable: true,
    dragEnable: true,
  });
  let toolBar = new AMap.ToolBar({
    position: {
      top: "40px",
      right: "40px",
    },
  });
  let hawkEye = new AMap.HawkEye({
    opened: false,
  });
  map.value.addControl(toolBar);
  map.value.addControl(hawkEye);
  drawMarkers();
  drawPie();
}

function drawMarkers() {
  let markers = [];
  for (let i of indexData.value.mapPoints) {
    if (i.latitude && i.longitude) {
      let content = `<div style='width:160px'>
        <img src='https://hhd-pat-1255802371.cos.ap-shanghai.myqcloud.com/frontend/ship-red-icon.png' style='display:block;width:20px;height:20px;margin:6px auto'/
      </div>`;

      let marker = new AMap.Marker({
        content,
        position: new AMap.LngLat(i.longitude, i.latitude),
        offset: new AMap.Pixel(-80, -20),
      });
      let infoWindowContent = `<div class='window-title pointer' style='font-size:12px'>${i.shipName}</div>
      <div style='font-size:12px;margin-top:5px'>查看详情</div>
      `;
      let infoWindow = new AMap.InfoWindow({
        position: new AMap.LngLat(i.longitude, i.latitude),
        offset: new AMap.Pixel(0, -10),
        content: infoWindowContent,
      });

      marker.on("mouseover", function () {
        infoWindow.open(map.value);
      });
      marker.setLabel({
        direction: "top",
        offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
        content: `${i.shipName}`, //设置文本标注内容
        style: "",
      });

      marker.on("click", () => {
        goToVoyageDetail(i.voyageId);
      });

      markers.push(marker);
    }
  }
  let overlayGroups = new AMap.OverlayGroup(markers);
  map.value.add(overlayGroups);
  map.value.setFitView(markers, true, [200, 50, 50, 50], 18);
}
let status = ref(3);
function changeVoyageType(s) {
  status.value = s;
  postData.value = {
    loadPortId: "",
    discPortId: "",
    isArrived: "",
    abnormalStatus: "",
    cargoId: "",
  };
  getIndexSelect();
  getIndexData();
}

function goToVoyageDetail(id) {
  router.push({
    path: "/voyage/voyageDetail",
    query: {
      id,
    },
  });
}

let postData = ref({
  status: 0,
  loadPortId: "",
  discPortId: "",
  isArrived: "",
  abnormalStatus: "",
  cargoId: "",
});
let indexData = ref({
  finshDiscTons: "",
  mapPoints: [],
  totalLoadTons: "",
  totalVoyageNum: "",
  unfinshDiscTons: "",
});
let isLoading = ref(false);
async function getIndexData(type) {
  isLoading.value = true;
  postData.value.status = status.value;
  try {
    let res = await api.getIndexData({
      ...postData.value,
    });
    isLoading.value = false;
    if (res.data.status == 0) {
      indexData.value = res.data.result;
      if (type == "init") {
        initMap();
        drawPie("init");
      } else {
        map.value.clearMap();
        drawMarkers();
        drawPie();
      }
    } else {
      indexData.value = {
        finshDiscTons: 0,
        mapPoints: [],
        totalLoadTons: 0,
        totalVoyageNum: 0,
        unfinshDiscTons: 0,
      };
      if (type == "init") {
        initMap();
        drawPie("init");
      } else {
        map.value.clearMap();
        drawMarkers();
        drawPie();
      }
    }
  } catch (error) {
    console.log(error);
    isLoading.value = false;
  }
}
let chartDom = ref({});
let myChart = ref({});

function drawPie(type) {
  if (!myChart.value.id) {
    chartDom.value = document.getElementById("pie");
    myChart.value = echarts.init(chartDom.value);
  }

  let option;

  option = {
    grid: {
      bottom: 500,
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        center: ["50%", "50%"],
        type: "pie",
        radius: "80%",
        data: [
          { value: indexData.value.finshDiscTons, name: "已卸货吨位" },
          { value: indexData.value.unfinshDiscTons, name: "剩余卸货吨位" },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          show: true,
          position: "inner", // 数值显示在内部
          formatter: "{d}%", // 格式化数值百分比输出
        },
      },
    ],
  };
  myChart.value.setOption(option);
}

let portOptions = ref([]);
async function getPortSelect() {
  if (portOptions.value.length) return;
  let res = await api.getCol({
    term: "",
  });
  portOptions.value = res.data.result;
}

let loadPortOptions = ref([]);
let discPortOptions = ref([]);

let cargoOptions = ref([]);
async function getCargoSelect() {
  if (cargoOptions.value.length) return;
  let res = await api.getCargoSelect({
    status: 2,
    term: "",
  });
  cargoOptions.value = res.data.result;
}

async function downloadFYDI() {
  let res0 = await api.getFYFIDownloadUrl({
    loginAccountId: localStorage.loginAccountId,
  });

  if (res0.data.result == 1) {
    ElNotification({
      type: "info",
      title: "更新中",
    });
  } else {
    let url = res0.data.result;
    let a = document.createElement("a");
    a.setAttribute("href", url);
    a.click();
  }
}

let exportModalVisable = ref(false);
let exportModalTitle = ref("");
let currentMonth = ref("");

function showExportModal(type) {
  exportModalVisable.value = true;
  exportModalTitle.value = type;
}

let isLoadingZip = ref(false);

async function exportZip() {
  if (!currentMonth.value && exportModalTitle.value != "航次列表") return;

  isLoadingZip.value = true;
  let path = "";
  let type = "";
  let postData = {
    loginAccountId: localStorage.loginAccountId,
  };
  let title = "";
  switch (exportModalTitle.value) {
    case "航次列表": {
      if (localStorage.userId == 7) {
        path = "/voyage/exportVoyageReportExcel";
        postData.loginAccountId = localStorage.loginAccountId;
        postData.date = currentMonth.value;
      } else {
        path = "/voyage/exportListExcel";
        let arr = [];
        for (let i of tableData.value) {
          arr.push(i.id);
        }
        postData.voyageIds = arr.join(",");
      }
      type =
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
      title = `${exportModalTitle.value}`;
      break;
    }
    case "航次跟踪": {
      path = "/voyage/exportMultExcel";
      type = "application/zip";
      postData.date = currentMonth.value;
      title = `${exportModalTitle.value}${currentMonth.value}`;

      break;
    }
    case "卸货记录": {
      path = "/voyage/exportMultDischargeExcel";
      type = "application/zip";
      postData.date = currentMonth.value;
      title = `${exportModalTitle.value}${currentMonth.value}`;
      break;
    }
  }
  try {
    let res = await downloadBlobFile(
      `${url.baseurl}${path}`,
      postData,
      title,
      "post",
      type
    );
    if (res.status == 0) {
      ElNotification({
        title: "导出成功!",
        type: "success",
      });
    } else {
      ElNotification({
        title: "暂无数据",
      });
    }
  } catch (error) {
    ElNotification({
      title: "暂无数据",
    });
  } finally {
    isLoadingZip.value = false;
    currentMonth.value = "";
    exportModalVisable.value = false;
  }
}

function resetFilter() {
  postData.value = {
    loadPortId: "",
    discPortId: "",
    isArrived: "",
    abnormalStatus: "",
    cargoId: "",
  };
  getIndexData();
}

async function getIndexSelect() {
  let res = await api.getIndexSelect({
    status: status.value,
  });
  if (res.data.status == 0) {
    loadPortOptions.value = res.data.result.loadPortSelect;
    discPortOptions.value = res.data.result.discPortSelect;
    cargoOptions.value = res.data.result.cargoSelect;
  } else {
    loadPortOptions.value = [];
    discPortOptions.value = [];
    cargoOptions.value = [];
  }
}
onMounted(() => {
  getIndexData("init");
  getIndexSelect();
});
</script>

<style scoped>
.old {
  position: fixed;
  top: -2000px;
}
.map-container {
  width: 100%;
  height: calc(100% - 94px);
}

.tabs {
  position: absolute;
  top: 20px;
  left: 25px;
}

.radio-btns {
  height: 30px;
  width: 60px;
  border: 1px solid #1486f9;
  line-height: 28px;
  text-align: center;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #0094fe;
  cursor: pointer;
  background: #fff;
}

.left-radius {
  border-top-left-radius: 15px;
  border-bottom-left-radius: 15px;
  width: 80px;
}

.right-radius {
  border-top-right-radius: 15px;
  border-bottom-right-radius: 15px;
  width: 80px;
}
.currentbtn {
  background: #1486f9;
  color: #fff;
}

:deep() .el-dialog {
  width: 800px;
}

.window-title {
  display: none;
}
.window-title:hover {
  display: block;
}

.export {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
  line-height: 14px;
  width: 90px;
  height: 32px;
  background: #008efe;
  border-radius: 2px;
  color: #fff;
  line-height: 32px;
  text-align: center;
}

.main {
  width: 100%;
  height: 100%;
  background: #f4f5f6;
}

.left {
  width: calc(100% - 315px);
  position: relative;
}

.filter {
  font-size: 14px;
  color: #353a42;
  width: calc(100vw - 320px);
  flex-wrap: wrap;
  margin-top: 36px;
}

.ml24 {
  margin-left: 24px;
}

.all {
  width: 60px;
  height: 32px;
  line-height: 32px;
  background: #008efe;
  border-radius: 2px;
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #ffffff;
  text-align: center;
}

.right {
  width: 267px;
  border-radius: 4px;
  height: calc(100% - 30px);
  margin-left: 26px;
}

.data {
  width: 267px;
  height: 466px;
  background: #ffffff;
  border-radius: 4px;
  margin-top: 16px;
  margin-bottom: 24px;
}

.pie {
  width: 267px;
  height: 385px;
  background: #ffffff;
  border-radius: 4px;
}

.icon {
  width: 48px;
  height: 48px;
  background: #008efe;
  border-radius: 4px;
}
</style>
