<template>
  <div class="h5mianList">
    <div class="header">
      <div @click="back" class="back">
        <van-icon size="1.3rem" name="arrow-left" />
      </div>
      <div class="title">任务中心</div>
    </div>
    <div class="search" style="border-bottom: 1px solid #f1f1f1">
      <van-dropdown-menu>
        <van-dropdown-item
          v-model="dataForm.isReceived"
          :options="option1"
          @change="changeisReceived"
        />
        <van-dropdown-item title="筛选" ref="itemRef">
          <van-form @submit="onSubmit">
            <van-field
              v-model="dataForm.lineName"
              label="航线名称"
              placeholder="请输入航线名称"
            />
            <van-field
              v-model="dataForm.lineUnitName"
              @keydown.enter="changeisReceived"
              label="单元名称"
              placeholder="请输入单元名称"
            />
          </van-form>
          <div style="padding: 5px 16px; display: flex">
            <van-button
              type="primary"
              block
              round
              @click="
                (dataForm.lineName = ''),
                  (dataForm.lineUnitName = ''),
                  (dataForm.page = 1),
                  (more = false),
                  (dataList = []),
                  getList(),
                  itemRef.toggle()
              "
            >
              清空
            </van-button>
            <van-button
              type="primary"
              block
              round
              @click="
                (dataForm.page = 1),
                  (more = false),
                  (dataList = []),
                  getList(),
                  itemRef.toggle()
              "
            >
              确认
            </van-button>
          </div>
        </van-dropdown-item>
        <van-dropdown-item
          :title="listTypeName"
          v-model="dataForm.lietType"
          :options="option2"
          @change="changelietType"
        />
      </van-dropdown-menu>
    </div>
    <div
      class="table-container"
      id="scroll-container"
      ref="scrollContainer"
      v-scroll="handleScroll"
    >
      <table>
        <thead>
          <tr>
            <th>管线及单元</th>
            <th v-if="listTypeName != '默认'">距离</th>
            <th>状态</th>
            <th>时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in dataList" :key="index">
            <td>{{ row.lineName }}({{ row.lineUnitName }})</td>
            <td style="width: 90px" v-if="listTypeName != '默认'">{{ (row.distance/1000).toFixed(2) }}km</td>
            <td style="width: 120px">
              <span :style="{ color: isReceivedColor[row.isReceived] }">
                {{ isReceived[row.isReceived] }}
              </span>
            </td>
            <td style="width: 90px">{{ row.updateDate.slice(0, -9) }}</td>
            <td>
              <div class="bts" style="width: 170px">
                <div
                  v-if="row.isReceived === '0'"
                  class="danger"
                  style="margin-right: 0.3rem"
                  @click.stop="refuseTaskArrange(row.id)"
                >
                  拒绝
                </div>
                <div
                  v-if="row.isReceived === '0'"
                  @click.stop="receiveTaskArrange(row)"
                >
                  接受
                </div>
                <div
                  class="danger"
                  v-if="row.isReceived === '1'"
                  @click.stop="cancelTaskArrange(row)"
                >
                  取消任务
                </div>
                <div
                  v-if="row.isReceived === '1'"
                  @click.stop="todownFly(row.verificationCode)"
                >
                  下载航线文件
                </div>
                <div
                  class="success"
                  v-if="row.isReceived === '6'"
                  @click.stop="completeTaskArrange(row.id)"
                >
                  完成
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <van-back-top target=".table-container" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import {
  ref,
  defineProps,
  watch,
  defineExpose,
  onMounted,
  getCurrentInstance,
  computed,
} from "vue";
import { showToast, showConfirmDialog } from "vant";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const total = ref(0);
const scrollContainer = ref();
const dataList = ref([]);
import { goBackToApp, saveCode, downFly } from "@/utils/bridge";
const isLoading = ref(false);
const more = ref(false);
const top = ref(false);
const listTypeName = computed(() => {
  if (!rectangle.value) {
    return "定位中...";
  }
  return option2.value[dataForm.value.lietType].text;
});
const rectangle = ref();
const location = ref();
const itemRef = ref();
const option1 = [
  { text: "全部", value: "" },
  { text: "未接收", value: 0 },
  { text: "已接收", value: 1 },
  { text: "已结束", value: 2 },
  { text: "已拒绝", value: 3 },
  { text: "已经下载航线文件", value: 4 },
  { text: "已上传文件", value: 5 },
  { text: "已确认上传文件为最终巡检文件", value: 6 },
];

