<template>
  <div class="right-Panel-container">
    <div class="top-title">
      <span class="title-text">区域分布</span>
    </div>
    <div class="map-container">
      <GisMap />
      <Tools></Tools>

      <div class="table-container" v-if="mapStore.currentToolSelectArray.includes('Bidding')">
        <div class="top-box">
          <span>患者: {{ drawPointStore.currentSelectName }}</span>
          <span>编号: {{ drawPointStore.currentSelectId }}</span>
          <el-button class="add-box" type="primary" @click="tableAdd">新增</el-button>
        </div>
        <el-table :data="drawPointStore.currentDrawPointList">
          <el-table-column show-overflow-tooltip label="点位:x" prop="x" min-width="60" />
          <el-table-column show-overflow-tooltip label="点位:y" prop="y" min-width="60" />
          <el-table-column show-overflow-tooltip label="时间" prop="date" min-width="60" />
          <el-table-column show-overflow-tooltip label="地点" prop="address" min-width="60" />
          <el-table-column show-overflow-tooltip label="描述" prop="described" min-width="60" />
          <el-table-column fixed="right" label="操作" min-width="70">
            <template #default="scoped">
              <el-button class="option-button" @click="handleView(scoped)" type="text"
                >查看</el-button
              >
              <el-popconfirm
                title="确定删除当前轨迹点吗?"
                cancel-button-text="取消"
                confirm-button-text="确定"
                @confirm="handleDelete(scoped)"
              >
                <template #reference>
                  <el-button class="option-button option-button-delete" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="search-container" v-if="modifyTrail">
        <div class="search-box">
          <el-input
            v-model="searchParam"
            class="w-50 m-2"
            size="small"
            placeholder="请输入"
            :suffix-icon="Search"
          />
          <el-button @click="handleSearch">搜索</el-button>
        </div>
        <div class="search-result" v-if="searchData && searchData.length > 0">
          <div
            class="search-result-item"
            v-for="(result, index) in searchData"
            :key="index"
            @click="selectPoint(result)"
          >
            <el-form>
              <el-form-item label="类型">{{ result.typeName }}</el-form-item>
            </el-form>
            <el-form>
              <el-form-item label="地址">{{ result.poiAddress }}</el-form-item>
            </el-form>
          </div>
        </div>
        <div class="search-pagination" v-if="searchTotal > 5">
          <el-pagination
            v-model:current-page="searchPageNum"
            @currentChange="currentChange"
            layout="prev, pager, next"
            :total="searchTotal"
            small
          />
        </div>
      </div>

      <div class="info-container" v-if="modifyTrail">
        <el-form>
          <el-form-item class="index-box" label="序号">
            {{ drawPointStore.infoBoxIndex }}</el-form-item
          >
          <!-- <el-form-item class="index-box" label="姓名"></el-form-item>
          <el-form-item class="index-box" label="编号"></el-form-item> -->
          <el-form-item class="index-box" label="地址">
            <el-input
              v-model="address"
              @input="addressInput"
              autosize
              type="text"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item class="index-box point-box" label="坐标">
            <div v-if="drawPointStore.currentDrawPointList[drawPointStore.infoBoxIndex]?.x">
              x:
              {{ drawPointStore.currentDrawPointList[drawPointStore.infoBoxIndex]?.x || '--' }}
            </div>
            <div v-if="drawPointStore.currentDrawPointList[drawPointStore.infoBoxIndex]?.y">
              y:
              {{ drawPointStore.currentDrawPointList[drawPointStore.infoBoxIndex]?.y || '--' }}
            </div>
            <!-- <el-button class="modify-buttton" type="primary">修改点位</el-button> -->
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              v-model="date"
              format="YYYY-MM-DD hh:mm"
              type="datetime"
              placeholder="请选择时间"
              @change="timeSelect"
            />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model="described"
              @input="textSelect"
              autosize
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <div class="point-pagination">
          <span class="left" @click="lastPoint">
            <el-icon><ArrowLeftBold /></el-icon>上一点位
          </span>

          <span class="right" @click="nextPoint">
            下一点位<el-icon><ArrowRightBold /></el-icon>
          </span>
        </div>
      </div>

      <div class="info-button" v-if="modifyTrail">
        <!-- <el-button type="primary" v-if="!drawPointStore.drawStartStatus" @click="startDrawLine"
          >开始画线</el-button
        > -->
        <el-button type="success" @click="handleSave">保存</el-button>
        <el-button type="warning" @click="handleClose">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import GisMap from '@/components/map/GisMap.vue';
import Tools from './Tools.vue';
import { ref } from 'vue';
import { useDrawPointStore } from '@/stores/drawPointManage';
import { useMapStore } from '@/stores/mapStore';
import { ArrowLeftBold, ArrowRightBold, Search } from '@element-plus/icons-vue';
import { startOutputPoint, closeOutputPoint, gotoPosition } from '@/utils/map/mapOperation.js';
import {
  addTrajectorPointOnPeople,
  getGeocode,
  delTrajectorPointOnPeopleByOId,
  getTrajectorPointOnPeopleById,
  updTrajectorPointOnPeopleByOId
} from '@/service/api/mapRequest.js';
import { ElMessage } from 'element-plus';

