<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">路线管理</span>
    </div>
    <div class="middles">
      <div class="middle">
        <!-- 路线管理 -->
        <div class="filter">
          <!-- <div class="addRoute">
            <el-button
              type="primary"
              color="rgba(61, 81, 232, 1)"
              @click="addroute"
              ><el-icon><CirclePlus /></el-icon><span>新增路线</span></el-button
            >
          </div> -->
          <el-table
            :data="pathNum.list"
            @selection-change="handleSelectionChange"
            style="
              width: 100%;
              --el-table-border-color: none;
              font-size: 16px;
              color: #000;
            "
            height="138"
            :header-cell-style="{
              height: '40px',
              border: 0,
              fontSize: '16px',
              color: '#000',
            }"
          >
            <el-table-column
              align="left"
              prop="route"
              label="出发路线名称"
              width="300"
            />
            <el-table-column align="left" label="候补截止时间" width="300"
              ><template #default="scope">
                <el-time-picker
                  ref="hb_time"
                  v-model="scope.row.repair_end"
                  placeholder="请选择时间"
                  format="HH:mm"
                  value-format="HH:mm"
                  :clearable="false"
                  :editable="false"
                  @change="savePath(scope.row, '是否修改候补截止时间')"
                />
                <!-- @change="savePath(scope.row, '是否修改候补截止时间')" -->
              </template>
            </el-table-column>
            <el-table-column label="是否候补" width="150" align="center">
              <template #default="scope">
                <el-switch
                  :disabled="
                    scope.row.repair_end == '' || scope.row.repair_end == 'null'
                      ? true
                      : false
                  "
                  v-model="scope.row.state"
                  class="ml-2"
                  style="
                    --el-switch-on-color: rgba(
                      61,
                      81,
                      232,
                      1
                    ); /*
                --el-switch-off-color: rgba(61, 81, 232, 1); */
                  "
                  @change="savePath(scope.row, '是否启用候补')"
                />
                <!-- @change="savePath(scope.row, '是否启用/取消候补')" -->
              </template>
            </el-table-column>
          </el-table>
          <!-- <div class="route">
            <div class="startRoute">
              <div class="name">出发路线名称</div>
            </div>
            <div class="startRoute waiting">
              <div class="name">是否候补</div>
            </div>
          </div>
          <div class="routes">
            <div class="route" v-for="item in pathNum.list">
              <div class="startRoute">
                <el-input
                  clearable
                  v-model="item.route"
                  placeholder="请输入路线名称"
                />
              </div>
              <div class="startRoute waiting">
                <el-switch
                  style="
                    --el-switch-on-color: rgba(61, 81, 232, 1);
                    /* --el-switch-off-color: rgba(61, 81, 232, 1); */
                  "
                  v-model="item.is_repair"
                  :active-value="1"
                  :inactive-value="0"
                  size="large"
                />
              </div>
              <div class="startRoute save">
                <el-button
                  type="primary"
                  color="rgba(61, 81, 232, 1)"
                  @click="savePath(item.id)"
                  ><span>保存</span></el-button
                >
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </div>
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">站点管理</span>
    </div>
    <div class="gongneng">
      <el-button type="primary" color="rgba(61, 81, 232, 1)" @click="addlist"
        ><el-icon><CirclePlus /></el-icon><span>新增站点</span></el-button
      >
    </div>
    <!-- 站点管理 -->

    <div class="footer">
      <el-table
        :row-class-name="tableRowClassName"
        :data="tableData.list"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '45px',
          border: 0,
        }"
      >
        <!-- <el-table-column align="center" type="selection" width="80" /> -->
        <el-table-column align="center" prop="route" label="路线名称" />
        <el-table-column align="center" prop="route_end" label="站点" />
        <el-table-column align="center" prop="create_time" label="创建时间" />

        <el-table-column align="center" label="操作" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="edit(scope.row)"
              ><div class="look">编辑</div></el-button
            >
            <el-button link type="danger" @click="del(scope.row)"
              ><div class="looks">删除</div></el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加路线弹窗 -->
      <el-dialog
        class="addStaff"
        v-model="addDialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="dialongTitle"
        align-center
        width="609"
        :before-close="cancelAdd"
      >
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :size="formSize"
          label-position="left"
          status-icon
        >
          <el-form-item label="线路名称 :" prop="route">
            <el-select
              v-model="ruleForm.route"
              class="m-2"
              placeholder="请选择线路名称"
            >
              <el-option
                :label="item.route"
                :value="item.route"
                v-for="item in pathNum.list"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="终点站 :" prop="route_end">
            <el-input
              clearable
              v-model="ruleForm.route_end"
              placeholder="请输入终点站"
            />
          </el-form-item>

          <el-form-item class="options">
            <el-button class="congzhi" @click="cancelAdd(ruleFormRef)"
              >取消</el-button
            >
            <el-button
              color="rgba(61, 81, 232, 1)"
              class="queding"
              type="primary"
              @click="submitAdd(ruleFormRef)"
            >
              确定
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper, slot"
      :total="total"
      @update:current-page="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();
