<template>
  <div>
    <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 type="daterange" v-model="selectDate" size="small" :clearable="false" style="width: 220px;" @change="search"></el-date-picker>
<!--                  <Button-->
<!--                    style="margin-left: 10px"-->
<!--                    type="primary"-->
<!--                    @click="getTransfer"-->
<!--                  >查询</Button-->
<!--                  >-->
                </div>
              </template>
              <Button type="primary" @click="exportDocx">导出</Button>
            </header-content>
          </slot>
        </LxHeader>
      </div>
    </div>

    <el-card id="docx-content" v-loading="loading"
             element-loading-spinner="el-icon-loading"
             element-loading-text="拼命加载中"
             element-loading-background="rgba(0, 0, 0, 0.8)">
      <div v-for="(value, date) in showData" :key="date" v-if="Object.keys(value).length > 0">
        <div class="title">{{ date }}调度指令执行情况</div>
        <p class="weather">{{ weather[date] ? weather[date].weather : '' }}</p>

        <div v-for="(area, areaId) in value" :key="areaId">
          <div class="area">{{ area.area ? area.area.key : '暂无区域' }}</div>

          <div v-for="(transfer, index) in area._data" :key="transfer.id" class="transfer">
            <div class="transfer__name">{{ numberToChinese(++index) }}. {{ transfer.xuhao }} {{ transfer.equipment_id_equipments_id_relation ? transfer.equipment_id_equipments_id_relation.name: '' }}</div>
            <div class="transfer__type">
              【{{ diaolingleixing.get(transfer.diaolingleixing) }}】{{ type(transfer.leibie) }}
            </div>
            <div class="transfer__plantime">
              <span>计划时间：</span>
              <span>{{ $moment(transfer.start_time).format('YYYY-MM-DD HH:mm') }} ~ {{ $moment(transfer.end_time).format('YYYY-MM-DD HH:mm') }}</span>
            </div>
            <div class="transfer__acttime">
              <span>实际时间：</span>
              <span>{{ $moment(transfer.act_start_time).format('YYYY-MM-DD HH:mm') }} ~ {{ $moment(transfer.act_end_time).format('YYYY-MM-DD HH:mm') }}</span>
            </div>
            <div class="transfer__content">
              <span>调令内容：</span>
              <span>{{ transfer.to_transfer_id ? "[调整]" : "" }}{{ transfer.content }}</span>
            </div>
          </div>
        </div>
      </div>
      <el-empty v-if="transfers.length === 0" description="暂无完成调令"></el-empty>

    </el-card>
  </div>
</template>