const option2 = ref([
  { text: "默认", value: 0 },
  { text: "离我最近", value: 1 },
]);

const isReceivedColor = {
  0: "#CCCCCC", // 灰色 - 未接收
  1: "#4CAF50", // 绿色 - 已接收
  2: "#9E9E9E", // 深灰色 - 已结束
  3: "#F44336", // 红色 - 已拒绝
  4: "#FFEB3B", // 黄色 - 已经下载航线文件
  5: "#2196F3", // 蓝色 - 已上传文件
  6: "#009688", // 深青色 - 已确认上传文件为最终巡检文件
};
const isReceived = {
  0: "未接收",
  1: "已接收",
  2: "已结束",
  3: "已拒绝",
  4: "已经下载航线文件",
  5: "已上传文件",
  6: "已确认上传文件为最终巡检文件",
};

const dataForm = ref({
  isReceived: "",
  lietType: 0,
  page: 1,
  limit: 15,
});

const getLocation = () => {
  AMap.plugin("AMap.Geolocation", function () {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 开启高精度模式
      timeout: 1000, // 设置超时时间为 30 秒
      noIpLocate: 0, // 使用 IP 定位作为备用方案
      noGeoLocation: 0, // 允许浏览器获取地理位置
    });

    geolocation.getCurrentPosition(function (status, result) {
      if (status === "complete") {
        var lng = result.position.lng;
        var lat = result.position.lat;
        console.log(lng, lat);
      } else {
        console.error("定位失败", result);
        fetch(
          "https://restapi.amap.com/v3/ip?key=74d5aa7c4270effe9a18d9cfa6149abf"
        )
          .then((response) => response.json())
          .then((data) => {
            console.log("IP 定位:", data);
            console.log("当前位置：" + data.province + data.city);
            console.log("经纬度：" + data.rectangle.split(";")[1]);
            location.value = data.province + data.city;
            rectangle.value = data.rectangle.split(";")[1];
            option2.value[1].text = `离我最近(${location.value})`;
          })
          .catch((error) => {
            console.error("IP 定位失败:", error);
            option2.value[1].text = "定位失败，点击重新定位";
            showToast("定位失败");
          });
      }
    });
  });
};

//获取数据
const getList = (e) => {
  if (more.value) {
    showToast("没有更多了");
    isLoading.value = false;
    return;
  }
  if (e == 2) {
    isLoading.value = true;
  }
  if (dataForm.value.lietType == 1) {
    dataForm.value.lon = rectangle.value.split(",")[0];
    dataForm.value.lat = rectangle.value.split(",")[1];
  } else {
    dataForm.value.lon = null;
    dataForm.value.lat = null;
  }
  proxy
    .$ajax({
      method: "GET",
      url: `/task/zhkjwurenjitaskarrange/getUserTaskArrange`,
      params: dataForm.value,
    })
    .then((res) => {
      isLoading.value = false;
      if (res.data.code != 0) {
        return showToast(res.data.msg);
      }
      dataList.value.push(...res.data.data.list);
      total.value = res.data.data.total;
      if (dataList.value.length == total.value) {
        more.value = true;
        showToast("没有更多了");
      }
    });
};

// 详情
const todetails = (e) => {
  let ruters = {
    path: "/taskDetails",
    component: () => import("./taskDetails.vue"),
  };
  router.addRoute(ruters);
  router.options.routes.push(ruters);
  sessionStorage.setItem("details", true);
  router.push({
    path: "/taskDetails",
    query: {
      id: e,
    },
  });
};
// 回到顶部
const toTop = () => {
  scrollContainer.value.scrollTop = 0;
};

const changeisReceived = (event) => {
  dataList.value = [];
  dataForm.value.page = 1;
  more.value = false;
  if (event.target) {
    event.target.blur();
    itemRef.value.toggle();
  }
  getList();
};
const changelietType = () => {
  if (!rectangle.value) {
    getLocation();
    return;
  }
  dataList.value = [];
  dataForm.value.page = 1;
  more.value = false;
  getList();
};

const back = () => {
  goBackToApp("home");
};

