<!-- 搜索表单 -->
<template>
  <div style="margin-top: 10px">
    <el-button type="primary" @click="addColumn()" v-if="edit"
      >新增列</el-button
    >
    <el-button type="primary" @click="addRow(columns.length)" v-if="edit"
      >新增行</el-button
    >
    <div class="table" style="margin-top: 10px" :id="id">
      <div class="table-body" style="display: flex">
        <template v-for="(row, index) in columns">
          <div class="column" :style="{ width: row[0].width + 'px' }">
            <div
              class="table-body-item tableTd"
              v-for="(item, rowIndex) in row"
              :style="{
                height: item.rowspan * 30 + 'px',
                display: item.rowspan ? 'block' : 'none'
              }"
            >
              <i
                class="el-icon-delete delete"
                style="display: none"
                @click="removeColumn(index)"
                v-if="edit && rowIndex == 0"
              ></i>
              <i
                class="el-icon-circle-plus-outline add"
                style="display: none"
                @click="addColumn(index)"
                v-if="edit && rowIndex == 0"
              ></i>
              <i
                class="el-icon-delete deleteRow"
                @click="removeRow(rowIndex)"
                v-if="edit && rowIndex != 0"
              ></i>
              <i
                class="el-icon-circle-plus-outline addRow"
                style="display: none"
                @click="addRow(rowIndex, index)"
                v-if="edit && rowIndex != 0 && index != columns.length - 1"
              ></i>
              <textarea
                v-if="item.rowspan > 1"
                v-model="item.value"
                class="templateInput"
                :id="item.id"
                :readonly="item.readonly == 2 || !edit"
                @click="inputClick(item)"
                @input="calculation"
                autocomplete="off"
                style="resize: none"
              ></textarea>
              <input
                v-else
                v-model="item.value"
                class="templateInput"
                :id="item.id"
                :readonly="item.readonly == 2 || !edit"
                @click="inputClick(item, rowIndex == 0 ? 'columns' : null)"
                @input="calculation"
                type="text"
                autocomplete="off"
              />
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import { generateRandomString } from '@/utils/util';

  export default {
    props: {},
    mixins: [dictMixins],
    props: {
      id: '',
      edit: {
        default: true,
        type: Boolean
      }
    },
    data() {
      return {
        form: null,
        valueObj: {},
        domId: '',
        rightClickShow: false,
        columns: [],
        // rows: [],
        equation: {}
      };
    },
    created() {},
    methods: {
      // 方法：添加新列
      addColumn(index) {
        let length = this.columns[0]?.length || 1;
        if (index === 0 || index) {
          this.columns.splice(
            index + 1,
            0,
            Array(length)
              .fill(null)
              .map(() => this.getInput())
          );
        } else {
          this.columns.push(
            Array(length)
              .fill(null)
              .map(() => this.getInput())
          );
        }
      },
      getInput() {
        return {
          readonly: 1,
          value: '',
          rowspan: 1,
          id: generateRandomString(5)
        };
      },

      // 方法：删除指定列
      removeColumn(index) {
        this.columns.splice(index, 1);
      },

      // 方法：添加新行
      addRow(rowIndex, columnIndex) {
        if (columnIndex > 0) { //不是第一列则需要合并单元格
          this.columns.forEach((item, newColumnIndex) => {
            let newRow = this.getInput();
            if (newColumnIndex < columnIndex) {
              newRow.rowspan = 0;
              let _rowIndex = null;
              if (item[rowIndex].rowspan == 0) {
                _rowIndex = this.getPreventRowspan(newColumnIndex, rowIndex);
              }
              let rowspan =
                this.columns[newColumnIndex][_rowIndex || rowIndex].rowspan ||
                1;

              this.$set(
                this.columns[newColumnIndex][_rowIndex || rowIndex],
                'rowspan',
                (rowspan += 1)
              );
            }
            this.columns[newColumnIndex].splice(rowIndex + 1, 0, newRow);
          });
        } else { 
          this.columns.forEach((item, index) => {
            let _rowIndex = rowIndex;
            if (item[rowIndex]?.rowspan > 1) {
              _rowIndex += Number(item[rowIndex].rowspan);
            }
            this.columns[index].splice(_rowIndex + 1, 0, this.getInput());
          });
        }
      },
      //找到真正需要改变rowspan的行
      getPreventRowspan(columnIndex, rowIndex) {
        let preventRowspan = null;
        this.columns[columnIndex].forEach((item, newRowIndex) => {
          if (newRowIndex < rowIndex && item.rowspan > 1) { //向上找到当前列合并过单元格的行
            preventRowspan = newRowIndex;
          }
        });

        return preventRowspan;
      },
      // 方法：删除指定行
      removeRow(rowIndex) {
        this.columns.forEach((item, columnIndex) => {
          if (item[rowIndex].rowspan == 0) { // 如果当前列，删除的这一行rowspan为0，则需要找到真正需要改变rowspan的行
            let preventRowspanIndex = this.getPreventRowspan(
              columnIndex,
              rowIndex
            );
            if (preventRowspanIndex) {
              this.$set(
                this.columns[columnIndex][preventRowspanIndex],
                'rowspan',
                this.columns[columnIndex][preventRowspanIndex].rowspan - 1
              );
            }
          } else if (item[rowIndex].rowspan > 1) { //rowspan大于1,代表合并过单元格,需要吧值继承给下一行
            let data = item[rowIndex];
            data.rowspan--;
            this.$set(this.columns[columnIndex], [rowIndex + 1], data); 
          }

          item.splice(rowIndex, 1);
        });
      },


      calculation() {
        this.$emit('calculation');
      },
      equationValue({ domId, value }) {
        this.columns.forEach((item, index) => {
          let cellIndex = item.findIndex((cell) => cell.id == domId);
          if (cellIndex != '-1') {
            this.$set(this.columns[index][cellIndex], 'value', value);
          }
        });
      },
      getValue() {
        return {
          form: null,
          equation: this.equation,
          valueObj: {
            columns: this.columns
          }
        };
      },
      init({ form, valueObj, equation }) {
        this.form = form;
        this.columns = valueObj.columns;
        this.equation = equation || {};
      },
      editInputChange(domObj) {
        if (domObj.equation) {
          this.equation[this.domId] = domObj.equation;
        }
        this.columns.forEach((item, index) => {
          let rowsIndex = item.findIndex((cells) => cells.id == this.domId);
          if (rowsIndex >= 0) {
            this.$set(this.columns[index], rowsIndex, domObj);
          }
        });
      },

      inputClick(item, type) {
        if (!this.edit) {
          return;
        }
        let dom = document.getElementById(item.id);

        this.domId = item.id;
        this.$emit('editShow', {
          templateDivRef: 'customTextRef' + this.id,
          domObj: {
            width: dom.parentElement.offsetWidth,
            isNoWidth: type == 'columns' ? false : true,
            id: item.id,
            readonly: item.readonly,
            value: item.value,
            rowspan: item.rowspan,
            equation: this.equation[item.id]
          }
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  :deep(.templateInput) {
    width: 100%;
    height: 100%;
    border: none;

    text-align: center;
    background-color: #fff;
  }

  .table-header {
    span {
      display: inline-block;
      height: 30px;
      border: 1px solid #ddd;
      width: 100px;
      background-color: #f2f2f2 !important;
    }

    input {
      background-color: #f2f2f2 !important;
    }
  }
  .table-body {
    white-space: nowrap;
    .column {
      display: inline-block;
      width: 100px;
      > div {
        height: 30px;
        border: 1px solid #ddd;
        width: 100%;
      }
      > div:nth-of-type(1) {
        background-color: #f2f2f2 !important;
        > input {
          background-color: #f2f2f2 !important;
        }
      }
    }
  }
  // th,
  // td {
  //   border: 1px solid #ddd;
  //   padding: 2px;
  //   text-align: center;
  //   height: 30px;
  // }
  // th {
  //   background-color: #f2f2f2;
  //   > input {
  //     background-color: #f2f2f2 !important;
  //   }
  // }
  tr:nth-child(even) {
    background-color: #f9f9f9;
  }
  input:focus {
    border-color: #66afe9; /* 改变边框颜色 */
    outline: none; /* 移除默认的轮廓线 */
  }
  .tableTd {
    position: relative;
  }
  .deleteRow {
    display: block !important;
    position: absolute;
    bottom: 0px;
    right: -15px;
    color: #f56c6c;
  }
  .tableTd:hover {
    .delete {
      display: block !important;
      position: absolute;
      right: 0;
      top: 0;
      color: #f56c6c;
    }

    .add {
      display: block !important;
      position: absolute;
      right: 20px;
      top: 0;
      color: #409eff;
    }
    .addRow {
      display: block !important;
      position: absolute;
      bottom: 0px;
      right: 10px;
      color: #409eff;
    }
  }
</style>
