<!--
 * @Author: your name
 * @Date: 2021-09-13 17:52:31
 * @LastEditTime: 2021-12-30 17:39:41
 * @LastEditors: Please set LastEditors
 * @Description: 生物安全 - 车辆管理
 * @FilePath: \hyyfClient\src\views\BioSafety\CarAdmin.vue
-->
<template>
  <div class="car-admin">
    <head-btns
      :btnNames="btnNames"
      :btnSelected="btnSelected"
      @btnSelected="getBtnSelected"
    >
    </head-btns>

    <!-- 筛选条件 -->
    <query-conditions
      v-if="btnSelected === 2 || btnSelected === 3 || btnSelected === 4"
      :formItems="formItems"
      :propFormData="propFormData"
      @getQueryParams="handleQuery"
    >
    </query-conditions>

    <!-- 表格 -->
    <new-table
      :title="title"
      :listData="listData"
      :tableItems="tableItems"
      :shows="tableShows"
      :height="600"
    >
      <template #right>
        <template v-if="btnSelected === 1">
          <el-button
            v-if="hasPerm('car:add')"
            size="mini"
            @click="add"
            type="primary"
          >
            新增车辆
          </el-button>
          <el-button
            v-if="hasPerm('car:white')"
            size="mini"
            @click="btnSelected = 5"
            type="success"
          >
            查看白名单
          </el-button>
          <el-button
            v-if="hasPerm('car:black')"
            size="mini"
            @click="btnSelected = 6"
            type="warning"
          >
            查看黑名单
          </el-button>
        </template>
        <template v-if="btnSelected === 5">
          <el-button size="mini" type="success" @click="addWhite(1)">
            添加白名单
          </el-button>
          <el-button size="mini" @click="btnSelected = 1" type="primary">
            查看车辆档案
          </el-button>
          <el-button size="mini" @click="btnSelected = 6" type="warning">
            查看黑名单
          </el-button>
        </template>
        <template v-if="btnSelected === 6">
          <el-button size="mini" type="success" @click="addWhite(2)">
            添加黑名单
          </el-button>
          <el-button size="mini" @click="btnSelected = 1" type="primary">
            查看车辆档案
          </el-button>
          <el-button size="mini" @click="btnSelected = 5" type="success">
            查看白名单
          </el-button>
        </template>
      </template>
      <!-- <template v-slot:right>
        <template>
        <div>共{{ total }}辆车</div>
        </template>
        <template v-else-if="btnSelected === 2">
          <div>
            <el-button size="mini">黑名单</el-button>
          </div>
        </template>
        <template v-else>
          <div>
            <el-button size="mini">黑名单</el-button>
          </div>
        </template>
      </template> -->
      <!--  白名单操作    -->
      <template #whiteHandle="scope">
        <el-button
          v-if="hasPerm('car:white-del')"
          size="mini"
          type="primary"
          @click="del(scope.row, 1)"
        >
          移出白名单
        </el-button>
      </template>
      <template #blackHandle="scope">
        <el-button
          v-if="hasPerm('car:black-del')"
          size="mini"
          type="primary"
          @click="del(scope.row, 2)"
        >
          移出黑名单
        </el-button>
      </template>
      <!--  车辆档案操作    -->
      <template #handle="scope">
        <!--        <el-button size="mini" type="success" @click="onJoin(scope.row, 1)">加入白名单</el-button>-->
        <!--        <el-button size="mini" type="warning" @click="onJoin(scope.row, 2)">加入黑名单</el-button>-->
        <el-button
          v-if="hasPerm('car:del')"
          size="mini"
          type="danger"
          @click="onJoin(scope.row, 3)"
        >
          删除
        </el-button>
      </template>
      <template v-slot:carNum="slotProps">
        {{ slotProps.row.carNum ? slotProps.row.carNum : "未识别" }}
      </template>
      <template #carHandle="scope">
        <el-button
          v-if="scope.row.carNum"
          size="mini"
          @click="addBase(scope.row.carNum)"
          >添加到车辆档案</el-button
        >
      </template>
      <template v-slot:originalPicPath="slotProps">
        <img
          :src="slotProps.row.originalPicPath"
          @click="clickImg(slotProps.row.originalPicPath)"
          alt="车辆通行"
          width="120"
        />
      </template>
      <template v-slot:alarmPicture="slotProps">
        <img
          :src="slotProps.row.alarmPicture"
          @click="clickImg(slotProps.row.alarmPicture)"
          alt="车辆通行"
          width="120"
        />
      </template>
      <template v-slot:handler="slotProps">
        <el-button size="mini" @click="clickEvent(slotProps.row)">
          查看回放
        </el-button>
      </template>

      <!-- 车辆烘干 -->
      <template #chekOk="scope">
        <span>{{ scope.row.chekOk === "1" ? "是" : "否" }}</span>
      </template>
      <template #handlerDrying="slotProps">
        <el-button size="mini" @click="clickDryingEvent(slotProps.row)">
          查看本次烘干温度详情
        </el-button>
      </template>
    </new-table>
    <table-footer
      :totals="total"
      :size="size"
      @sizeChange="sizeChange"
      @pageChange="pageChange"
    >
    </table-footer>
    <el-dialog :title="'车辆档案新增'" :visible.sync="isFile" width="50%">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item prop="carId" label="车辆编号" v-if="showType">
          <el-input v-model="form.carId" disabled></el-input>
        </el-form-item>
        <el-form-item prop="carNum" label="车牌号">
          <el-input v-model="form.carNum"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <el-dialog title="车辆图片" :visible.sync="dialogVisible" width="50%">
      <img :src="imgUrl" alt="车辆通行" width="100%" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <el-dialog title="回放视频" :visible.sync="videoVisible" width="50%">
      <div style="width: 100%; height: 600px">
        <iframe
          v-if="videoVisible"
          :src="'static/dahua/index.html?' + rtsp"
          frameborder="0"
          style="width: 100%; height: 100%"
        >
        </iframe>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="videoVisible = false">取 消</el-button>
        <el-button type="primary" @click="videoVisible = false">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog title="温度详情" :visible.sync="tempVisible" width="80%">
      <div style="width: 100%; height: 500px">
        <chart-car-drying :tempList="tempChartData"></chart-car-drying>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="tempVisible = false">取 消</el-button>
        <el-button type="primary" @click="tempVisible = false">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="showType ? '添加黑名单' : '添加白名单'"
      :visible.sync="isWhite"
      width="50%"
    >
      <new-table
        :title="''"
        :listData="abList"
        :tableItems="abItems"
        :shows="abShows"
        @selectionChange="selectionChange"
      ></new-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isWhite = false">取 消</el-button>
        <el-button type="primary" @click="clickCar">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import HeadBtns from "components/bioSafety/Btns";
