<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 v-model="selectDate" size="small" :clearable="false" style="width: 140px;" @change="getTransfer"></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>
      <div class="title">{{ $moment(selectDate).format('YYYY-MM-DD') }}调度指令执行情况</div>

      <p style="text-indent: 30px;line-height: 1.2;padding: 20px 0;">{{ weather.weather }}</p>

      <div v-for="(item, index) in showData" :key="item.value">
        <div class="item" v-if="item._data.length > 0">
          <div class="sub-title">{{ numberToChinese(index+1) }}. {{ item.key }}</div>

          <div v-for="(item1, index1) in item._data" :key="item1.id">
            <div class="name">
              {{index1+1}}.{{ item1.equipment_id_equipments_id_relation ? item1.equipment_id_equipments_id_relation.name : '' }}
            </div>
            <div class="time">
              <span>时间：</span>
              <span>{{ $moment(item1.act_start_time).format('YYYY-MM-DD HH:mm') }} - {{ $moment(item1.act_end_time).format('HH:mm') }}</span>
            </div>
            <div class="content">
              <span>内容：</span>
              <span>{{ item1.content }}</span>
            </div>
          </div>
        </div>
      </div>
    </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 {
      types: [],
      areas: [],
      weather: {},
      transfers: [],
      showData: [],
      selectDate: new Date(),
    }
  },
  methods: {
    async getWeatherInfo () {
      let infoObj = {
        weather: '',
        water: '',
        rain: '',
        prevent: '',
        early_warning: ''
      }
      const weatherInfo = await weather()
      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)
    },
    async getWeather () {
      const res = (await index({
        table_name: 'waters',
        filter: [
          {
            key: 'date',
            op: 'eq',
            value: this.$moment().format('YYYY-MM-DD')
          }
        ]
      },false)).data[0]

      if (!res) {
        await this.getWeatherInfo()
      } else {
        this.weather = res
      }
    },

    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: 1 }, 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,
          filter: [
            {
              key: 'start_time',
              op: 'range',
              value: `${this.$moment(this.selectDate).startOf('days').format('YYYY-MM-DD HH:mm:ss')},${this.$moment(this.selectDate).endOf('days').format('YYYY-MM-DD HH:mm:ss')}`
            },
            {
              key: 'status',
              op: 'eq',
              value: 7
            }
          ]
        })).data

        this.showData = this.areas.map(i => {
          return {
            ...i,
            _data: []
          }
        })
        this.transfers.forEach(item => {
          let filterData = this.showData.find(i => i.value === item.equipment_id_equipments_id_relation.area)
          if (filterData) {
            filterData._data.push(item)
          }
        })
      } catch (e) {

      }
    },

    async exportDocx () {
      const document = new Document({
        sections: [
          {
            children: [
              new Paragraph({
                text: `${this.$moment(this.selectDate).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.length>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,
                      }),
                    ]
                  }),
                  ...i._data.map((i1, index1) => (
                    [
                      new Paragraph({
                        spacing: {
                          before: 200,
                          line: 300
                        },
                        indent: {
                          firstLine: convertInchesToTwip(0.5)
                        },
                        children: [
                          new TextRun({
                            text: `${index1+1}. ${i1.equipment_id_equipments_id_relation.name}`,
                            size: 24,
                          }),
                          new TextRun({
                            text: `\n时间： ${this.$moment(i1.act_start_time).format('YYYY-MM-DD HH:mm')} - ${this.$moment(i1.act_end_time).format('HH:mm')}`,
                            size: 18
                          }),
                          new TextRun({
                            text: `\n内容：${i1.content || ''}`,
                            size: 18
                          })
                        ]
                      })
                    ]
                  )).flat()
                ]
              )).flat()
            ]
          },
        ]
      })

      const blob = await Packer.toBlob(document)
      saveAs(blob, `${this.$moment(this.selectDate).format('YYYY-MM-DD')}调令.docx`)
    }
  },
  computed: {
    area () {
      return function (area) {
        return this.areas.find(i => i.value === area)?.key
      }
    }
  },
  created() {
    this.getArea()
    this.getTransfer()
    this.getWeather()
  }
}
</script>

<style scoped lang="scss">
.title {
  font-weight: bolder;
  font-size: 19px;
  text-align: center;

  padding: 10px 0;
}
.sub-title {
  font-weight: bold;
  font-size: 16px;

  padding: 8px 0;
}
.name {
  text-indent: 30px;
  line-height: 1.5;

  padding: 6px 0;
}
.time {
  text-indent: 60px;
  line-height: 1.5;

}
.content {
  text-indent: 60px;
  line-height: 1.5;

}
.item + .item {
  margin-top: 20px;
}
</style>
