<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" style="width: 140px;"></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>

      <div v-for="(item, index) in transfers" :key="item.id" class="item">
        <div class="sub-title">{{ numberToChinese(index+1) }}. {{ item.equipment_id_equipments_id_relation ? item.equipment_id_equipments_id_relation.name : '' }}</div>
        <div class="time">
          <span>时间：</span>
          <span>{{ $moment(item.act_start_time).format('YYYY-MM-DD HH:mm') }} - {{ $moment(item.act_end_time).format('HH:mm') }}</span>
        </div>
        <div class="content">
          <span>{{ item.equipment_id_equipments_id_relation ? area(item.equipment_id_equipments_id_relation.area) : '' }}：</span>

          <span>{{ item.content }}</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  Document,
  Paragraph,
  HeadingLevel,
  AlignmentType,
  TextRun,
  Packer,
  convertInchesToTwip
} from "docx";
import { saveAs } from 'file-saver';
import { index } 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";
export default {
  components: {
    LxHeader,
    headerContent
  },
  mixins: [authMixin],
  data() {
    return {
      types: [],
      areas: [],
      transfers: [],
      selectDate: new Date(),
    }
  },
  methods: {
    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 () {
      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
    },

    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: "今日小雨转晴，北风2级，气温22℃~29℃。水情信息：8:00新塘3.06m，环城河北3.02m，觅渡桥2.99m，人民桥3.00m；16:00新塘3.03m，环城河北2.90m，觅渡桥2.92m，人民桥2.95m。",
                    size: 18,
                  })
                ]
              }),
              ...this.transfers.map((i, index) => (
                [
                  new Paragraph({
                    spacing: {
                      before: 200,
                      line: 400
                    },
                    children: [
                      new TextRun({
                        text: `${this.numberToChinese(index+1)}、${i.equipment_id_equipments_id_relation?.name}`,
                        size: 28,
                        bold: true,
                      }),
                    ]
                  }),
                  new Paragraph({
                    spacing: {
                      before: 200,
                      line: 400
                    },
                    indent: {
                      firstLine: convertInchesToTwip(0.5)
                    },
                    children: [
                      new TextRun({
                        text: `1、时间：${this.$moment(i.act_start_time).format('YYYY-MM-DD HH:mm')} - ${this.$moment(i.act_end_time).format('YYYY-MM-DD HH:mm')}  2、实际执行情况：${i.content}`,
                        size: 18,
                      })
                    ]
                  })
                ]
              )).flat()
            ]
          },
        ]
      })

      const blob = await Packer.toBlob(document)
      saveAs(blob, 'test.docx')
    }
  },
  computed: {
    area () {
      return function (area) {
        return this.areas.find(i => i.value === area)?.key
      }
    }
  },
  created() {
    this.getArea()
    this.getTransfer()
  }
}
</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;
}
.time {
  line-height: 1.5;

  padding: 0 4px;
}
.content {
  line-height: 1.5;

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