<script>
import {
  Document,
  Paragraph,
  HeadingLevel,
  AlignmentType,
  TextRun,
  Packer,
  convertInchesToTwip,
} from "docx";
import { saveAs } from 'file-saver';
import { index, save } from "@/api/system/baseForm";
import headerContent from "@/components/LxHeader/XyContent.vue";
import LxHeader from "@/components/LxHeader/index.vue";
import { authMixin } from "@/mixin/authMixin";
import { show } from "@/api/system/customFormField";
import { info, weather} from "@/api/other";
export default {
  components: {
    LxHeader,
    headerContent
  },
  mixins: [authMixin],
  data() {
    return {
      loading: false,
      types: [],
      areas: [],
      weather: {},
      transfers: [],
      showData: {},
      selectDate: [new Date(),new Date()],
      diaolingleixing: new Map([
        [1,"水环境调令"],
        [2,"防汛调令"],
        [3,"船只过闸调令"],
        [4,"逻辑调令"]
      ])
    }
  },
  methods: {
    search () {
      if (this.loading) return;
      this.loading = true;
      Promise.all([this.getTransfer(),this.getWeather()]).then(_ => this.loading = false).catch(_ => this.loading = false)
    },

    async getWeatherInfo () {
      try {
        let infoObj = {
          weather: '',
          water: '',
          rain: '',
          prevent: '',
          early_warning: ''
        }
        const weatherInfo = await weather()
        if (!weatherInfo || typeof weatherInfo !== 'object' || weatherInfo.length === 0) return;
        infoObj.weather = `${weatherInfo.weather},${weatherInfo.wD}${weatherInfo.wS},${weatherInfo.sendibleTemp}-${weatherInfo.temp}°C`
        const infos = (await info({
          date: this.$moment().format('YYYY-MM-DD')
        }))[0]
        infoObj.water = `${infos?.daily_water?.map(i => i.range + i.stnm + i.s_value + 'm,')?.toString()}`
        infoObj.rain = `${infos?.daily_rain?.map(i => i.type + i.rain_value + 'mm,')?.toString()}`

        this.weather = infoObj

        await save({
          table_name: 'waters',
          date: this.$moment().format('YYYY-MM-DD'),
          ...infoObj
        },false)
      } catch (err) {

      }
    },
    async getWeather () {
      const res = (await index({
        table_name: 'waters',
        filter: [
          {
            key: 'date',
            op: 'range',
            value: `${this.$moment(this.selectDate[0]||new Date()).startOf('days').format('YYYY-MM-DD HH:mm:ss')},${this.$moment(this.selectDate[1]||new Date()).endOf('days').format('YYYY-MM-DD HH:mm:ss')}`
          }
        ]
      },false)).data


      let pickDateArr = [];
      let startDay = this.$moment(this.selectDate[0]||new Date()).startOf('days')
      while (startDay.isBefore(this.$moment(this.selectDate[1]||new Date()).endOf('days')) || (startDay.valueOf() === this.$moment(this.selectDate[1]||new Date()).endOf('days').valueOf())) {
        pickDateArr.push(startDay.format('YYYY-MM-DD'))
        startDay = startDay.add(1,'day')
      }
      this.weather = {};
      pickDateArr.forEach(date => {
        this.weather[date] = res.find(i => i.date === date)
      })
      console.log(this.weather)
    },

    numberToChinese (num) {
      if (num == 10) {
        return '十'
      } else if (num == 1) {
        return '一'
      }
      const digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
      const units = ['', '十', '百', '千', '万'];
      let result = '';
      let numStr = num.toString();
      for (let i = 0; i < numStr.length; i++) {
        let digit = parseInt(numStr.charAt(i));
        let unit = units[numStr.length - i - 1];
        if (digit === 0) {
          // 当前数字为0时不需要输出汉字，但需要考虑上一个数字是否为0，避免出现连续的零
          if (result.charAt(result.length - 1) !== '零') {
            result += '零';
          }
        } else {
          result += digits[digit] + unit;
        }
      }
      // 对于一些特殊的数字，如10、100等，需要在最前面加上“一”
      if (result.charAt(0) === '一') {
        result = result.substr(1, result.length);
      } else if (result.charAt(0) === '百') {
        result = '一' + result;
      } else if (result.charAt(0) === '千') {
        result = '一' + result;
      }
      return result
    },

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

    async getType() {
      const obj = (await show({ id: 31 }, false))?.select_item;
      if (obj && typeof obj === "object") {
        let keys = Object.keys(obj);
        if (keys.length > 0) {
          this.types = keys.map((key) => {
            return {
              key,
              value: /^\d*$/.test(obj[key]) ? Number(obj[key]) : obj[key],
            };
          });
        }
      }
    },

    async getTransfer () {
      try {
        this.transfers = (await index({
          table_name: "transfers",
          page: 1,
          page_size: 999,
          sort_name: "start_time",
          filter: [
            {
              key: 'start_time',
              op: 'range',
              value: `${this.$moment(this.selectDate[0]||new Date()).startOf('days').format('YYYY-MM-DD HH:mm:ss')},${this.$moment(this.selectDate[1]||new Date()).endOf('days').format('YYYY-MM-DD HH:mm:ss')}`
            },
            {
              key: 'status',
              op: 'eq',
              value: 7
            }
          ]
        })).data

        let pickDateArr = [];
        let startDay = this.$moment(this.selectDate[0]||new Date()).startOf('days')
        while (startDay.isBefore(this.$moment(this.selectDate[1]||new Date()).endOf('days')) || (startDay.valueOf() === this.$moment(this.selectDate[1]||new Date()).endOf('days').valueOf())) {
          pickDateArr.push(startDay.format('YYYY-MM-DD'))
          startDay = startDay.add(1,'day')
        }

        this.showData = {}
        pickDateArr.forEach(date => {
          this.showData[date] = {}
        })
        this.transfers.forEach(item => {
          if (item.start_time && item.equipment_id_equipments_id_relation.area) {
            let myDate = this.$moment(item.start_time).format('YYYY-MM-DD');
            let dateObj = this.showData[myDate];
            if (dateObj.hasOwnProperty(item.equipment_id_equipments_id_relation.area)) {
              dateObj[item.equipment_id_equipments_id_relation.area]._data.push(item)
            } else {
              dateObj[item.equipment_id_equipments_id_relation.area] = {
                _data: [item],
                area: this.areas.find(k => k.value === item.equipment_id_equipments_id_relation.area)
              }
            }
          }
        })
        // this.showData = this.areas.map(i => {
        //   return {
        //     ...i,
        //     _data: new Map()
        //   }
        // })
        // this.transfers.forEach(item => {
        //   let filterData = this.showData.find(i => i.value === item.equipment_id_equipments_id_relation.area)
        //   if (filterData) {
        //     if (filterData._data.has(item.equipment_id)) {
        //       filterData._data.get(item.equipment_id).push(item)
        //     } else {
        //       filterData._data.set(item.equipment_id, [item])
        //     }
        //   }
        // })
      } catch (e) {

      }
      this.showData = Object.assign({}, this.showData)
      console.log(this.showData)
    },

    async exportDocx () {
      if (this.loading) return;
      if (this.transfers.length <=0 ) {
        this.$message({
          type: "warning",
          message: "暂无完成调令"
        })
      }
      const document = new Document({
        title: `${this.selectDate[0] ? this.$moment(this.selectDate[0]).format('YYYY年MM月DD日') : "-"} ~ ${this.selectDate[1] ? this.$moment(this.selectDate[1]).format('YYYY年MM月DD日') : "-"}调度指令执行情况`,
        sections: (() => {
          let sections = [];
          for (let date in this.showData) {
            let value = this.showData[date];
            if (Object.keys(value).length > 0) {
              let sectionChildren = [
                new Paragraph({
                  text: `${this.$moment(date).format('YYYY年MM月DD日')}调度指令执行情况`,
                  heading: HeadingLevel.HEADING_2,
                  alignment: AlignmentType.CENTER,
                  spacing: {
                    after: 300
                  }
                }),
                new Paragraph({
                  text: this.weather[date]?.weather,
                  heading: HeadingLevel.HEADING_4,
                  alignment: AlignmentType.CENTER,
                  spacing: {
                    after: 200
                  }
                }),
              ]
              for (let areaId in value) {
                let area = value[areaId];
                sectionChildren.push(new Paragraph({
                  indent: {
                    firstLine: convertInchesToTwip(0.5)
                  },
                  spacing: {
                    after: 100,
                    before: 100
                  },
                  children: [
                    new TextRun({
                      text: area?.area.key || "暂无区域",
                      size: 24,
                      bold: true
                    })
                  ]
                }))

                for (let index in area._data) {
                  let transfer = area._data[index];
                  sectionChildren.push(new Paragraph({
                    text: `${ this.numberToChinese(++index) }. ${ transfer?.xuhao || ' ' } ${ transfer?.equipment_id_equipments_id_relation?.name }`,
                    indent: {
                      firstLine: convertInchesToTwip(0.8)
                    },
                    spacing: {
                      after: 50
                    },
                  }))
                  sectionChildren.push(new Paragraph({
                    text: `【${ this.diaolingleixing.get(transfer.diaolingleixing) }】${this.type(transfer.leibie)}`,
                    indent: {
                      firstLine: convertInchesToTwip(1)
                    },
                    spacing: {
                      after: 50
                    },
                  }))
                  sectionChildren.push(new Paragraph({
                    text: `计划时间：${ this.$moment(transfer.start_time).format('YYYY-MM-DD HH:mm') } ~ ${ this.$moment(transfer.end_time).format('YYYY-MM-DD HH:mm') }`,
                    indent: {
                      firstLine: convertInchesToTwip(1)
                    },
                    spacing: {
                      after: 50
                    },
                  }))
                  sectionChildren.push(new Paragraph({
                    text: `实际时间：${ this.$moment(transfer.act_start_time).format('YYYY-MM-DD HH:mm') } ~ ${ this.$moment(transfer.act_end_time).format('YYYY-MM-DD HH:mm') }`,
                    indent: {
                      firstLine: convertInchesToTwip(1)
                    },
                    spacing: {
                      after: 50
                    },
                  }))
                  sectionChildren.push(new Paragraph({
                    text: `${ transfer.to_transfer_id ? '[调整]' : '' }内容：${ transfer.content || ' ' }`,
                    indent: {
                      firstLine: convertInchesToTwip(1)
                    },
                    spacing: {
                      after: 50
                    },
                  }))
                }
              }
              sections.push({
                children: sectionChildren
              })
            }
          }
          return sections;
        })()
      })
      // const document = new Document({
      //   sections: [
      //     {
      //       children: [
      //         new Paragraph({
      //           text: `${this.selectDate[0] ? this.$moment(this.selectDate[0]).format('YYYY年MM月DD日') : "-"} ~ ${this.selectDate[1] ? this.$moment(this.selectDate[1]).format('YYYY年MM月DD日') : "-"}调度指令执行情况`,
      //           heading: HeadingLevel.HEADING_1,
      //           alignment: AlignmentType.CENTER,
      //           spacing: {
      //             after: 400
      //           }
      //         }),
      //         new Paragraph({
      //           indent: {
      //             firstLine: convertInchesToTwip(0.5)
      //           },
      //           spacing: {
      //             before: 200,
      //             line: 500
      //           },
      //           children: [
      //             new TextRun({
      //               text: this.weather.weather,
      //               size: 18,
      //             })
      //           ]
      //         }),
      //         ...this.showData.filter(i => (i._data && i._data.size>0)).map((i, index) => (
      //           [
      //             new Paragraph({
      //               spacing: {
      //                 before: 200,
      //                 line: 400
      //               },
      //               children: [
      //                 new TextRun({
      //                   text: `${this.numberToChinese(index+1)}、${i.key}`,
      //                   size: 28,
      //                   bold: true,
      //                 }),
      //               ]
      //             }),
      //             ...Array.from(i._data).map((i1, index1) => (
      //               [
      //                 new Paragraph({
      //                   spacing: {
      //                     before: 200,
      //                     line: 300
      //                   },
      //                   indent: {
      //                     left: 200
      //                   },
      //                   children: [
      //                     new TextRun({
      //                       text: `${index1+1}. ${i1[1][0].equipment_id_equipments_id_relation ? i1[1][0].equipment_id_equipments_id_relation.name : ''}`,
      //                       size: 24,
      //                     }),
      //                   ]
      //                 }),
      //                 ...i1[1].sort((a,b) => new Date(a.act_start_time).valueOf() - new Date(b.act_start_time).valueOf()).map((i2, index2) => {
      //                   return new Paragraph({
      //                     indent: {
      //                       left: 400
      //                     },
      //                     alignment: AlignmentType.LEFT,
      //                     children: [
      //                       new TextRun({
      //                         text: `${index1+1}.${index2+1} 【${ this.diaolingleixing.get(i2.diaolingleixing) }】${ this.type(i2.leibie) }`,
      //                         size: 20,
      //
      //                         break: 1,
      //                       }),
      //                       new TextRun({
      //                         text: `时间： ${i2.act_start_time ? this.$moment(i2.act_start_time).format('YYYY-MM-DD HH:mm') : "-" } ~ ${ i2.act_end_time ? this.$moment(i2.act_end_time).format('HH:mm') : "-" }`,
      //                         size: 18,
      //                         break: 1,
      //                       }),
      //                       new TextRun({
      //                         text: `${ i2.to_transfer_id ? "[调整]" : "" }内容：${i2.content || ''}`,
      //                         size: 18,
      //                         break: 1,
      //                       }),
      //                       ...(() => {
      //                         if (i2.diaolingleixing === 4) {
      //                           return i2.id_logs_transfer_id_relation.map(log => new TextRun({
      //                             text: `${this.$moment(log.created_at).format('HH:mm')} ${log.content}`,
      //                             size: 18,
      //                             break: 1,
      //                           }))
      //                         } else {
      //                           return []
      //                         }
      //                       })()
      //                     ]
      //                   })
      //                 })
      //               ]
      //             )).flat()
      //           ]
      //         )).flat()
      //       ]
      //     },
      //   ]
      // })

      const blob = await Packer.toBlob(document)
      saveAs(blob, `${this.selectDate[0] ? this.$moment(this.selectDate[0]).format('YYYY年MM月DD日') : "-"} ~ ${this.selectDate[1] ? this.$moment(this.selectDate[1]).format('YYYY年MM月DD日') : "-"}调度指令执行情况.docx`)
    },
  },
  computed: {
    area () {
      return function (area) {
        return this.areas.find(i => i.value === area)?.key
      }
    },
    type () {
      return function (type) {
        return this.types.find(i => i.value === type)?.key
      }
    }
  },
  created() {
    this.getType()
    this.getArea()
    this.search()
  }
}
</script>

<style scoped lang="scss">
#docx-content {
  min-height: 300px;
}
.title {
  font-weight: bolder;
  font-size: 19px;
  text-align: center;
  line-height: 3;
}
.weather {
  font-size: 15px;
  text-align: center;
  line-height: 1.5;
}
.area {
  font-weight: 600;
  font-size: 15px;
  line-height: 3;
}
.transfer {
  line-height: 1.75;
  text-indent: 20px;
  & > div:nth-child(n+2) {
    text-indent: 40px;
  }
  &__type {

  }
  &__name {

  }
}
</style>
