<template>
  <div class="content-box" v-if="addShow">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">班次管理</span>
    </div>
    <div class="middle">
      <div class="filter">
        <div class="condition">
          <span>班次名称 : </span>
          <el-input
            clearable
            v-model="searchInput.name"
            class="w-50 m-2"
            placeholder="请输入关键字"
            style="width: 150px"
          />
        </div>
        <div class="condition">
          <span>创建时间 : </span>
          <el-date-picker
            v-model="searchInput.createTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
          />
        </div>

        <el-button
          style="margin-left: 20px"
          color="rgba(61, 81, 232, 1)"
          type="primary"
          class="search"
          @click="searchBtn"
          ><el-icon><Search /></el-icon> <span>查询</span></el-button
        >
        <el-button
          style="margin-left: 20px !important"
          color="rgba(61, 81, 232, 1)"
          type="primary"
          class="search"
          @click="searchRefresh"
          ><el-icon><Refresh /></el-icon><span>重置</span></el-button
        >
      </div>
      <!-- 按钮列表 -->
      <div class="gongneng">
        <el-button type="primary" color="rgba(61, 81, 232, 1)" @click="addClass"
          ><el-icon><CirclePlus /></el-icon><span>新增班次</span></el-button
        >
      </div>
    </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: '50px',
          border: 0,
        }"
      >
        <!-- <el-table-column align="center" type="selection" width="80" /> -->
        <!-- <el-table-column
          type="index"
          width="80"
          align="center"
          label="序号"
          index="1"
        /> -->
        <el-table-column
          align="center"
          prop="name"
          label="班次名称"
          width="200"
        />
        <el-table-column label="是否启用" width="150" align="center">
          <template #default="scope">
            <el-switch
              @change="startClasses(scope.row)"
              :disabled="false"
              v-model="scope.row.states"
              class="ml-2"
              style="
                --el-switch-on-color: rgba(61, 81, 232, 1);
                /* --el-switch-off-color: rgba(61, 81, 232, 1); */
              "
            />
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="route" label="路线" /> -->
        <el-table-column align="center" prop="create_time" label="创建时间" />
        <el-table-column align="center" prop="work_duration" label="运行时间" />

        <el-table-column align="center" label="操作" width="250">
          <template #default="scope">
            <el-button link type="primary" @click="particulars(scope.row)"
              ><div class="look">详情</div></el-button
            >
            <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="400"
        :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="name">
            <el-input
              clearable
              v-model="ruleForm.name"
              placeholder="请输入班次名称"
            />
          </el-form-item>
          <el-form-item
            label="是否启用 :"
            prop="stateRadio"
            style="
              padding-bottom: 40px;
              border-bottom: 1px solid rgba(230, 230, 230, 1);
            "
          >
            <el-radio-group v-model="ruleForm.stateRadio" class="ml-4">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="0" size="large">否</el-radio>
            </el-radio-group>
          </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> -->
      <!-- 班次详情弹窗 -->
      <el-dialog
        class="addStaff particulars"
        v-model="particularsDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="dialongTitle"
        align-center
        width="1200"
        :before-close="particularsCancel"
      >
        <el-table
          :row-class-name="tableRowClassName"
          :data="tableData.buslist"
          @selection-change="handleSelectionChange"
          style="width: 100%; height: 500px"
          :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }"
        >
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column
            width="150"
            align="center"
            prop="ci_time"
            label="发车时间"
          />
          <el-table-column align="center" prop="car_number" label="车牌号" />
          <el-table-column align="center" prop="contain" label="容量" />
          <el-table-column
            align="center"
            width="250"
            prop="route"
            label="线路名称"
          />
          <el-table-column
            align="center"
            width="150"
            prop="route_end"
            label="线路终点"
          />
          <el-table-column align="center " width="300" label="周期">
            <template #default="scope">
              <div>{{ scope.row.weekarr }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否提前预约">
            <template #default="scope">
              <div>{{ scope.row.before_state == 1 ? "是" : "否" }}</div>
            </template>
          </el-table-column>
        </el-table>
      </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>
  <div class="content-box" v-else>
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <div class="cameratxt" @click="backClass">
        <img style="width: 20px; height: 20px" src="@/assets/back.png" alt="" />
        <span style="font-weight: 600; font-size: 17px"
          >&nbsp;{{ dialongTitle }}</span
        >
      </div>
    </div>
    <div class="middle">
      <div class="filter">
        <el-form
          ref="ruleFormRef"
          :rules="rules"
          :inline="true"
          :size="formSize"
          status-icon
          :model="ruleForm"
          class="demo-form-inline"
        >
          <el-form-item label="班次名称 : " prop="name">
            <el-input
              clearable
              v-model="ruleForm.name"
              class="w-50 m-2"
              placeholder="请输入班次名称"
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="运行时间 : " prop="createTime">
            <!-- <el-date-picker
              v-model="ruleForm.createTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :prefix-icon="Calendar"
              placeholder="请选择日期"
            /> -->
            <el-date-picker
              v-model="ruleForm.createTime"
              :unlink-panels="true"
              type="daterange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :size="size"
            />
          </el-form-item>
          <el-form-item>
            <span style="color: #606266">是否启用 : &nbsp;</span>
            <el-switch
              style="
                --el-switch-on-color: rgba(61, 81, 232, 1);
                /* --el-switch-off-color: rgba(61, 81, 232, 1); */
              "
              :disabled="!tableData.buslist.length"
              v-model="ruleForm.ClassSwitch"
              size="large"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              style="margin-left: 20px; width: 80px"
              color="rgba(61, 81, 232, 1)"
              type="primary"
              class="search"
              @click="busSave(ruleFormRef)"
            >
              <span>保存</span></el-button
            >
          </el-form-item>
        </el-form>
        <!-- <div class="condition">
          <span>班次名称 : </span>
          <el-input
            clearable
            v-model="searchInput.name"
            class="w-50 m-2"
            placeholder="请输入关键字"
            style="width: 150px"
          />
        </div>
        <div class="condition">
          <span>创建时间 : </span>
          <el-date-picker
            v-model="searchInput.createTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :prefix-icon="Calendar"
            placeholder="请选择日期"
          />
        </div>
        <div class="condition">
          <span>是否启用 : </span>
          <el-switch
            class="switchClass"
            style="
              --el-switch-on-color: rgba(61, 81, 232, 1);
              /* --el-switch-off-color: rgba(61, 81, 232, 1); */
            "
            v-model="ClassSwitch"
            size="large"
          />
        </div>
        <el-button
          style="margin-left: 20px; width: 80px"
          color="rgba(61, 81, 232, 1)"
          type="primary"
          class="search"
          @click="busSave"
        >
          <span>保存</span></el-button
        > -->
      </div>
      <!-- 新增车次按钮列表 -->
      <div class="gongneng">
        <el-button
          type="primary"
          color="rgba(61, 81, 232, 1)"
          :disabled="busAddshow"
          @click="addbus"
          ><el-icon><CirclePlus /></el-icon><span>新增车次</span></el-button
        >
        <!-- <el-button
          color="rgba(61, 81, 232, 1)"
          class="import"
          type="primary"
          @click="importExcel"
          ><img
            src="@/assets/import.png"
            style="width: 14px; height: 14px; margin-right: 4px"
            alt=""
          />
          <span>导出表单</span></el-button
        > -->
      </div>
    </div>
    <div class="footer">
      <el-table
        :row-class-name="tableRowClassName"
        :data="tableData.buslist"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '50px',
          border: 0,
        }"
      >
        <el-table-column
          align="center"
          prop="ci_time"
          label="发车时间"
          width="150"
        />

        <el-table-column align="center" prop="car_number" label="车牌号" />
        <el-table-column
          align="center"
          prop="contain"
          width="80"
          label="容量"
        />
        <el-table-column align="center" prop="route" label="线路名称" />
        <el-table-column align="center" prop="route_end" label="线路终点" />
        <el-table-column align="center" label="周期" width="300">
          <template #default="scope">
            <div>{{ scope.row.weekarr }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="100" label="是否提前预约">
          <template #default="scope">
            <div>{{ scope.row.before_state == 1 ? "是" : "否" }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="busedit(scope.row)"
              ><div class="look">编辑</div></el-button
            >
            <el-button link type="danger" @click="busdel(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="400"
        :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="name">
            <el-input
              clearable
              v-model="ruleForm.name"
              placeholder="请输入班次名称"
            />
          </el-form-item>
          <el-form-item
            label="是否启用 :"
            prop="stateRadio"
            style="
              padding-bottom: 40px;
              border-bottom: 1px solid rgba(230, 230, 230, 1);
            "
          >
            <el-radio-group v-model="ruleForm.stateRadio" class="ml-4">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="0" size="large">否</el-radio>
            </el-radio-group>
          </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> -->

      <!-- 车次页面编辑弹窗 -->
      <el-dialog
        class="busAdd"
        v-model="busdialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="busdialogTitle"
        align-center
        width="680"
        :before-close="cancelbus"
      >
        <el-form
          ref="ruleFormRefBus"
          :model="ruleFormBus"
          :rules="rulesBus"
          label-width="100px"
          class="demo-ruleForm"
          :size="formSize"
          label-position="left"
          status-icon
        >
          <el-form-item label="发车时间 :" prop="startTime">
            <el-time-picker
              v-model="ruleFormBus.startTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="请选择发车时间"
            />
          </el-form-item>
          <el-form-item label="车牌号 :" prop="busnumber">
            <el-select
              v-model="ruleFormBus.busnumber"
              class="m-2"
              placeholder="请选择车牌号"
            >
              <el-option
                :label="item.car_number"
                :value="item.car_number"
                :key="item.car_number"
                v-for="item in busNum.list"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="容量 :" prop="contain">
            <el-input
              style="width: 220px;"
              :disabled="true"
              v-model="ruleFormBus.contain"
              placeholder="请输入容量"
              clearable
            />
          </el-form-item>

          <el-form-item label="路线 :" prop="route">
            <el-select
              v-model="ruleFormBus.route"
              class="m-2"
              placeholder="请选择路线"
              @change="changeRoute"
            >
              <el-option
                :label="item.route"
                :value="item.route"
                :key="item.route"
                v-for="item in pathNum.list"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="终点站 :" prop="busterminus">
            <!-- <el-input
              v-model="ruleFormBus.busterminus"
              placeholder="请输入终点站"
              clearable
            /> -->
            <el-select
              v-model="ruleFormBus.busterminus"
              class="m-2"
              placeholder="请输入终点站"
            >
              <el-option
                :label="item.route_end"
                :value="item.route_end"
                :key="item.route_end"
                v-for="item in route_endSelect.list"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="周期 :" prop="weeks">
            <el-checkbox-group v-model="ruleFormBus.weeks">
              <el-checkbox
                v-for="item in checkweeks"
                :key="item"
                :label="item"
                >{{ item }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            label="是否可提前一天预约"
            prop="yesterday"
            class="yesterday"
            style="
              padding-bottom: 20px;
              border-bottom: 1px solid rgba(230, 230, 230, 1);
            "
          >
            <el-switch
              v-model="ruleFormBus.yesterday"
              size="large"
              style="
                --el-switch-on-color: rgba(61, 81, 232, 1);
                /* --el-switch-off-color: rgba(61, 81, 232, 1); */
              "
            />
          </el-form-item>

          <el-form-item class="options">
            <el-button class="congzhi" @click="cancelbus(ruleFormRefBus)"
              >取消</el-button
            >
            <el-button
              color="rgba(61, 81, 232, 1)"
              class="queding"
              type="primary"
              @click="submitAddBus(ruleFormRefBus)"
            >
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="currentPage2"
      :page-size="pageSize2"
      layout="total, prev, pager, next, jumper, slot"
      :total="total2"
      @update:current-page="handleCurrentChange2"
    />
  </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 lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();
const pathNum = reactive({ list: [] });
const busNum = reactive({ list: [] });
const route_endSelect = reactive({ list: [] });

// 表格数据
const tableData = reactive({
  list: [],
  buslist: [],
});
// 新增班次页面
const activeIndex = ref(); // 默认跳转路由
const dialongTitle = ref("新增班次"); // 弹窗标题
const addShow = ref(true); // 新增班次按钮
const particularsDialog = ref(false); //详情页面弹窗

// 新增车次页面
const busdialog = ref(false); // 控制新增车次页面编辑按钮
const busAddshow = ref(true); // 当新增班次的时候，车次新增按钮不能使用
const busdialogTitle = ref("新增车次");
const checkweeks = ref([
  "周一",
  "周二",
  "周三",
  "周四",
  "周五",
  "周六",
  "周日",
]);

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

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数

const currentPage2 = ref(1); // 当前页
const pageSize2 = ref(10);
const total2 = ref(); // 当前总数

const selectData = reactive({
  list: [],
}); // 多选框选择的数据

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

// 表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const ruleFormRefBus = ref();
// const ruleForm = reactive({
//   route: "南昌校区",
//   startTime: "16:30",
//   id: "",
// });
// // 表单验证
// const rules = reactive({
//   startTime: [
//     { required: true, message: "时间不能为空", trigger: "blur" },
//     // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
//   ],
//   route: [
//     {
//       required: true,
//       message: "路线不能为空",
//       trigger: "blur",
//     },
//   ],

//   // desc: [{ required: true, message: "Please input activity form", trigger: "blur" }],
// });
const ruleForm = reactive({
  ClassSwitch: false,
  name: "",
  createTime: "",
  id: "", //编辑车次时用到的b_id
});
const ruleFormBus = reactive({
  startTime: "", //发车时间
  route: "",
  busterminus: "", // 终点站
  weeks: [],
  yesterday: 0,
  busnumber: [],
  contain: "",
  id: "",
});
// 表单验证
const rules = reactive({
  name: [
    { required: true, message: "班次名称不能为空", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  createTime: [
    { required: true, message: "运行时间不能为空", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
});
const rulesBus = reactive({
  startTime: [{ required: true, message: "发车时间不能为空", trigger: "blur" }],
  route: [{ required: true, message: "路线不能为空", trigger: "blur" }],
  busterminus: [{ required: true, message: "终点站不能为空", trigger: "blur" }],
  weeks: [{ required: true, message: "周期不能为空", trigger: "blur" }],
  contain: [
    { required: true, message: "容量不能为空", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "请输入正确数字",
      trigger: "blur",
    },
  ],
  busnumber: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
  // yesterday: [
  //   { required: true, message: "班次名称不能为空", trigger: "blur" },
  //   // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  // ],
});

// 监控车牌号
watch(
  () => ruleFormBus.busnumber,
  (newValue, oldValue) => {
    console.log(newValue);
    if (!newValue == "") {
      let arr = busNum.list.filter((item) => {
        return item.car_number == newValue;
      });
      console.log(arr);
      if (arr == []) {
      } else {
        ruleFormBus.contain = arr[0].contain;
      }
    }
  }
);

// 监控路线
// watch(
//   () => ruleFormBus.route,
//   (newValue, oldValue) => {
//     console.log(newValue);
//     let arr = JSON.parse(sessionStorage.getItem("route_endSelect"));
//     // ruleFormBus.busterminus = "";
//     route_endSelect.list = arr.filter((item) => {
//       return item.route == newValue;
//     });
//   }
// );
const changeRoute = (val) => {
  let arr = JSON.parse(sessionStorage.getItem("route_endSelect"));
  ruleFormBus.busterminus = "";
  route_endSelect.list = arr.filter((item) => {
    return item.route == val;
  });
};

// 获取班次列表
const getList = async (message) => {
  let data = new FormData();
  if (searchInput.createTime == null) {
    searchInput.createTime = "";
  }
  data.set("name", searchInput.name);
  data.set("create_time", searchInput.createTime); //前面的key记得对应！
  data.set("page", currentPage.value);
  data.set("rows", pageSize.value); //前面的key记得对应！
  let res = await axios({
    method: "post",
    url: api.value + "/carBook/bclist.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  console.log(res);
  if (res.status == 200) {
    if (message) {
      ElMessage({
        type: "success",
        showClose: true,
        message: message,
        center: true,
      });
    }
    tableData.list = res.data.rows;
    tableData.list.forEach((item) => {
      if (item.state == 1) {
        item.states = true;
      } else if (item.state == 0) {
        item.states = false;
      }
    });
    // currentPage.value = res.data.currentPage;
    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 backClass = () => {
  addShow.value = true;
  getList();
};

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

// 重置搜索
const searchRefresh = lodash.debounce(async () => {
  searchInput.createTime = "";
  searchInput.name = "";
  currentPage.value = 1;
  getList();
}, 300);

// 表格页面启用班次开关
const startClasses = (row) => {
  ElMessageBox.confirm(`是否启用/取消 ${row.name} 班次`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row.states == true) {
        row.state = 1;
      } else if (row.states == false) {
        row.state = 0;
      }
      let data = {
        id: row.id,
        state: row.state,
      };
      let res = await axios({
        method: "post",
        url: api.value + "/carBook/bcupdatestate.action",
        headers: {
          "Content-Type": "application/json;charset=utf-8",
          token: sessionStorage.getItem("token"),
        },
        data: data,
      });
      console.log(res.data);
      if (res.data.code == 200) {
        getList();
        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: "已取消",
      });
      if (row.state == 0) {
        row.states = false;
      } else if (row.state == 1) {
        row.states = true;
      }
    });
};

//新增班次
const addClass = async () => {
  dialongTitle.value = "新增班次";
  busAddshow.value = true;
  ruleForm.name = "";
  ruleForm.ClassSwitch = false;
  ruleForm.createTime = [];
  ruleForm.id = "";
  tableData.buslist = [];
  addShow.value = false;
};

//编辑按钮
const edit = (row) => {
  console.log(row);
  dialongTitle.value = "编辑班次";
  busAddshow.value = false;
  ruleForm.createTime = row.work_duration.split("~");
  ruleForm.name = row.name;
  ruleForm.id = row.id;
  if (row.state == 1) {
    ruleForm.ClassSwitch = true;
  } else if (row.state == 0) {
    ruleForm.ClassSwitch = false;
  }
  addShow.value = false;
  getbusList();
};
// 班次详情按钮
const particulars = (row) => {
  console.log(row);
  dialongTitle.value = "班次详情";
  ruleForm.id = row.id;
  getbusList(100);
  particularsDialog.value = true;
};
// 取消班次详情
const particularsCancel = (row) => {
  particularsDialog.value = false;
};

// 取消添加班次
// const cancelAdd = () => {
//   addDialogVisible.value = false;
//   ruleFormRef.value.resetFields();
// };
// 确认添加班次
// const submitAdd = async (formEl) => {
//   if (!formEl) return;
//   await formEl.validate(async (valid, fields) => {
//     if (valid) {
//       if (dialongTitle.value == "新增班次") {
//         let data = {
//           name: ruleForm.name,
//           state: ruleForm.stateRadio,
//         };
//         // let res = await admin.adminAdd(data);
//         let res = await axios({
//           method: "post",
//           url: "/api/carBook/bcinsert.action",
//           headers: {
//             "Content-Type": "application/json;charset=utf-8",
//             token: sessionStorage.getItem("token"),
//           },
//           data: data,
//         });
//         // console.log(res, "添加账号");
//         if (res.data.code == 200) {
//           getList();
//           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("error submit!", fields);
//     }
//   });
// };

//删除按钮
const del = (row) => {
  ElMessageBox.confirm(`是否删除 ${row.name} 班次 ?`, "提示", {
    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/bcdel.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();
        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 getbusList = async (pageSize) => {
  let data = new FormData();
  if (searchInput.createTime == null) {
    searchInput.createTime = "";
  }
  data.set("b_id", ruleForm.id);
  data.set("page", currentPage2.value);
  if (pageSize) {
    data.set("rows", pageSize);
  } else {
    data.set("rows", pageSize2.value);
  }
  //前面的key记得对应！
  let res = await axios({
    method: "post",
    url: api.value + "/carBook/cclist.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  console.log(res, "车次");
  if (res.status == 200) {
    tableData.buslist = res.data.rows;
    if (res.data.rows == []) {
      tableData.buslist = [];
    } else {
      tableData.buslist.forEach((item) => {
        let weekarr = [];
        item.week.split(",").forEach((item) => {
          weekarr.push(checkweeks.value[item - 1]);
        });
        item.weekarr = weekarr.join(",");
      });
    }

    total2.value = res.data.total;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 在车次页面修改班次功能(保存按钮)
const busSave = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "新增班次") {
        let ClassSwitch = 0;
        if (ruleForm.ClassSwitch == true) {
          ClassSwitch = 1;
        } else if (ruleForm.ClassSwitch == false) {
          ClassSwitch = 0;
        }
        let time = ruleForm.createTime.join("~");
        let data = {
          name: ruleForm.name,
          work_duration: time,
          state: ClassSwitch,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/bcinsert.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        console.log(res.data);
        if (res.data.code == 200) {
          getList();
          busAddshow.value = false;

          // 保存成功后通过接口找到对象班次id
          let data = new FormData();
          data.set("name", ruleForm.name);
          // data.set("create_time", ruleForm.createTime); //前面的key记得对应！
          data.set("page", 1);
          data.set("rows", 10); //前面的key记得对应！
          let resId = await axios({
            method: "post",
            url: api.value + "/carBook/bclist.action",
            headers: {
              token: sessionStorage.getItem("token"),
            },
            data: data,
          });

          // console.log(resId, "班次id");
          if (resId.status == 200) {
            ruleForm.id = resId.data.rows[0].id;
            console.log(ruleForm.id);
          }
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        let ClassSwitch = 0;
        if (ruleForm.ClassSwitch == true) {
          ClassSwitch = 1;
        } else if (ruleForm.ClassSwitch == false) {
          ClassSwitch = 0;
        }
        let time = ruleForm.createTime.join("~");
        let data = {
          name: ruleForm.name,
          work_duration: time,
          state: ClassSwitch,
          id: ruleForm.id,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/bcupdate.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          // ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("错误提交", fields);
    }
  });
};
// 新增车次功能
const addbus = (row) => {
  busdialogTitle.value = "新增车次";
  ruleFormBus.id = "";
  busdialog.value = true;
  ruleFormBus.busnumber = "";
  ruleFormBus.contain = "";
  ruleFormBus.startTime = "";
  ruleFormBus.route = "";
  ruleFormBus.busterminus = "";
  ruleFormBus.yesterday = "";
  ruleFormBus.weeks = [];
  ruleFormBus.id = "";
  console.log(ruleForm.id);
};
// 编辑车次功能
const busedit = (row) => {
  console.log(row);
  let before_state = "";
  if (row.before_state == 1) {
    before_state = true;
  } else if (row.before_state == 0) {
    before_state = false;
  }
  let arr = JSON.parse(sessionStorage.getItem("route_endSelect"));
  route_endSelect.list = arr.filter((item) => {
    return item.route == row.route;
  });
  busdialogTitle.value = "编辑车次";
  ruleFormBus.busnumber = row.car_number;
  ruleFormBus.contain = row.contain;
  ruleFormBus.startTime = row.ci_time;
  ruleFormBus.route = row.route;
  ruleFormBus.busterminus = row.route_end;
  ruleFormBus.yesterday = before_state;
  ruleFormBus.weeks = row.weekarr.split(",");
  ruleFormBus.id = row.id;
  busdialog.value = true;
};
// 取消车次弹窗按钮
const cancelbus = () => {
  ruleFormRefBus.value.resetFields();
  busdialog.value = false;
};

// 确认车次添加车次
const submitAddBus = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (busdialogTitle.value == "新增车次") {
        let yesterday = 0;
        if (ruleFormBus.yesterday == true) {
          yesterday = 1;
        } else if (ruleFormBus.yesterday == false) {
          yesterday = 0;
        }
        let weekarr = [];
        checkweeks.value.forEach((item, index) => {
          ruleFormBus.weeks.forEach((i) => {
            if (item == i) {
              weekarr.push(index + 1);
            }
          });
        });

        let data = {
          car_number: ruleFormBus.busnumber,
          contain: ruleFormBus.contain,
          ci_time: ruleFormBus.startTime,
          route: ruleFormBus.route,
          route_end: ruleFormBus.busterminus,
          week: weekarr.join(","),
          before_state: yesterday,
          b_id: ruleForm.id,
        };
        // let res = await admin.adminAdd(data);
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/ccinsert.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        // console.log(res, "添加账号");
        if (res.data.code == 200) {
          getbusList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          busdialog.value = false;
          ruleFormRefBus.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        // 车次名称修改接口
        let yesterday = 0;
        if (ruleFormBus.yesterday == true) {
          yesterday = 1;
        } else if (ruleFormBus.yesterday == false) {
          yesterday = 0;
        }
        let weekarr = [];
        checkweeks.value.forEach((item, index) => {
          ruleFormBus.weeks.forEach((i) => {
            if (item == i) {
              weekarr.push(index + 1);
            }
          });
        });
        let data = {
          b_id: ruleForm.id,
          id: ruleFormBus.id,
          car_number: ruleFormBus.busnumber,
          contain: ruleFormBus.contain,
          ci_time: ruleFormBus.startTime,
          route: ruleFormBus.route,
          route_end: ruleFormBus.busterminus,
          week: weekarr.join(","),
          before_state: yesterday,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/carBook/ccupdate.action",
          headers: {
            "Content-Type": "application/json;charset=utf-8",
            token: sessionStorage.getItem("token"),
          },
          data: data,
        });
        if (res.data.code == 200) {
          getbusList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          busdialog.value = false;
          ruleFormRefBus.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 删除车次功能
const busdel = (row) => {
  ElMessageBox.confirm(`是否删除终点站为 ${row.route_end} 车次 ?`, "提示", {
    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/ccdel.action",
        headers: {
          token: sessionStorage.getItem("token"),
        },
        data: data,
      });
      if (res.data.code == 200) {
        if (tableData.buslist.length == 1 && currentPage2.value != 1) {
          currentPage2.value = currentPage2.value - 1;
        }
        if (tableData.buslist.length == 1) {
          let datas = {
            id: ruleForm.id,
            state: 0,
          };
          let resdata = await axios({
            method: "post",
            url: api.value + "/carBook/bcupdatestate.action",
            headers: {
              "Content-Type": "application/json;charset=utf-8",
              token: sessionStorage.getItem("token"),
            },
            data: datas,
          });
          console.log(resdata.data);
          if (resdata.data.code == 200) {
            ruleForm.ClassSwitch = false;
            // ElMessage({
            //   type: "success",
            //   showClose: true,
            //   message: res.data.message,
            //   center: true,
            // });
          } else {
            ElMessage({
              type: "error",
              showClose: true,
              message: resdata.data.message,
              center: true,
            });
          }
        }
        getbusList();
        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 importExcel = async () => {
  if (searchInput.createTime == null) {
    searchInput.createTime = "";
  }
  let data = new FormData();
  data.set("route", searchInput.route);
  data.set("start_time", searchInput.startTime);
  data.set("create_time", searchInput.createTime);
  let res = await axios({
    method: "post",
    url: api.value + "/carBook/bctoExcel.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  // console.log(res, "导出账号");
  if (res.data.code == 200) {
    const elt = document.createElement("a");
    elt.setAttribute(
      "href",
      "https://car.meiyishuoo.com/ride-sharing" + res.data.downurl
    );
    elt.setAttribute("download", "file.png");
    elt.style.display = "none";
    document.body.appendChild(elt);
    elt.click();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 表格斑马纹颜色修改
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();
};

const handleCurrentChange2 = (value) => {
  // console.log(value);
  currentPage2.value = value;
  getbusList();
};

onBeforeMount(() => {
  api.value = store.state.user.api;
  pathNum.list = JSON.parse(sessionStorage.getItem("pathSelect"));
  busNum.list = JSON.parse(sessionStorage.getItem("busSelect"));
  route_endSelect.list = JSON.parse(sessionStorage.getItem("route_endSelect"));
  getList();
});
onUnmounted(() => {});
</script>

<style scoped lang="scss">
.content-box {
  width: calc(100% - 40px);
  height: calc(100% - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;

  .left {
    width: calc(100% - 60px);
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: #000;
    font-size: 18px;
    font-weight: 600;
    .camera {
      margin-right: 15px;
      color: #4392f7;
    }
    .cameratxt {
      display: flex;
      align-items: center;
      cursor: pointer;
    }
    .busSave {
      background-color: rgba(61, 81, 232, 1);
      border: 1px solid rgba(61, 81, 232, 1);
      width: 80px;
    }
  }
  .middle {
    width: calc(100% - 60px);
    margin: 0 auto;

    color: #000;
    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin: 10px 0 0 0;
      .el-form-item {
        :deep(.el-input__suffix-inner) {
          color: rgba(61, 81, 232, 1);
        }
      }
      .search {
        margin-left: 0 !important;
      }
      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;
        :deep(.el-input .el-input__inner) {
          font-size: 16px;
        }
        span {
          margin: 0 10px 0 0;
        }
      }
    }
    .gongneng {
      margin: 10px 0;
    }
    :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;
    }
  }
  .footer {
    width: calc(100% - 60px);
    flex:1;
    margin: 10px auto 10px;
    overflow: auto;
    .el-table--fit {
      height: 100%;
      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;
        color: #000;
      }
      :deep(.el-table__row) {
        height: 50px;
        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(.busAdd) {
      //   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;
        .yesterday {
          .el-form-item__label {
            width: 150px !important;
          }
        }
        .el-form-item {
          .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__wrapper {
            width: 198px;
          }
        }

        .options {
          margin-left: 320px;
        }
      }
    }

    // 添加员工弹窗样式
    // :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-input {
    //       width: 200px;
    //     }
    //     .options {
    //       margin-left: 320px;
    //     }
    //   }
    // }
    :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;
        padding-bottom: 17px;
        .el-dialog__headerbtn {
          outline: none;
        }
      }
      .el-dialog__body {
        padding: 30px 20px 10px 20px;
        .el-input {
          width: 200px;
        }
        .options {
          margin-left: 120px;
        }
      }
    }
    :deep(.particulars) {
      .el-dialog__body {
        padding: 30px 20px 35px 20px;
      }
    }
  }
  .el-pagination {
    // width: 1600px;
    width: calc(100% - 60px);
    height: 60px;
    margin: 0 30px;
    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>