const drawPointStore = useDrawPointStore();
const mapStore = useMapStore();
const date = ref('');
const described = ref('');
const searchParam = ref('');
const address = ref('');

// 定义格式化封装函数
const formaData = (timer) => {
  const year = timer.getFullYear();
  const month = timer.getMonth() + 1; // 由于月份从0开始，因此需加1
  const day = timer.getDate();
  const hour = timer.getHours();
  const minute = timer.getMinutes();
  const pad = (timeEl, total = 2, str = '0') => {
    return timeEl.toString().padStart(total, str);
  };
  return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}`;
};
const timeSelect = (time) => {
  const val = formaData(time);
  drawPointStore.modifyCurrentDrawPointList('date', val);
};

const textSelect = (val) => {
  drawPointStore.modifyCurrentDrawPointList('described', val);
};

const searchData = ref([]);
const searchPageNum = ref(1);
const searchTotal = ref(0);
const handleSearch = async () => {
  try {
    const res = await getGeocode({
      keyWord: searchParam.value,
      pageIndex: searchPageNum.value,
      pageSize: 5
    });
    searchData.value = [];
    if (res.result) {
      searchData.value = res.result;
      searchTotal.value = res.total;
    } else {
      console.log('geocode:error');
    }
  } catch (error) {
    console.log(error);
  }
};

const addressInput = async () => {
  try {
    drawPointStore.modifyCurrentDrawPointList('address', address.value);
    const res = await getGeocode({
      keyWord: address.value,
      pageIndex: 1,
      pageSize: 5
    });
    if (res?.result?.length > 0) {
      drawPointStore.modifyCurrentDrawPointList('x', res.result[0]?.x || '');
      drawPointStore.modifyCurrentDrawPointList('y', res.result[0]?.y || '');
      gotoPosition(res.result[0]);
    } else {
      console.log('geocode:error');
    }
  } catch (error) {
    console.log(error);
  }
};

//是否在修改或新增轨迹点位
const modifyTrail = ref(false);
const tableAdd = async () => {
  modifyTrail.value = true;
  startOutputPoint(true);
  const newTime = new Date();
  const data = {
    id: drawPointStore.currentSelectId,
    x: '',
    y: '',
    date: formaData(newTime),
    described: '',
    address: ''
  };
  //添加新的一条数据
  drawPointStore.pushCurrentDrawPointList(data);
  date.value = data.date;
  drawPointStore.setInfoBoxIndex(drawPointStore.currentDrawPointList.length - 1);
  //新增
  try {
    const res = await addTrajectorPointOnPeople([data]);
    if (res.code == '200') {
      ElMessage.success('新增成功');
    }
  } catch (error) {
    console.log(error);
  }
};

const handleView = (scope) => {
  const row = scope.row;
  const index = scope.$index;
  drawPointStore.setInfoBoxIndex(index);
  date.value = drawPointStore.currentDrawPointList[index]?.date || '';
  address.value = drawPointStore.currentDrawPointList[index]?.address || '';
  described.value = drawPointStore.currentDrawPointList[index].described || '';
  modifyTrail.value = true;
  startOutputPoint(true);
  gotoPosition({
    x: row.x,
    y: row.y
  });
};

//重新获取当前病例列表数据
const getCurrentData = async () => {
  const result = await getTrajectorPointOnPeopleById({
    id: drawPointStore.currentSelectId
  });
  if (result.code == 200) {
    drawPointStore.currentDrawPointList = result.data || [];
    const index = drawPointStore.currentDrawPointList.length - 1;
    drawPointStore.setInfoBoxIndex(index);
  } else {
    console.log('获取病例轨迹数据错误');
  }
};

//删除
const handleDelete = async (scoped) => {
  try {
    const res = await delTrajectorPointOnPeopleByOId({
      oId: scoped.row.oid
    });
    if (res.code == 200) {
      ElMessage.success('删除成功');
      getCurrentData();
    } else {
      throw 'delTrajectorPointOnPeopleByOId：error';
    }
  } catch (error) {
    ElMessage('删除失败');
    console.log(error);
  }
};

const currentChange = () => {
  handleSearch();
};

//搜索框选中点
const selectPoint = (result) => {
  gotoPosition(result);
  address.value = result.poiAddress;
};

const startDrawLine = () => {
  //标会工具，使用坐标点输出来做
  startOutputPoint(true);
  //开始画线
  drawPointStore.setDrawStartStatus(true);
};

const handleSave = async () => {
  try {
    const data = drawPointStore.currentDrawPointList[drawPointStore.infoBoxIndex];
    data.oId = data.oid;
    data.address = 76650012223;
    delete data.oid;
    const res = await updTrajectorPointOnPeopleByOId(data);
    if (res.code == 200) {
      ElMessage.success('修改成功');
      getCurrentData();
    } else {
      ElMessage('修改失败');
      throw '修改接口错误';
    }
  } catch (error) {
    console.log(error);
  }
};

const handleClose = () => {
  modifyTrail.value = false;
  closeOutputPoint();
  getCurrentData();
};

const lastPoint = () => {
  //上一点位
  if (drawPointStore.infoBoxIndex <= 0) return;
  const index = drawPointStore.infoBoxIndex - 1;
  drawPointStore.setInfoBoxIndex(index);
  date.value = drawPointStore.currentDrawPointList[index]?.date || '';
  address.value = drawPointStore.currentDrawPointList[index]?.address || '';
  described.value = drawPointStore.currentDrawPointList[index]?.described || '';
  gotoPosition({
    x: drawPointStore.currentDrawPointList[index].x,
    y: drawPointStore.currentDrawPointList[index].y
  });
};
const nextPoint = () => {
  //下一点位
  if (drawPointStore.infoBoxIndex >= drawPointStore.currentDrawPointList.length - 1) return;
  const index = drawPointStore.infoBoxIndex + 1;
  drawPointStore.setInfoBoxIndex(index);
  date.value = drawPointStore.currentDrawPointList[index]?.date || '';
  address.value = drawPointStore.currentDrawPointList[index]?.address || '';
  described.value = drawPointStore.currentDrawPointList[index]?.described || '';
  gotoPosition({
    x: drawPointStore.currentDrawPointList[index].x,
    y: drawPointStore.currentDrawPointList[index].y
  });
};
</script>

<style lang="scss" scoped>
.right-Panel-container {
  padding-top: 22px;
  .top-title {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background-image: url('@/assets/image/title-bg.png');
    background-size: 100% 100%;
    width: 1020px;
    font-size: 28px;
    color: #ffffff;
    margin-left: 10px;
    height: 56px;
    padding-left: 20px;
    .title-text {
      position: relative;
      top: -5px;
    }
  }
  .map-container {
    position: relative;
    width: 1045px;
    height: 976px;
    margin-top: 27px;

    .info-button {
      position: absolute;
      background-color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 250px;
      height: 45px;
      bottom: 20px;
      right: 10px;
    }
    .info-button-play {
      width: 100px;
    }
    .point-pagination {
      color: #0080ff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      .left,
      .right {
        .el-icon {
          position: relative;
          top: 2px;
          margin: 5px;
        }
      }
    }

    .table-container {
      position: absolute;
      padding: 10px 8px;
      bottom: 20px;
      left: 100px;
      width: 500px;
      height: 350px;
      background: #ffffff;
      box-shadow: 0px 4px 5px #cccccc;
      overflow: hidden;
      .option-button {
        width: 30px;
      }
      .top-box {
        display: flex;
        justify-content: flex-start;
        padding-right: 20px;
        span {
          margin-right: 10px;
        }
        .add-box {
          width: 40px;
          height: 30px;
          margin-left: auto;
        }
      }
      :deep(.el-table) {
        height: calc(100% - 50px);
        .cell {
          padding: 0;
        }
        .el-table__cell {
          padding: 5px 3px;
        }
        .el-button + .el-button {
          margin-left: 5px;
        }
      }
      .table-row-head,
      .table-row-box {
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        height: 25px;
        font-size: 14px;
        .table-td {
          flex: 1;
          text-align: center;
        }
      }
      .table-row-head {
        background-color: #dde2eb;
      }
      .table-row-box {
      }
    }

    :deep(.search-container) {
      position: absolute;
      top: 40px;
      right: 20px;
      .search-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 40px;
        width: 250px;
        padding: 10px;
        background-color: #ffffff;
        box-shadow: 0px 4px 5px #cccccc;
        .el-input {
          width: calc(100% - 40px);
          height: 25px;
        }
        .el-button {
          width: 40px;
          height: 25px;
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
      }
      .search-result {
        height: 300px;
        width: 250px;
        background: #ffffff;
        margin-top: 5px;
        box-shadow: 0px 3px 5px #cccccc;
        padding: 10px 15px;
        overflow-y: auto;
        scrollbar-width: none;
        .search-result-item {
          background: rgb(0, 128, 255, 0.1);
          margin-bottom: 10px;
          padding: 10px;
          .one {
            font-size: 14px;
            padding: 3px 7px;
            color: rgba(63, 63, 63, 1);
          }
          .el-form-item {
            margin: 0;
            .el-form-item__content,
            .el-form-item__label {
              line-height: 1.3;
            }
          }
        }
      }
      .search-pagination {
        width: 250px;
        padding: 10px;
        background-color: #ffffff;
        .el-pagination {
          width: 250px;
        }
      }
    }
    :deep(.info-container) {
      position: absolute;
      background-color: #ffffff;
      box-shadow: 0px 4px 5px #cccccc;
      padding: 10px;
      font-size: 16px;
      width: 250px;
      bottom: 65px;
      right: 10px;

      .index-box {
        margin: 0;
      }
      .point-box {
        position: relative;
        .modify-buttton {
          height: 30px;
          padding: 3px 5px;
          margin-bottom: 10px;
        }
      }

      .el-form-item__label {
        font-size: 15px;
        width: 45px;
      }
      input,
      textarea {
        height: unset !important;
        min-height: unset !important;
      }
    }
  }
}
</style>
