<template>
  <div class="elem-fill-field">
    <div
      class="fill-field-item"
      v-for="(info, index) in fields"
      :key="index"
      :style="itemStyles"
    >
      <div class="fill-field-content" :style="lineStyles">
        <span :style="paramStyle" v-html="info.contentHtml"></span>
        <span>：</span>
        <span :style="info.contStyle || contStyle">{{
          fieldInfos[info.code]
        }}</span>
      </div>
    </div>
    <div v-if="!data.fields.length" class="fill-field-item" :style="itemStyles">
      <div class="fill-field-content" :style="lineStyles">
        <span :style="paramStyle">变量名</span>
        <span>：</span>
        <span :style="contStyle">12345</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "elem-fill-field",
  props: {
    data: {
      type: Object,
    },
  },
  data() {
    return {
      fieldInfos: this.data["fieldInfos"] || {},
      fields: [],
      paramStyle: {},
      contStyle: {},
      lenWidths: {
        3: 45,
        4: 62,
        5: 75,
        6: 90,
        7: 105,
        8: 120,
      },
    };
  },
  computed: {
    itemStyles() {
      return {
        width: 100 / this.data.fieldCountPerLine + "%",
      };
    },
    lineStyles() {
      return {
        height: this.data.lineSpacing + "px",
        paddingTop: this.data.lineSpacing - 26 + "px",
      };
    },
  },
  methods: {
    init() {
      this.fields = this.data.fields.map((item) => {
        // 兼容wkhtmltopdf 汉字两端对齐的问题
        let nitem = { ...item };
        nitem.contentHtml = item.name
          .split("")
          .map((str) => `<i>${str}</i>`)
          .join(" ");
        if (!this.data.nameIsJustify) {
          nitem.contStyle = {
            marginLeft: item.name.length * 14 + 4 + 20 + "px",
          };
        }
        return nitem;
      });
      if (this.data.nameIsJustify) {
        const nameNums = this.data.fields.map((item) => item.name.length);
        const maxNameLen = Math.max.apply(null, nameNums);
        const num = maxNameLen < 3 ? 3 : maxNameLen > 8 ? 8 : maxNameLen;
        this.paramStyle = {
          width: this.lenWidths[num] + "px",
        };
        this.contStyle = {
          marginLeft: this.lenWidths[num] + 20 + "px",
        };
      } else {
        this.paramStyle = {};
        this.contStyle = {};
      }
    },
  },
  watch: {
    data: {
      immediate: true,
      handler() {
        this.init();
      },
    },
  },
};
</script>