// 拒绝
const refuseTaskArrange = (id) => {
  showConfirmDialog({
    title: "提示",
    message: "是否拒收该任务",
  })
    .then(() => {
      // on confirm
      proxy
        .$ajax({
          method: "get",
          url: `/task/zhkjwurenjitaskarrange/refuseTaskArrange/${id}`,
        })
        .then((res) => {
          if (res.data.code != 0) {
            return showToast(res.data.msg);
          }
          showToast("操作成功");
          dataForm.value.page = 1;
          more.value = false;
          dataList.value = [];
          getList();
        });
    })
    .catch(() => {
      // on cancel
    });
};

// 完成
const completeTaskArrange = (id) => {
  showConfirmDialog({
    title: "提示",
    message: "是否完成任务",
  })
    .then(() => {
      // on confirm
      proxy
        .$ajax({
          method: "get",
          url: `/task/zhkjwurenjitaskarrange/completeTaskArrange/${id}`,
        })
        .then((res) => {
          if (res.data.code != 0) {
            return showToast(res.data.msg);
          }
          showToast("操作成功");

          dataList.value = [];
          dataForm.value.page = 1;
          more.value = false;
          getList();
        });
    })
    .catch(() => {
      // on cancel
    });
};

// 接受
const receiveTaskArrange = (data) => {
  showConfirmDialog({
    title: "提示",
    message: "是否确认接受该任务",
  })
    .then(() => {
      let DeviceId = sessionStorage.getItem("DeviceId");
      let info = JSON.parse(sessionStorage.getItem("userInfo"));

      data.receivedUserId = info.id;
      data.receivedUserName = info.realName;
      data.deviceId = DeviceId;
      proxy
        .$ajax({
          method: "post",
          url: `/task/zhkjwurenjitaskarrange/receiveTaskArrange`,
          data: data,
        })
        .then((res) => {
          if (res.data.code != 0) {
            return showToast(res.data.msg);
          }

          saveCode(res.data.data);
          showToast("操作成功");

          dataList.value = [];
          dataForm.value.page = 1;
          more.value = false;
          getList();
        });
    })
    .catch(() => {
      // on cancel
    });
};
const cancelTaskArrange = (data) => {
  showConfirmDialog({
    title: "提示",
    message: "是否取消任务",
  })
    .then(() => {
      proxy
        .$ajax({
          method: "get",
          url: `/task/zhkjwurenjitaskarrange/completeTaskArrange/${
            data.id
          }/${0}`,
        })
        .then((res) => {
          if (res.data.code != 0) {
            return showToast(res.data.msg);
          }

          showToast("操作成功");

          dataList.value = [];
          dataForm.value.page = 1;
          more.value = false;
          getList();
        });
    })
    .catch(() => {
      // on cancel
    });
};

// 下载航行文件
const todownFly = (code) => {
  showConfirmDialog({
    title: "提示",
    message: "是否下载飞行文件",
  })
    .then(() => {
      // on confirm
      downFly(code);
    })
    .catch(() => {
      // on cancel
    });
};
// 触底加载
const handleScroll = () => {
  // console.log(
  //   scrollContainer.value.scrollHeight,
  //   scrollContainer.value.scrollTop,
  //   scrollContainer.value.clientHeight
  // );
  // 判断滚动容器是否触底
  if (
    scrollContainer.value.scrollHeight <=
    scrollContainer.value.scrollTop + scrollContainer.value.clientHeight + 70
  ) {
    // 触底逻辑，可以在这里进行数据加载或其他操作
    dataForm.value.page++;
    getList(1);
  }
};

onMounted(() => {
  if (sessionStorage.getItem("information")) {
    //判断是否有流程
    let a = JSON.parse(sessionStorage.getItem("information"));
    // console.log(a);
    dataForm.value.activityId = a.id;
  }

  // 获取滚动容器元素
  const scrollContainer = document.getElementById("scroll-container");

  // 监听滚动事件
  scrollContainer.addEventListener("scroll", handleScroll);

  getList(1);
  getLocation();
});
</script>

<style scoped lang="less">
.content {
  height: calc(85vh - 2rem);
}
.table-container {
  height: 300px; /* 设置容器高度 */
  overflow-y: auto; /* 内容区域滚动 */
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  position: sticky;
  top: 0;
  background-color: #fff; /* 表头背景色 */
}

th,
td {
  padding: 8px;
  border: 1px solid #ddd;
}

.bts {
  display: flex;
  justify-content: space-around;
  color: #3e8ef7;
  .danger {
    color: #f5686f;
  }
}
</style>
