<template>

  <div>
    <div ref="lxHeader">
      <LxHeader
        icon="md-apps"
        :text="$route.meta.title"
        style="margin-bottom: 10px; border: 0px; margin-top: 15px"
      >
        <div slot="content"></div>
        <slot>
          <header-content :auths="auths_auth_mixin">
            <template #search>
              <div style="display: flex">
                <el-date-picker v-model="weekSelect" format="yyyy 第 WW 周" type="week" size="small" style="width: 150px;"></el-date-picker>
                <Select clearable v-model="selectArea" placeholder="请选择范围" style="width: 140px;margin-left: 6px;">
                  <Option v-for="item in Array.from(areas)" :value="item[0]">{{ item[1] }}</Option>
                </Select>
                <Button
                  style="margin-left: 10px"
                  type="primary"
                  @click="getData"
                >查询</Button
                >
              </div>
            </template>
            <template #export>
              <Button
                type="primary"
                @click="exportExcel(new Date().getTime().toString())"
              >导出</Button
              >
            </template>
          </header-content>
        </slot>
      </LxHeader>
    </div>

    <el-row :gutter="10">
      <el-col :span="4">
        <el-tree :data="equipments"
                 node-key="id"
                 :style="{ 'max-height':  (tableHeight || 630) + 'px', 'overflow': 'scroll' }"
                 ref="elTree"
                 :props="{ children: 'children', label: 'name' }"
                 show-checkbox
                 @check="handleCheckChange">
        </el-tree>
      </el-col>
      <el-col :span="20">
        <el-table :data="tableData" :span-method="objectSpanMethod" style="width: 100%" stripe :height="tableHeight">
          <el-table-column type="index" label="序号" width="50" header-align="center" align="center" fixed="left">
          </el-table-column>

          <el-table-column prop="equipment.area"
                           label="所属区域"
                           header-align="center"
                           width="100"
                           fixed="left"
                           align="center" :formatter="(row, column, cellValue) => (areas.get(cellValue))">
          </el-table-column>
          <el-table-column prop="equipment.name" label="控制工程名称" header-align="center" width="150" fixed="left">
          </el-table-column>
          <el-table-column prop="unit" label="管理单位" header-align="center" width="150" fixed="left">
            <template>
              <span>河道处</span>
            </template>
          </el-table-column>
          <!--      <el-table-column prop="gate" label="闸门（孔×米）" header-align="center" width="150" fixed="left">-->
          <!--        <template>-->
          <!--          <span>14m</span>-->
          <!--        </template>-->
          <!--      </el-table-column>-->
          <!--      <el-table-column prop="gm" label="泵站规模（台×m3/s）" header-align="center" width="150" fixed="left">-->
          <!--        <template>-->
          <!--          <span>3×5m3/s</span>-->
          <!--        </template>-->
          <!--      </el-table-column>-->
          <el-table-column :label="weekRange[i]" header-align="center" v-for="(n,i) in 6">
            <el-table-column prop="x1" :label="weekName[i]" min-width="220" header-align="center">
              <template #default="{ row }">
                <div>
                  <p v-for="item in row._sortData[i]">
                    {{ $moment(item.act_start_time).format('HH:mm') }} ~ {{ $moment(item.act_end_time).format('HH:mm') }}
                    {{ item.content }}
                    {{ abilities.get(item.leibie) }}
                  </p>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import { index } from "@/api/system/baseForm"
  import {
    mergeTableRow
  } from "@/utils/mergeTableRow"
  import { show } from "@/api/system/customFormField";
  import headerContent from "@/components/LxHeader/XyContent.vue";
  import { authMixin } from "@/mixin/authMixin";
  import LxHeader from "@/components/LxHeader";
  import {AlignmentType, convertInchesToTwip, Document, HeadingLevel, Packer, Paragraph, TextRun} from "docx";
  import * as XLSX from "xlsx";
  import { saveAs } from "file-saver";
  export default {
    mixins: [authMixin],
    components: {
      headerContent,
      LxHeader
    },
    data() {
      return {
        selectArea: "",
        weekSelect: new Date(),
        tableHeight: '600px',
        abilities: new Map(),
        areas: new Map(),
        equipments: [],
        tableData: [],
        list: [],
        equipmentIds: [],
        weekRange: [],
        weekName: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
      }
    },
    methods: {
      handleCheckChange (data, checked, indeterminate) {
        this.treeValue = this.$refs['elTree'].getCheckedNodes(true)?.filter(i => !i.children)?.map(i => i.name).toString()
        this.equipmentIds = this.$refs['elTree'].getCheckedNodes(true)?.filter(i => !i.children)?.map(i => i.id)

        this.getData()
      },

      async getEquipments () {
        const res = (await index({
          table_name: 'equipments',
          page: 1,
          page_size: 9999
        },false))?.data || []
        this.equipments = Array.from(this.areas).map(i => ({
          id: `area_${i[0]}`,
          name: i[1],
          children: res.filter(j => j.area === i[0])
        }))

        this.$nextTick(() => {
          Array.from(this.areas).forEach(i => {
            this.$refs['elTree'].setChecked(`area_${i[0]}`, true, true)
          })
        })
      },

      async getArea() {
        const obj = (await show({ id: 4 }, false))?.select_item;
        if (obj && typeof obj === "object") {
          let keys = Object.keys(obj);
          console.log(keys.map((key) => [/^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],key]))
          if (keys.length > 0) {
            this.areas = new Map(keys.map((key) => [/^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],key]));
          }
        }
        await this.getEquipments();
      },
      async getAbility() {
        const obj = (await show({ id: 31 }, false))?.select_item;
        if (obj && typeof obj === "object") {
          let keys = Object.keys(obj);
          if (keys.length > 0) {
            this.abilities = new Map(keys.map((key) => [/^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],key]));
          }
        }
      },

      async getData () {
        this.weekRange = [this.$moment(this.weekSelect).startOf('week').format('YYYY-MM-DD')]
        for (let i = 1;i <= 6;i++) {
          this.weekRange.push(this.$moment(this.weekRange[0]).add(i,'day').format('YYYY-MM-DD'))
        }
        const res = await index({
          table_name: 'transfers',
          page: 1,
          page_size: 999,
          sort_name: 'equipment_id',
          filter: [
            {
              key: "status",
              op: "eq",
              value: 7
            },
            {
              key: "act_start_time",
              op: "range",
              value: `${this.weekRange.at(0)},${this.weekRange.at(-1)}`
            },
            {
              key: "equipment_id",
              op: "in",
              value: this.equipmentIds
            }
          ]
        })
        const sortData = (arr) => {
          let equipments = new Map();
          // 首先，我们将数组按照type进行分类
          let grouped = arr.reduce((acc, cur) => {
            if (!acc[cur.equipment_id]) {
              acc[cur.equipment_id] = [];
              equipments.set(cur.equipment_id,cur)
            }
            acc[cur.equipment_id].push(cur);
            return acc;
          }, {});

          // 然后，我们将每个分类的数组按照data进行排序，并填充undefined
          for (let equipment in grouped) {
            grouped[equipment].sort((a, b) => (Number(this.$moment(a.act_start_time).diff(this.$moment(b.act_start_time),'days'))));
            let sorted = Array.from({length: 7}, () => []);
            for (let item of grouped[equipment]) {
              sorted[this.weekRange.indexOf(this.$moment(item.act_start_time).format('YYYY-MM-DD'))].push(item);
            }
            grouped[equipment] = sorted;
          }

          // 最后，我们将对象转换为所需的数组格式
          let result = [];
          for (let equipment in grouped) {
            result.push({ equipment_id: Number(equipment),equipment: equipments.get(Number(equipment))?.equipment_id_equipments_id_relation, _sortData: grouped[equipment] });
          }

          return result;
        }

        this.tableData = mergeTableRow({
          data: this.selectArea ? sortData(res.data).filter(i => (i.equipment?.area === this.selectArea)) : sortData(res.data),
          mergeColNames: ["equipment_id","equipment.area","equipment.name"], // 需要合并的列，默认合并列相同的数据
          firstMergeColNames: ["equipment_id"], // 受影响的列，只合并以firstMerge为首的同类型数据
          firstMerge: "equipment_id", // 以哪列为基础进行合并，一般为第一列
        })
        console.log(this.tableData)
      },

      objectSpanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        const span = column['property'] + '-span'
        if (row[span]) {
          return row[span]
        }
      },

      async exportExcel(sheetName) {
        if (this.tableData) {
          const data = this.tableData.map(i => ([
            this.areas.get(i.equipment.area),
            i.equipment.name,
            '河道处',
            ...i._sortData.map(j => ((j.length > 0) ? j.map(k => (`${ this.$moment(k.act_start_time).format('HH:mm') } ~ ${ this.$moment(k.act_end_time).format('HH:mm') }  ${ k.content || " " }  ${ this.abilities.get(k.leibie) }\n`)).toString() : "")
            )])
          );
          data.unshift(["所属区域","工程名称","管理单位",...this.weekName]);
          data.unshift(["所属区域","工程名称","管理单位",...this.weekRange]);
          const wb = XLSX.utils.book_new();
          let ws = XLSX.utils.aoa_to_sheet(data);
          ws["!merges"] = [{ s: { r: 0, c: 0 }, e: { r: 1, c: 0 } },{ s: { r: 0, c: 1 }, e: { r: 1, c: 1 } },{ s: { r: 0, c: 2 }, e: { r: 1, c: 2 } }]
          ws["!cols"] = [{ wch: 30 }, { wch: 30 },{ wch: 10 },{ wch: 50 },{ wch: 50 },{ wch: 50 },{ wch: 50 },{ wch: 50 },{ wch: 50 },{ wch: 50 }]
          XLSX.utils.book_append_sheet(wb, ws, sheetName);
          const wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array",
          });
          saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            `${sheetName}.xlsx`
          );
        }
      },
    },
    created() {
      this.getAbility()
      this.getArea()
      this.getData()
    },
    mounted() {
      let clientHeight = document.documentElement.clientHeight;
      let lxheader = document.querySelector(".v-header")?.getBoundingClientRect();
      let lxHeader_height = lxheader.height + 25; //查询 头部
      let paginationHeight = 37; //分页的高度
      let topHeight = 50; //页面 头部
      this.tableHeight =
        clientHeight - lxHeader_height - topHeight - paginationHeight - 20 - 25 + 36;
    }
  }
</script>