import QueryConditions from "components/bioSafety/QueryConditions";
import NewTable from "components/newTable/NewTable";
import TableFooter from "../../components/TableFooter";
import ChartCarDrying from "./chart/ChartCarDrying.vue";

import { formItems, propFormData } from "./carAdmin/queryCondition.config";
import { titles, tableItems, tableShows } from "./carAdmin/table.config";

import {
  getCarPassage,
  getCarWash,
  getCarWashTotal,
  getCarWashVideo,
  getCarDrying,
  getCarDryingTemp,
  getCarList,
  addCarWhite,
  addCarBlack,
  showCarWhite,
  addCarBase,
  showCarBlack,
  delCarWhite,
  delCarBlack,
  delCarBase,
  addWandB,
} from "../../utils/chenApi";
import { timeDate } from "../../utils/index";
import { mapState } from "vuex";

export default {
  name: "CarAdmin",
  components: {
    HeadBtns,
    QueryConditions,
    NewTable,
    TableFooter,
    ChartCarDrying,
  },
  computed: {
    ...mapState(["ip"]),
  },
  data() {
    return {
      btnNames: [
        // 按钮情况
        { id: 1, name: "车辆档案" },
        { id: 2, name: "车辆通行" },
        { id: 3, name: "车辆洗消" },
        { id: 4, name: "车辆烘干" },
      ],
      btnSelected: 1, // 选中的按钮
      formItems: [], // 传给 QueryCondition 组件的 formItems
      propFormData: {}, // 传给 QueryCondition 组件的 propFormData
      title: "", // 传给 BioTable 组件的 title
      listData: [], // 传给 BioTable 组件的表格展示的值 listData
      tableItems: [], // 传给 BioTable 组件的表格的列表 tableItems
      tableShows: {},
      // table的翻页
      total: 0,
      size: 20,
      pageNum: 1,
      selectId: "",
      params: {},
      dialogVisible: false,
      imgUrl: "", // 点击图片后放大的图片路径
      videoVisible: false, // 车辆回放
      rtsp: "", // 车辆回放的地址
      tempVisible: false, // 车辆烘干 - 查看温度详情
      tempChartData: {},
      isFile: false,
      form: {
        carId: "",
        carNum: "",
      },
      rules: {
        carId: [{ required: true, message: "请输入车辆编号", trigger: "blur" }],
        carNum: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
      },
      showType: false,
      isWhite: false,
      // 白黑名单
      abList: [],
      abItems: [
        {
          prop: "carId",
          label: "车辆编号",
          minWidth: "120",
          slotName: "carId",
        },
        {
          prop: "carNum",
          label: "车牌号",
          minWidth: "120",
          slotName: "carNum",
        },
      ],
      abShows: {
        showIndex: false,
        showSelect: true,
      },
      selectList: [],
    };
  },
  watch: {
    btnSelected: {
      handler(newVal) {
        const loading = this.$loading({
          lock: true,
          text: "加载中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.pageNum = 1;
        this.listData = [];
        if (newVal > 1) {
          this.formItems = formItems[this.btnSelected - 2];
          this.propFormData = propFormData[this.btnSelected - 2];
        } else {
          this.formItems = {};
          this.propFormData = {};
        }
        this.title = titles[this.btnSelected - 1];
        this.tableItems = tableItems[this.btnSelected - 1];
        this.getPageFn(newVal).forEach(async (fn) => {
          await fn();
        });
        // if (newVal === 1) {
        //   // 档案
        //   await this.getCarList();
        // } else if (newVal === 2) {
        //   // 车辆通行
        //   await this.carPassage();
        // } else if (newVal === 3) {
        //   // 车辆洗消
        //   await this.carWash();
        // } else if (newVal === 4) {
        //   // 车辆烘干
        //   await this.carDrying();
        // } else if (newVal === 5) {
        //   // 白名单
        //   await this.ShowCarWhite();
        // } else {
        //   // 黑名单
        //   await this.ShowCarBlack();
        // }
        loading.close();
      },
    },
  },
  mounted() {
    this.formItems = formItems[this.btnSelected - 1];
    this.propFormData = propFormData[this.btnSelected - 1];
    this.title = titles[this.btnSelected - 1];
    this.tableItems = tableItems[this.btnSelected - 1];
    this.tableShows = tableShows;
    // 档案
    this.getCarList();
  },
  methods: {
    getBtnSelected(id) {
      this.btnSelected = id;
    },
    // 获取当前操作对应的页面请求
    getPageFn(newVal) {
      const fns = {
        1: [this.getCarList], // 档案
        2: [this.carPassage], // 车辆通行
        3: [this.carWash, this.carWashTotal], // 车辆洗消
        4: [this.carDrying], // 车辆烘干
        5: [this.ShowCarWhite], // 白名单
        6: [this.ShowCarBlack], // 黑名单
      };
      return fns[newVal];
    },
    // 获取查询条件
    handleQuery(params) {
      this.pageNum = 1;
      this.params = params;
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.listData = [];
      this.getPageFn(this.btnSelected).forEach(async (fn) => {
        await fn();
      });
      loading.close();
    },
    // 修改size
    async sizeChange(val) {
      this.size = val;
      this.pageNum = 1;
      this.listData = [];
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      await this.getPageFn(this.btnSelected)[0]();
      loading.close();
    },
    // 修改页数
    async pageChange(val) {
      this.pageNum = val;
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      await this.getPageFn(this.btnSelected)[0]();
      loading.close();
    },
    // 车辆通行 查询
    carPassage() {
      let queryParams = {
        pageNum: this.pageNum,
        pageSize: this.size,
        carNum: this.params.name || undefined,
      };
      getCarPassage(queryParams).then((res) => {
        const result = JSON.parse(res.result);
        this.listData = result.data.pageData;
        this.listData.forEach((item) => {
          item.originalPicPath = `${this.ip}/video/picture/get?fileUrl=${item.originalPicPath}`;
          item.devChnName = item.devChnName.split("_")[0];
        });
        this.total = parseInt(result.data.totalRows);
      });
    },
    // 点击图片放大
    clickImg(url) {
      this.dialogVisible = true;
      this.imgUrl = url;
    },
    // 车辆档案
    getCarList() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.size,
      };
      getCarList(params).then((res) => {
        if (res.code == 200) {
          const result = JSON.parse(res.result);
          this.total = parseInt(result.data.totalRows);
          this.listData = result.data.pageData;
        }
      });
    },
    // 档案操作
    onJoin(row, num) {
      if (num === 1) {
        addCarWhite({ carId: row.carId }).then((res) => {
          if (res.code == 200) {
            this.$message.success("加入白名单成功");
            this.getCarList();
          } else {
            this.$message.error(res.errMsg);
          }
        });
      } else if (num === 2) {
        addCarBlack({ carId: row.carId }).then((res) => {
          if (res.code == 200) {
            this.$message.success("加入黑名单成功");
            this.getCarList();
          } else {
            this.$message.error(res.errMsg);
          }
        });
      } else if (num === 3) {
        // 删除
        let params = {
          carIdList: [row.carId],
        };
        delCarBase(params).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.getCarList();
          } else {
            this.$message.error(res.errMsg);
          }
        });
      }
    },
    // 新增车辆
    add() {
      this.isFile = true;
      this.showType = false;
    },

    // 添加白名单
    addWhite(num) {
      this.isWhite = true;
      let params = {
        pageNum: 1,
        pageSize: 200,
      };
      if (num === 1) {
        params.draw = 4;
        this.showType = false;
      } else {
        this.showType = true;
        params.draw = 5;
      }
      addWandB(params).then((res) => {
        if (res.code == 200) {
          const result = JSON.parse(res.result);
          this.abList = result.data.pageData;
        } else {
          this.$message.error(res.errMsg);
        }
      });
    },
    clickCar() {
      if (this.selectList.length > 0) {
        let params = {};
        let arr = [];
        this.selectList.forEach((item) => {
          arr.push(item.carId);
        });
        params.carIdList = arr;
        if (this.showType) {
          // 黑名单
          addCarBlack(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功!");
              this.ShowCarBlack();
            } else {
              this.$message.error(res.errMsg);
            }
            this.isWhite = false;
          });
        } else {
          addCarWhite(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功!");
              this.ShowCarWhite();
            } else {
              this.$message.error(res.errMsg);
            }
            this.isWhite = false;
          });
        }
      } else {
        this.$message.error("请选择要添加的车辆！");
      }
    },
    // 选择
    selectionChange(item) {
      this.selectList = item;
    },
    // 档案编辑
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.showType) {
            // 编辑
          } else {
            let params = {
              carNum: this.form.carNum,
            };
            addCarBase(params).then((res) => {
              if (res.code == 200) {
                this.reset();
                this.$message.success("添加成功");
                this.getCarList();
              } else {
                this.$message.error(res.errMsg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 重置
    reset() {
      this.isFile = false;
      this.showType = false;
      this.form = {
        carNum: "",
        carId: "",
      };
    },
    // 白名单列表
    ShowCarWhite() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.size,
      };
      showCarWhite(params).then((res) => {
        if (res.code == 200) {
          const result = JSON.parse(res.result);
          this.total = parseInt(result.data.totalRows);
          this.listData = result.data.pageData;
        }
      });
    },
    // 黑名单列表
    ShowCarBlack() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.size,
      };
      showCarBlack(params).then((res) => {
        if (res.code == 200) {
          const result = JSON.parse(res.result);
          this.total = parseInt(result.data.totalRows);
          this.listData = result.data.pageData;
        } else {
          this.$message.error(res.errMsg);
        }
      });
    },
    // 移除黑白名单
    del(row, num) {
      let params = {
        carIdList: [row.carId],
      };
      if (num === 1) {
        delCarWhite(params).then((res) => {
          if (res.code == 200) {
            this.$message.success("移出白名单成功！");
            this.ShowCarWhite();
          } else {
            this.$message.error(res.errMsg);
          }
        });
      } else {
        delCarBlack(params).then((res) => {
          if (res.code == 200) {
            this.$message.success("移出黑名单成功！");
            this.ShowCarBlack();
          } else {
            this.$message.error(res.errMsg);
          }
        });
      }
    },
    // 车辆通行添加到车辆档案
    addBase(id) {
      let params = {
        carNum: id,
      };
      addCarBase(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("添加成功！");
        } else {
          this.$message.error(res.errMsg);
        }
      });
    },
    // 车辆洗消
    carWash() {
      if (!this.params.time) {
        this.params.time = [
          timeDate(new Date().getTime()),
          timeDate(new Date().getTime()),
        ];
      }
      let queryParams = {
        pageNum: this.pageNum,
        pageSize: this.size,
        alarmStartDateString: this.params.time[0] + " 00:00:00",
        alarmEndDateString: this.params.time[1] + " 23:59:59",
        nodeCodeList: ["1002871$1$0$0", "1002872$1$0$0", "1002873$1$0$0"],
        deviceCategory: 1,
        alarmType: 303,
        dbType: 0,
      };
      getCarWash(queryParams).then(async (res) => {
        const result = JSON.parse(res.result);
        this.listData = result.data.pageData;
        this.listData.forEach((item) => {
          item.alarmPicture = `${this.ip}/video/picture/get?alarmPicture=${item.alarmPicture}`;
        });
      });
    },
    // 车辆洗消 - 按钮
    clickEvent(row) {
      getCarWashVideo({
        happendTime: row.alarmDate,
        channelName: row.alarmPosition,
      }).then((res) => {
        if (res.code === 0) {
          this.rtsp = res.URL;
          this.videoVisible = true;
        }
      });
    },
    // 车辆洗消 - 总条数
    carWashTotal() {
      if (!this.params.time) {
        this.params.time = [
          timeDate(new Date().getTime()),
          timeDate(new Date().getTime()),
        ];
      }
      let queryParams = {
        orgCodeList: [],
        nodeCodeList: ["1002871$1$0$0", "1002872$1$0$0", "1002873$1$0$0"],
        deviceCategory: 1,
        alarmStartDateString: this.params.time[0] + " 00:00:00",
        alarmEndDateString: this.params.time[1] + " 23:59:59",
        alarmType: 303,
        dbType: 0,
      };
      getCarWashTotal(queryParams).then((res) => {
        this.total = JSON.parse(res.result).data.value;
      });
    },
    // 车辆烘干
    carDrying() {
      if (!this.params.time) {
        this.params.time = [
          timeDate(new Date().getTime() - 1000 * 60 * 60 * 24 * 3),
          timeDate(new Date().getTime()),
        ];
      }
      getCarDrying({
        startTimeString: this.params.time[0] + " 00:00:00",
        endTimeString: this.params.time[1] + " 23:59:59",
        current: this.pageNum,
        size: this.size,
      }).then((res) => {
        if (res && res.code === 10000) {
          this.listData = res.data.records;
          this.total = res.data.total;
        }
      });
    },
    // 车辆烘干的回放事件
    clickDryingEvent(row) {
      getCarDryingTemp({
        deviceId: row.deviceId,
        eventTimeString: row.eventTime,
      }).then((res) => {
        if (res.code === 10000) {
          this.tempChartData = res.data;
          this.tempVisible = true;
        }
      });
    },
  },
};
</script>

<style scoped>
.car-admin {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
}
</style>
