<template>
  <transition name="slide-fade">
    <div class="station-types" v-drag>
      <div class="header">
        <span class="title">历史轨迹：{{ info.name }}</span>
        <i class="el-icon-close" @click="cancel"></i>
      </div>
      <div class="content">
        <el-form ref="form" :model="form" label-width="80px">
          <el-row>
            <div class="time-col-left">
              <el-form-item label="开始时间">
                <el-date-picker v-model="form.beginDate" type="datetime" placeholder="选择日期时间" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </div>
            <div class="time-col-right">
              <el-button type="danger" @click="endTrajectory">结束轨迹播放</el-button>
            </div>
          </el-row>
          <el-row>
            <div class="time-col-left">
              <el-form-item label="结束时间">
                <el-date-picker v-model="form.endDate" type="datetime" placeholder="选择日期时间" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </div>
            <div class="time-col-right">
              <el-button type="primary" @click="search">&nbsp;&nbsp;开始查询&nbsp;&nbsp;&nbsp;</el-button>
            </div>
          </el-row>
          <el-row>
            <div class="btn-row">
              <div
                class="btn-row-btn"
                v-for="(item, i) in speedBtnList"
                :key="i"
                :class="speedBtnActive === item.id ? 'btn-row-btnAc' : ''"
                @click="changeSpeed(item.id)"
              >
                {{ item.label }}
              </div>
              <!--              <div-->
              <!--                class="btn-row-btn btn-row-btnSelf"-->
              <!--                :class="speedBtnActive === '7' ? 'btn-row-btnAc' : ''"-->
              <!--              >-->
              <!--                <el-input-->
              <!--                  type="text"-->
              <!--                  placeholder="自定义"-->
              <!--                  clearable-->
              <!--                  v-model="speedSelfValue"-->
              <!--                  @input="changeSpeed('7')"-->
              <!--                ></el-input>-->
              <!--              </div>-->
            </div>
          </el-row>
          <el-row>
            <div class="btn-row btn-row2">
              <div class="btn-row-control" v-for="(item, i) in controlList" :key="i" @click="controlClick(item)">
                <img style="cursor: pointer" :src="item.icon" alt="" />
              </div>
            </div>
          </el-row>
        </el-form>
        <div class="detail-row">
          <div class="detail-row-btn" @click="detailOpenFn">
            <i :class="detailOpen ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            {{ detailOpen ? "折叠详情" : "查看详情" }}
          </div>
        </div>
        <div v-if="detailOpen">
          <selfTable
            ref="table"
            :columns="columns"
            :dataList="marketList"
            :current-index="currentIndex"
            :index="false"
            maxHeight="200"
            :hasPage="false"
          >
            <template slot="createdTime" slot-scope="scope">
              {{ parseTime(scope.row.createdTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
            </template>
            <template slot="locations" slot-scope="scope"> {{ scope.row.longitude }}, {{ scope.row.latitude }} </template>
          </selfTable>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
// import AMapLoader from "@amap/amap-jsapi-loader";
import { getEmployeesTrack } from "@/api/employee-controller";
import { parseTime } from "@/utils/index";
import selfTable from "@/components/common/selfTable";
import { saveAnalyticsLogs } from "@/api/analytics-controller";
import dayjs from "dayjs";

export default {
  name: "trajectory",
  components: {
    selfTable,
  },
  props: {
    info: {
      type: Object,
      default() {
        return {};
      },
    },
    map: {
      type: Object,
      default() {
        return null;
      },
    },
  },
  data() {
    return {
      speedSelfValue: "",
      speedBtnActive: "1",
      detailOpen: false,
      columns: [
        {
          prop: "createdTime",
          label: "时间",
          width: 180,
        },
        {
          prop: "locations",
          label: "位置参数",
          width: 300,
        },
        // {
        //   prop: "locationName",
        //   label: "位置名称",
        // },
      ],
      controlList: [
        {
          id: 1,
          name: "left",
          icon: require("@/assets/images/mapToolbar/trajectory/left.png"),
        },
        {
          id: 2,
          name: "play",
          icon: require("@/assets/images/mapToolbar/trajectory/play.png"),
        },
        {
          id: 3,
          name: "right",
          icon: require("@/assets/images/mapToolbar/trajectory/right.png"),
        },
        {
          id: 4,
          name: "stop",
          icon: require("@/assets/images/mapToolbar/trajectory/stop.png"),
        },
        {
          id: 5,
          name: "refresh",
          icon: require("@/assets/images/mapToolbar/trajectory/refresh.png"),
        },
      ],

      speedBtnList: [
        {
          id: "1",
          label: "x1",
          num: 1,
        },
        {
          id: "2",
          label: "x2",
          num: 2,
        },
        {
          id: "3",
          label: "x5",
          num: 5,
        },
      ],
      form: {
        beginDate: "",
        endDate: "",
      },
      marketList: [],
      marker: null,
      lineArr: [],
      polyline: [],
      markerSpeed: 1, //速度
      polyline1: [], //重绘通过路径轨迹的集合
      len: null, //marker移动中路径数组
      duration: 5000,
      passedPolyline: [],
      currentIndex: null,
    };
  },
  methods: {
    parseTime,
    endTrajectory() {
      if (this.lineArr.length > 0) {
        this.map.remove(this.marker);
        this.map.remove(this.polyline);
        this.map.remove(this.passedPolyline);
        this.lineArr = [];
        this.stopAnimation();
      }

      this.cancel();
    },
    controlClick(obj) {
      switch (obj.name) {
        case "left":
          this.backStep();
          break;
        case "play":
          this.startMove();
          break;
        case "stop":
          this.stopAnimation();
          break;
        case "right":
          this.nextStep();
          break;
        case "refresh":
          this.refresh();
          break;
      }
    },
    detailOpenFn() {
      if (this.marketList.length <= 0) {
        this.$message({
          message: "暂无轨迹数据",
          type: "warning",
        });
      } else {
        this.detailOpen = !this.detailOpen;
      }
    },
    changeSpeed(id) {
      this.speedBtnActive = id;
      let speedNumObj = [];
      if (Number(id) < 7) {
        speedNumObj = this.speedBtnList.filter((item) => item.id === id);
        this.markerSpeed = speedNumObj[0].num;
      } else {
        this.markerSpeed = this.speedSelfValue;
      }
      //this.startAnimation();
      this.startMove();
    },
    // 开始回放
    startMove() {
      this.$emit("startMove", this.markerSpeed);
    },
    backStep() {
      this.$emit("backStep");
    },
    nextStep() {
      this.$emit("nextStep");
    },
    // startAnimation() {
    //   let that = this;
    //   if (this.passedPolyline.length != 0) {
    //     this.map.remove(this.passedPolyline);
    //     that.passedPolyline = new AMap.Polyline({
    //       map: this.map,
    //       strokeColor: "#AF5", // 线颜色
    //       strokeWeight: 6, // 线宽
    //     });
    //   }
    //   console.log(this.markerSpeed);
    //   this.marker.moveAlong(this.lineArr, this.markerSpeed);
    // },
    pauseAnimation() {
      this.marker.pauseMove();
    },
    resumeAnimation() {
      this.marker.resumeMove();
    },
    // 倍速控制
    // handleSelect(e) {
    //   console.log("e", parseInt(e.charAt(0)));
    //   this.duration = 5000 / parseInt(e.charAt(0));
    // },
    stopAnimation() {
      // this.marker.stopMove();
      // this.$emit("stopMove");
      this.$emit("pauseMove");
    },
    refresh() {
      this.$emit("refresh", this.markerSpeed);
    },
    mapListTrans(list) {
      let arr = [];
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let items = [item.longitude, item.latitude];
        arr.push(items);
      }
      return arr;
    },
    search() {
      let params = {
        employeeId: this.info.id,
        employeeName: this.info.name,
        beginDate: dayjs(this.form.beginDate).format("YYYY-MM-DD HH:mm:ss"),
        endDate: dayjs(this.form.endDate).format("YYYY-MM-DD HH:mm:ss"),
      };
      getEmployeesTrack(params)
        .then((res) => {
          if (res.length > 0) {
            this.marketList = res;
            console.log(this.marketList);
            const pathData = this.marketList.map((path) => {
              // const next = this.marketList[index+1]
              return {
                position: [path.longitude, path.latitude],
                time: dayjs(path.createdTime).format("YYYY-MM-DD HH:mm:ss"),
                duration: 10000,
                // duration: dayjs(path.createdTime).diff(dayjs(pre.createdTime)),
              };
            });
            console.log(pathData);
            console.log(
              pathData.map((path) => {
                return path?.position;
              })
            );
            this.$emit("setTrack", pathData);
            this.setCurrentRow(0);
          } else {
            this.$message({
              message: "暂无轨迹",
              type: "error",
            });
          }

          //查询增加调度记录
          saveAnalyticsLogs({
            analyticsLogs: [
              {
                referenceNumber: params.employeeId, //轨迹查询对应的职员id
                referenceName: params.employeeName, //轨迹查询对应的职员名称
                type: 0, //职员的轨迹查询对应的类型为0.
                params: {
                  beginDate: params.beginDate, //轨迹查询的起始时间
                  endDate: params.endDate, //截止时间
                },
              },
            ],
          })
            .then((res) => {
              console.log("saveAnalyticsLogs", res);
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log(err);
          this.$message({
            message: err.response.data.message,
            type: "error",
          });
        });
    },
    cancel() {
      this.$emit("cancel");
    },
    setCurrentRow(index) {
      // const row = this.marketList[index]
      this.currentIndex = index;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table__body tr.current-row > td.el-table__cell {
  background-color: #ffff00;
}
.station-types {
  min-width: 448px;
  // height: 332px;
  background: #ffffff;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px 4px 8px 8px;
  border: 2px solid #3e8dff;
  position: absolute;
  top: 50%;
  left: 60%;
  transform: translateY(-50%);
  padding: 0 24px;
  z-index: 999;

  .header {
    height: 54px;
    border-bottom: 1px solid #bdcfde;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333333;
    }

    i {
      cursor: pointer;
      font-size: 16px;
      color: #999999;
    }
  }

  .content {
    .top {
      display: flex;
      align-items: stretch;
      justify-content: flex-start;
      margin: 16px 0 19px 0;

      .location {
        width: 22px;
        height: 22px;
        background: url("~@/assets/images/mapSearch/驻勤点类型.png") no-repeat;
        background-size: 100% 100%;
        margin-right: 8px;
      }

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #0e71ff;
      }
    }

    .type-icon {
      width: 16px;
      height: 16px;
    }

    ::v-deep .el-radio {
      display: flex;
      align-items: center;

      .el-radio__label {
        display: flex;
        align-items: center;
        padding-left: 8px;
        font-size: 16px;
        color: #666666;
      }
    }

    .el-form {
      margin-top: 11px;
      border-bottom: 1px solid #bdcfde;

      .el-row {
        display: flex;

        .time-col-left {
          // margin-bottom: 24px;

          input {
            width: 200px;
          }
        }

        .time-col-right {
          min-width: 120px;
          margin-left: 16px;

          // margin-bottom: 24px;
          button {
            text-align: center;
          }
        }
      }
    }

    .btn-row {
      display: flex;
      align-items: center;
      margin-bottom: 24px;
      width: 100%;
      justify-content: center;
      &2 {
        width: 100%;
        justify-content: center;
        margin-bottom: 16px;
      }

      &-btn {
        width: 60px;
        height: 38px;
        line-height: 38px;
        text-align: center;
        border-radius: 4px;
        border: 1px solid #d9d9d9;
        margin-right: 17px;
        cursor: pointer;
      }

      &-btnAc {
        background: rgba(22, 119, 255, 0.1);
        border-radius: 4px;
        border: 1px solid #1677ff;
      }

      &-btnSelf {
        width: 70px;
        height: 38px;

        ::v-deep .el-input {
          width: 70px;
          height: 30px;
          line-height: 38px;
          font-weight: 500;
          color: #666666;
          font-size: 14px;
        }

        ::v-deep .el-input__inner {
          border: none;
          padding: 0;
          width: 100%;
          height: 100%;
        }
      }

      &-control {
        width: 32px;
        height: 32px;
        margin-right: 16px;

        &:nth-child(3) {
          position: relative;

          &::after {
            content: "";
            width: 1px;
            height: 32px;
            background: #d9d9d9;
            position: absolute;
            right: -16px;
          }
        }

        &:nth-child(4) {
          margin-left: 16px;
        }

        &:nth-last-child(1) {
          margin-right: 16px;
        }

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .detail-row {
      height: 46px;
      line-height: 46px;
      display: flex;
      align-items: center;
      justify-content: center;

      &-btn {
      }
    }
  }
}
</style>