const hb_time = ref(); // 路线管理候补截止时间组件 ref
// 表格数据
const tableData = reactive({
  list: [],
});
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增站点"); // 弹窗标题

const searchInput = reactive({
  carnumber: "",
  createTime: "",
  route: "",
  citime: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(6);
const total = ref(10); // 当前总数
const selectData = reactive({
  list: [],
}); // 多选框选择的数据

const addDialogVisible = ref(false); // 控制添加员工弹窗

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  route: [],
  route_end: "",
  id: "",
  is_repair: "",
});
const pathNum = reactive({ list: [] });
// 表单验证
const rules = reactive({
  route: [{ required: true, message: "线路名称不能为空", trigger: "blur" }],
  route_end: [
    {
      required: true,
      message: "终点站不能为空",
      trigger: "blur",
    },
  ],
});

watch(
  () => pathNum.list,
  (newValue, oldValue) => {
    newValue.forEach(async (item) => {
      if (item.repair_end == "" || item.repair_end == "null") {
        console.log("时间为空");
        item.state = false;
        item.is_repair = "0";
        let data = new FormData();
        data.set("route", item.route);
        data.set("is_repair", item.is_repair);
        data.set("repair_end", item.repair_end);
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/routeupdateState.action",
          headers: {
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        console.log(res, "修改路线候补时间和是否开启");
        if (res.data.code == 200) {
          store.dispatch("pathSelect");
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    });
  }
);

// 获取车次信息
const getList = async (flag) => {
  let data = new FormData();
  if (searchInput.createTime == null) {
    searchInput.createTime = "";
  }
  data.set("create_time", searchInput.createTime);
  data.set("page", currentPage.value);
  data.set("rows", pageSize.value);
  let res = await axios({
    method: "post",
    url: api.value + "/carBook/routelist.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  // console.log(res);

  if (res.status == 200) {
    tableData.list = res.data.rows;
    tableData.list.forEach((item) => {
      item.route2 = item.route;
      item.route_end2 = item.route_end;
      item.path_start = item.route.split("-")[0];
      item.path_end = item.route.split("-")[1];
      if (item.is_repair == "" || item.is_repair == 0) {
        item.state = false;
      } else if (item.is_repair == 1) {
        item.state = true;
      }
    });
    // let pathSelect = tableData.list.filter((item) => {
    //   return item.is_repair == 1;
    // });
    // console.log(pathSelect);
    // pathNum.list = pathSelect;
    total.value = res.data.total;
  } else {
    tableData.list = res.data.rows;
    currentPage.value = 1;
    total.value = res.data.total;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
    if (res.data.message == "token错误") {
      router.push({
        path: `/login`,
      });
    }
  }
};

// 修改路线候补时间和是否开启
const savePath = async (row, title) => {
  ElMessageBox.confirm(`${title}`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let augment = pathNum.list.filter((item) => {
        return item.id == row.id;
      });
      if (augment[0].state == false) {
        augment[0].is_repair = 0;
      } else if (augment[0].state == true) {
        augment[0].is_repair = 1;
      }
      let data = new FormData();
      data.set("route", augment[0].route);
      data.set("is_repair", augment[0].is_repair);
      data.set("repair_end", augment[0].repair_end);
      let res = await axios({
        method: "post",
        url: api.value + "/carBook/routeupdateState.action",
        headers: {
          token: sessionStorage.getItem("token"),
        },
        data: data,
      });
      // console.log(res, "修改路线候补时间和是否开启");
      if (res.data.code == 200) {
        getList();
        store.dispatch("pathSelect");
        console.log(hb_time.value);
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    })
    .catch((action) => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
      pathNum.list = JSON.parse(sessionStorage.getItem("pathSelect"));
      if (row.is_repair == 0) {
        row.state = false;
      } else if (row.is_repair == 1) {
        row.state = true;
      }
    });
};
// 确定修改路线候补时间时选择时间框没有关闭的bug
const handleClose = (val) => {
  console.log(val);
};

// 确定截止时间
const timeUpdata = (row) => {
  console.log(row);
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList("查询成功");
}, 300);

// 添加车次
const addlist = () => {
  dialongTitle.value = "新增站点";
  addDialogVisible.value = true;
  ruleForm.route = [];
  ruleForm.route_end = "";
};
//编辑按钮
const edit = (row) => {
  dialongTitle.value = "编辑站点";
  addDialogVisible.value = true;
  ruleForm.route = row.route;
  ruleForm.route_end = row.route_end;
  ruleForm.id = row.id;
  ruleForm.is_repair = row.is_repair;
  ruleForm.repair_end = row.repair_end;
};
// 取消添加车次
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
// 重置搜索
const searchRefresh = lodash.debounce(async () => {
  searchInput.createTime = "";
  currentPage.value = 1;
  getList();
}, 300);
// 确认新增车次
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "新增站点") {
        let data = {
          route: ruleForm.route,
          route_end: ruleForm.route_end,
          // repair_end: ruleForm.repair_end,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/routeinsert.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        // console.log(res, "添加账号");
        if (res.data.code == 200) {
          getList();
          store.dispatch("pathSelect");
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        let data = {
          route: ruleForm.route,
          route_end: ruleForm.route_end,
          id: ruleForm.id,
          is_repair: ruleForm.is_repair,
          repair_end: ruleForm.repair_end,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/routeupdate.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        // console.log(res, "修改账号");
        if (res.data.code == 200) {
          getList();
          store.dispatch("pathSelect");
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("错误提交", fields);
    }
  });
};

//删除按钮
const del = (row) => {
  ElMessageBox.confirm(`是否删除 ${row.route} 这条路线?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let data = new FormData();
      data.set("id", row.id);
      // let res = await adminApi.adminLogin(data);
      let res = await axios({
        method: "post",
        url: api.value + "/carBook/routedel.action",
        headers: {
          token: sessionStorage.getItem("token"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        if (tableData.list.length == 1 && currentPage.value != 1) {
          currentPage.value = currentPage.value - 1;
        }

        getList();
        store.dispatch("pathSelect");
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
      console.log(res);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 分页
const handleCurrentChange = (value) => {
  console.log(value);
  currentPage.value = value;
  getList();
};

onBeforeMount(() => {
  pathNum.list = JSON.parse(sessionStorage.getItem("pathSelect"));
  console.log(pathNum.list);
  api.value = store.state.user.api;
  getList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
::-webkit-scrollbar {
  /* 对应纵向滚动条的宽度 */
  width: 10px;
  /* 对应横向滚动条的宽度 */
  height: 10px;
}

/* 滚动条上的滚动滑块 */
::-webkit-scrollbar-thumb {
  background-color: rgba(61, 81, 232, 1);
  border-radius: 32px;
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  background-color: rgba(61, 81, 232, 0.2);
  border-radius: 32px;
}
.content-box {
  width: 97.5%;
  height: 89%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    padding: 10px 0;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
  }
  .middles {
    .middle {
      width: 96%;
      margin: 0 auto;
      color: #000;
      // border-bottom: 1px solid rgb(231, 231, 231);
      .filter {
        // display: flex;
        // flex-wrap: wrap;
        // align-items: center;
        margin: 10px 10px 0 10px;
        .route {
          display: flex;
          align-items: center;
          margin: 10px 0 0 0;
          .startRoute {
            width: 200px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            .name {
              margin: 10px 0;
              font-size: 14px;
            }
          }
          .waiting {
            align-items: center;
            margin: 0 40px;
          }
          .line {
            // transform: translateY(48px);
            padding: 0 20px;
          }
          .save {
            .el-button {
              width: 100px;
            }
          }
        }
        .routes {
          height: 100px;
          overflow: auto;
        }
      }

      :deep(.cont) {
        width: 60%;
        margin: 20px auto;
      }
      :deep(.download) {
        display: flex;
        align-items: center;
        margin: 10px;
      }
      :deep(.download span) {
        font-size: 16px;
        margin-left: 20px;
      }
      :deep(.cont .el-button) {
        margin-left: 60px;
        margin-bottom: 30px;
      }

      :deep(.cont .accomplish) {
        width: 100%;
        display: flex;
        justify-content: center;
      }
      :deep(.cont .accomplish .el-button) {
        width: 50%;
        margin: 0;
      }
    }
  }

  .gongneng {
    margin: 20px 25px;
  }
  .footer {
    width: 96%;
    height: 550px;
    margin: 10px auto 30px;
    .el-table--fit {
      height: 100%;
      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;
        color: #000;
      }
      :deep(.el-table__row) {
        height: 45px;
        font-size: 16px;
        color: #000;
      }
      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }
      :deep(.el-table__body .even) {
        background-color: #fff;
      }
      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }
      :deep(.look) {
        padding: 5px 10px;
        border-radius: 45px;
        border: 0.74px solid rgba(30, 125, 251, 1);
      }
      :deep(.looks) {
        padding: 5px 10px;
        border-radius: 45px;
        border: 0.74px solid #f56c6c;
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;
      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;
        .el-dialog__headerbtn {
          outline: none;
        }
      }
      .el-dialog__body {
        padding: 30px 20px 10px 20px;
        .el-form-item {
          label {
            width: 120px !important;
          }
          .el-form-item__label {
            width: 120px !important;
          }
          .informTime {
            display: flex;
            align-items: center;
            .el-input {
              width: 120px;
              margin-right: 10px;
              .el-input__inner {
                text-align: center;
              }
            }
          }
        }
        .el-form-item__content {
          flex: none;
          .el-input {
            width: 370px;
          }
        }
        .el-input {
          width: 200px;
        }
        .options {
          margin-left: 320px;
        }
      }
    }
  }
  .el-pagination {
    // width: 1600px;
    width: 96%;
    margin: 0 auto 18px;
    justify-content: flex-end;
    :deep(.el-pagination__total) {
      color: #000;
    }
    :deep(.el-pagination__goto) {
      color: #000;
    }
    :deep(.el-pagination__classifier) {
      color: #000;
    }
    :deep(.el-input__wrapper) {
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      box-shadow: none;
    }
    :deep(.el-pager li) {
      margin: 0 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }
    :deep(.el-pager li.is-active) {
      background-color: rgba(30, 125, 251, 1);
    }
    :deep(.btn-prev) {
      margin-right: 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }
    :deep(.btn-next) {
      margin-left: 5px;
      border: 1px solid rgba(0, 0, 0, 1);
      border-radius: 5px;
      background-color: transparent;
    }
  }
}
.el-input {
  width: 192px;
}
</style>
