<template>
  <div class="newFlightView">
    <div class="newFlightView-left">
      <div class="newFlightView-left-top">
        <div class="newFlightView-left-top-top">
          <div class="newFlightView-left-top-top-title flex-wrap">
            <div class="newFlightView-left-top-top-title-info">
              航班基本信息
            </div>
            <div class="newFlightView-left-top-top-title-no">
              {{ flightObj.carrierFlights }}
            </div>
          </div>
          <div class="newFlightView-left-top-top-status">
            <el-scrollbar style="height: 100%">
              <el-checkbox-group @change="checkChange" class="flex-wrap" v-model="checkList">
                <Item v-for="(item, index) in checkStates" :key="index" :total="checkStates" :index="index + 1" :item="item" />
              </el-checkbox-group>
            </el-scrollbar>
          </div>
        </div>
        <div class="newFlightView-left-top-list">
          <el-descriptions :column="2">
            <el-descriptions-item label="起飞机场简称">{{
              infoObj.takeoff_airport_name
            }}</el-descriptions-item>
            <el-descriptions-item label="起飞机场三字码">{{
              infoObj.outAirport
            }}</el-descriptions-item>
            <el-descriptions-item label="登机口">{{
              infoObj.gateCd
            }}</el-descriptions-item>
            <el-descriptions-item label="停机位">
              {{ infoObj.depstandCd }}</el-descriptions-item>
            <el-descriptions-item :span="2" label="计划起飞时间">{{
              formatTime(infoObj.scheduleTakeOffTime)
            }}</el-descriptions-item>
            <el-descriptions-item :span="2" label="实际起飞时间">{{
              formatTime(infoObj.actualTakeOffTime)
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="newFlightView-left-top-list">
          <el-descriptions :column="2">
            <el-descriptions-item label="降落机场简称">{{
              infoObj.target_airport_name
            }}</el-descriptions-item>
            <el-descriptions-item label="降落机场三字码">{{
              infoObj.landAirport
            }}</el-descriptions-item>
            <el-descriptions-item label="提取转盘">{{
              infoObj.arrcarouselCd
            }}</el-descriptions-item>
            <el-descriptions-item label="停机位">
              {{ infoObj.arrstandCd }}</el-descriptions-item>
            <el-descriptions-item :span="2" label="计划降落时间">{{
              formatTime(infoObj.scheduleLandInTime)
            }}</el-descriptions-item>
            <el-descriptions-item :span="2" label="实际降落时间">{{
              formatTime(infoObj.actualLandInTime)
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="newFlightView-left-top-list">
          <el-descriptions :column="2">
            <el-descriptions-item label="航班状态">{{
              infoObj.normalState
            }}</el-descriptions-item>
            <el-descriptions-item label="托运旅客数">{{
              infoObj.checked_passengers_number
            }}</el-descriptions-item>
            <el-descriptions-item label="中转进行李数">{{
              infoObj.transfer_baggage_number
            }}</el-descriptions-item>
            <el-descriptions-item label="终点行李数">{{
              infoObj.destination_bags_number
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div class="newFlightView-left-bottom">
        <Table :tableTag="table1" tableName="容器列表" />
      </div>
    </div>
    <div class="newFlightView-right">
      <div class="newFlightView-right-top flex">
        <div class="newFlightView-right-top-left flex-wrap">
          <div class="manageTitle">航班行李列表</div>
          <div class="newFlightView-right-top-left-select">
            快捷筛选
            <el-cascader v-model="selectedFilter" :options="fastFilterOptions" :props="{ expandTrigger: 'hover', checkStrictly: true }" size="small" placeholder="无" clearable />
          </div>
        </div>
        <div class="newFlightView-right-top-right">
          <!-- <TimeZoneSelector /> -->
          <img class="btn-img btn-shadow" src="@/assets/baggage/ic_export.png" title="导出" @click="exportHandler('table', '航班行李列表')" />
        </div>
      </div>
      <div class="newFlightView-right-bottom">
        <Table :tableTag="table2" ref="table" :fast-filter="fastFilter" :btnStyle="{ top: '-52px' }" :istableCol="true" tableName="航班行李列表" :pageSize="999" @tableLoad="tableLoad" />
      </div>
    </div>
  </div>
</template>

<script>
import Table from "@/views/newQuery/components/table.vue";
import TimeZoneSelector from "@/components/TimeZoneSelector";
import { exportToExcel } from "@/utils/table";
import { combine } from "@/utils";
import pf from "@/layout/mixin/publicFunc";
import Item from "./item.vue";
export default {
  components: { Table, TimeZoneSelector, Item },
  mixins: [pf],
  data () {
    return {
      radio: "1",
      options: [],
      value: "",
      dataContent: {},
      flightObj: {},
      infoObj: {},
      checkList: [],
      checkStates: [],
      table1: {},
      table2: {},
      showObj: {},
      deArrs: [],
      deArrsNum: [],
      fastFilterOptions: [
        {
          label: "中转进航班",
          value: "inflightNo",
          children: [],
        },
        {
          label: "中转出航班",
          value: "transferFlightNO",
          children: [],
        },
      ],
      selectedFilter: [],
      viewClassName: [
        {
          label: "值机",
          value: "check_in_baggage_number",
        },
        {
          label: "未激活",
          value: "NO_activate_number",
        },
        {
          label: "预计装载",
          value: "estimated_load_number",
        },
        {
          label: "安检",
          value: "screened_number",
        },
        {
          label: "分拣",
          value: "sorted_number",
        },
        {
          label: "装车",
          value: "loaded_number",
        },
        {
          label: "装机",
          value: "onaiecraft_number",
        },
        {
          label: "待翻检",
          value: "NO_check_number",
        },
        {
          label: "已翻减",
          value: "checked_number",
        },
        {
          label: "取消托运",
          value: "cancel_consignment_number",
        },
        {
          label: "无bsm",
          value: "NO_BSM_number",
        },
        {
          label: "中转行李",
          value: "transfer_baggage_number",
        },
      ],
    };
  },
  computed: {
    fastFilter () {
      const [key, value] = this.selectedFilter;
      // console.log(this.selectedFilter)
      if (!key) {
        return () => true;
      }
      return (row) => {
        switch (key) {
          case "inflightNo":
          case "transferFlightNO":
            return value ? row[key] === value : (row[key] ?? "") !== "";
          case "check_in_baggage_number":
            return row["No_BSM"] != 1;
          case "NO_activate_number":
            return row["activeState"] == 1;
          case "estimated_load_number":
            return row["dataState"] != "DEL" && row["activeState"] != 1;
          case "screened_number":
            return row["securityInspectionResults"];
          case "sorted_number":
            return row["sorting_time"];
          case "loaded_number":
            return (
              row["loading_time"] &&
              (row["abnormalType"] == "OFF" || !row["abnormalType"])
            );
          case "onaiecraft_number":
            return row["installation_time"];
          case "NO_check_number":
            return (
              row["dataState"] == "DEL" &&
              row["loading_time"] &&
              (row["abnormalType"] != "OFF" || !row["abnormalType"])
            );
          case "checked_number":
            return row["dataState"] == "DEL" && row["abnormalType"] == "OFF";
          case "cancel_consignment_number":
            return row["dataState"] == "DEL";
          case "NO_BSM_number":
            return row["No_BSM"] == 1;
          case "transfer_baggage_number":
            return row["inflightNo"] && row["dataState"] != "DEL";
          default:
            return (row[key] ?? "") !== "";
        }
      };
    },
  },
  async created () {
    const checkDatas = [];
    const query = this.$route.query;
    const np = [
      {
        k1: "inflightNo",
        k2: "inflightDate",
      },
      {
        k1: "transferFlightNO",
        k2: "outflightDate",
      },
      {
        k1: "Inbound_flight_number",
        k2: "Inbound_flight_date",
      },
      {
        k1: "departure_flights_number",
        k2: "departure_flights_date",
      },
    ];
    const nq = this.formatParams(np, { ...query });
    const filterMap = {
      Inbound_flight_number: "inflightNo",
      departure_flights_number: "transferFlightNO",
    };
    Object.entries(nq).forEach(([key, value]) => {
      if (
        ![
          "carrierFlights",
          "carrierFlightsDate",
          "outAirport",
          "landAirport",
        ].includes(key)
      ) {
        if (filterMap[key]) {
          this.selectedFilter = [filterMap[key], value];
        }
        delete nq[key];
      }
    });
    let tableKey = null;
    Object.keys({ ...query }).forEach((key) => {
      const findKey = this.viewClassName.filter((item) => item.value === key);
      if (findKey?.length) {
        tableKey = [...findKey];
      }
    });
    if (tableKey?.length) {
      const { value } = tableKey[0];
      this.selectedFilter = [value];
    }
    const { carrierFlights, carrierFlightsDate } = nq;
    this.flightObj = nq;
    this.dataContent = nq;
    const res = await this.getViewInfo(nq);
    this.infoObj = res[0];
    const sts = await this.getViewInfo({ carrierFlights, carrierFlightsDate })
    if (sts && sts.length) {
      for (const p of sts) {
        const { outAirport, landAirport } = p;
        if (
          outAirport &&
          outAirport != "" &&
          landAirport &&
          landAirport != ""
        ) {
          this.deArrs.push({
            outAirport,
            landAirport,
          });
        }
      }
      console.log(this.deArrs)
    }
    const newDatas = _.cloneDeep(this.deArrs);
    if (newDatas && newDatas.length) {
      const m = combine(newDatas, "outAirport", "landAirport");
      m.forEach((item, index) => {
        checkDatas.push(`${m[index]}-${m[index + 1]}`);
        const obj = {
          item,
          index,
        };
        this.deArrsNum.push(obj);
      });
      this.checkStates = m;
      const [a1, a2] = [m[0], m[m.length - 1]];
      const { outAirport, landAirport } = this.infoObj;
      if (a1 == outAirport && a2 == landAirport) {
        this.checkList = checkDatas.splice(0, m.length - 1);
      } else {
        this.checkList = [`${outAirport}-${landAirport}`];
      }
    }
  },
  mounted () {
    this.table1 = this.dataContent;
    this.table2 = this.dataContent;
  },
  methods: {
    //格式化参数-航班号
    formatParams (arr = [], query = {}) {
      if (arr && arr.length) {
        for (let index = 0; index < arr.length; index++) {
          const { k1, k2 } = arr[index];
          if (query[k2]) {
            query.carrierFlights = query[k1];
            query.carrierFlightsDate = query[k2];
            delete query[k1];
            delete query[k2];
          }
        }
      }
      return query;
    },
    // 获取基本信息
    async getViewInfo (dataContent = this.dataContent) {
      const { code, returnData } = await this.getQueryList(
        SERVICE_ID.bagViewId,
        dataContent
      );
      if (code == 0) {
        return returnData;
      } else {
        return [];
      }
    },
    // 显示日期
    formatTime (datetime) {
      return datetime?.replace("T", " ") ?? "";
    },
    // 导出
    exportHandler (refName, tableName) {
      const { carrierFlights, carrierFlightsDate, outAirport, landAirport } =
        this.flightObj;
      const table = this.$refs[refName].$el.cloneNode(true);
      const fileName = `${tableName}-${carrierFlights}-${carrierFlightsDate}-${outAirport}-${landAirport}.xlsx`;
      exportToExcel(table, tableName, fileName);
    },
    // 选中
    async checkChange (arr) {
      const datas = [];
      const result = [...arr];
      if (result && result.length) {
        const c1 = result.join("-");
        const c2 = c1.split("-");
        const c3 = _.uniq(c2);
        this.deArrsNum.forEach((item) => {
          c3.forEach((p) => {
            if (item.item == p) {
              const obj = {
                name: item.item,
                index: item.index,
              };
              datas.push(obj);
            }
          });
        });
        const caps = datas.sort((a, b) => a.index - b.index);
        const c4 = caps[0].name; //起飞
        const c5 = caps[caps.length - 1].name; //降落
        const newPrams = _.cloneDeep(this.dataContent);
        newPrams.outAirport = c4;
        newPrams.landAirport = c5;
        this.table1 = newPrams;
        this.table2 = newPrams;
        const res = await this.getViewInfo(newPrams);
        if (res && res.length) {
          this.infoObj = res[0];
        }
      }
    },
    // 获取行李列表后设置快捷筛选
    tableLoad (tableData) {
      this.setFastFilterOptions(tableData);
    },
    setFastFilterOptions (tableData) {
      const viewDatas = [];
      const inFlightNOList = new Set();
      const transferFlightNOList = new Set();
      tableData.forEach((item) => {
        item["inflightNo"] && inFlightNOList.add(item["inflightNo"]);
        item["transferFlightNO"] &&
          transferFlightNOList.add(item["transferFlightNO"]);
      });
      this.fastFilterOptions.splice(
        this.fastFilterOptions.length - 2,
        2,
        {
          label: "中转进航班",
          value: "inflightNo",
          children: [...inFlightNOList].map((value) => ({
            label: value,
            value,
          })),
        },
        {
          label: "中转出航班",
          value: "transferFlightNO",
          children: [...transferFlightNOList].map((value) => ({
            label: value,
            value,
          })),
        }
      );
      this.viewClassName.forEach((item) => {
        viewDatas.push({
          label: item.label,
          value: item.value,
        });
      });
      this.fastFilterOptions = this.fastFilterOptions.concat(viewDatas);
    },
  },
};
</script>

<style lang="scss" scoped>
.newFlightView {
  height: calc(100vh - 80px);
  padding: 8px;
  display: flex;
  flex-wrap: wrap;
  &-left {
    width: 408px;
    margin-right: 8px;
    &-top {
      height: 575px;
      background-color: #fff;
      &-top {
        padding: 25px 16px;
        border-bottom: 1px solid #c8cfdb;
        &-title {
          line-height: 23px;
          font-size: 20px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: #101116;
          margin-bottom: 25px;
          &-info {
            margin-right: 16px;
          }
        }
        &-status {
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: #101116;
          ::v-deep .el-checkbox-group {
            font-size: initial;
            .el-checkbox__inner {
              border-radius: 50%;
            }
            .el-checkbox__label {
              display: none;
            }
          }
        }
      }
      &-list {
        padding: 25px 16px 13px 16px;
        border-bottom: 1px solid #c8cfdb;
        &:last-child {
          border-bottom: none;
        }
      }
    }
    &-bottom {
      height: calc(100% - 575px - 10px);
      margin-top: 8px;
    }
  }
  &-right {
    flex: 1;
    height: 100%;
    width: calc(100% - 416px);
    &-top {
      padding: 18px 0;
      &-left {
        line-height: 30px;
      }
      &-right {
        padding-right: 70px;
        .btn-img {
          margin-left: 10px;
        }
      }
    }
    &-bottom {
      height: calc(100% - 68px);
    }
  }
}
</style>
