<!--
 * @Description: 动态表格 用于批量填入数据
 -->
<template>
  <div>
    <a-form ref="dynamicValidateForm" :model="dynamicValidateForm">
      <a-table v-if="!isMobile"
               class="batch-table"
               :rowKey="(column) => column.key"
               :columns="columns"
               :dataSource="dynamicValidateForm.domains"
               bordered
               :pagination="pagination"
               @change="tablePaginationChange"
               :scroll="{x: 'max-content'}"
      >
        <template #headerCell="{ column }">
          <div>
          <span
              v-if="
              record.list.find((item) => item.model == column.dataIndex) &&
              record.list.find((item) => item.model == column.dataIndex).rules[0].required
            "
              style="color: #ff4d4f; margin-right: 4px"
          >*</span
          >
            <span>{{ column.title }}</span>
          </div>
        </template>

        <template #bodyCell="scope">
          <div v-if="scope.column.dataIndex === 'sequence_index_number'">
            {{ getSerialNumber(scope.index) }}
          </div>
          <div v-else-if="record.list.find((item) =>item.disableColumn&& item.disableColumn ==scope.column.dataIndex)&&
          record.list.find((item) =>Array.isArray(item.disableIndex)&&item.disableIndex.includes(getSerialNumber(scope.index)))
          ">
            <StFormModelItem
                :record="record.list.find((item) => item.model == scope.column.dataIndex)"
                :config="config"
                :parentDisabled="true"
                :index="record.list.findIndex((item) => item.model == scope.column.dataIndex)"
                :domains="dynamicValidateForm.domains"
                :dynamicData="dynamicData"
                :formData="formData"
                :formConfig="formConfig"
                :childTableFieldRecord="record.list"
                :rowIndex="scope.index"
                v-model:value="scope.record[record.list.find((item) => item.model == scope.column.dataIndex).model]"
                @input="handleInput"
                :tableScope="scope"
                :columns="columns"
                :pagination="pagination"
                :currentTableData="currentTableData"
            />
          </div>
          <div v-else-if="record.list.find((item) => item.model == scope.column.dataIndex)">
            <StFormModelItem
                :record="record.list.find((item) => item.model == scope.column.dataIndex)"
                :config="config"
                :parentDisabled="disabled"
                :index="record.list.findIndex((item) => item.model == scope.column.dataIndex)"
                :domains="dynamicValidateForm.domains"
                :dynamicData="dynamicData"
                :formData="formData"
                :formConfig="formConfig"
                :childTableFieldRecord="record.list"
                :rowIndex="scope.index"
                v-model:value="scope.record[record.list.find((item) => item.model == scope.column.dataIndex).model]"
                @input="handleInput"
                :tableScope="scope"
                :columns="columns"
                :pagination="pagination"
                :currentTableData="currentTableData"
            />
          </div>

          <div v-if="scope.column.dataIndex === 'dynamic-opr-button'">
            <a-button v-if="!disabled" type="dashed" @click="removeDomain(scope.record)" danger>
              <template #icon>
                <DeleteOutlined/>
              </template>
            </a-button>
          </div>
        </template>
      </a-table>

      <div v-if="isMobile">
        <a-card v-for="(item, rowIdx) in firstData" :key="rowIdx" style="margin-bottom: 10px"
                class="mobile-table">
          <div v-for="(col, colIdx) in columns" :key="colIdx" class="mobile-table-item">
            <div class="mobile-table-item-content" v-if="col.dataIndex === 'sequence_index_number'">
              <div>
              <span>
                {{ col.title }}
              </span>
              </div>
              <div>
                <a-tag>{{ rowIdx + 1 }}</a-tag>
              </div>
            </div>
            <div class="mobile-table-item-content" v-if="col.dataIndex === 'dynamic-opr-button'">
              <div class="mob-label">
              <span>
                {{ col.title }}
              </span>
              </div>
              <a-button v-if="!disabled" type="dashed" @click="removeDomain(item)" danger>
                <template #icon>
                  <DeleteOutlined/>
                </template>
              </a-button>
            </div>
            <div class="mobile-table-item-content"
                 v-if="['sequence_index_number', 'dynamic-opr-button'].indexOf(col.dataIndex) === -1">
              <div class="mob-label">
              <span
                  v-if="
                  record.list.find((item) => item.model == col.dataIndex) &&
                  record.list.find((item) => item.model == col.dataIndex).rules[0].required
                "
                  style="color: #ff4d4f; margin-right: 4px"
              >*</span
              >
                <span>
                {{ col.title }}
              </span>
              </div>

              <div class="mobile-tanle-form-item">
                <StFormModelItem
                    :record="record.list.find((item) => item.model == col.dataIndex)"
                    :config="config"
                    :parentDisabled="disabled"
                    :index="record.list.findIndex((item) => item.model == col.dataIndex)"
                    :domains="dynamicValidateForm.domains"
                    :dynamicData="dynamicData"
                    :formData="formData"
                    :formConfig="formConfig"
                    :childTableFieldRecord="record.list"
                    :rowIndex="rowIdx"
                    v-model:value="item[record.list.find((item) => item.model == col.dataIndex).model]"
                    @input="handleInput"
                    :columns="columns"
                    :pagination="pagination"
                    :currentTableData="currentTableData"
                    :colIndex="colIdx"
                />
              </div>
            </div>
          </div>
        </a-card>
        <a-button type="dashed" style="width: 100%"
                  v-show="this.dynamicValidateForm.domains&&this.dynamicValidateForm.domains.length>1"
                  @click="openChild=true">查看更多 (共有{{ this.dynamicValidateForm.domains.length }}条数据)
        </a-button>
      </div>

      <a-button type="dashed" :disabled="disabled" @click="addDomain" v-if="!disabled">
        <template #icon>
          <PlusOutlined/>
        </template>
        增加
      </a-button>
    </a-form>

    <a-modal
        v-if="isMobile"
        v-model:open="openChild"
        :title="null"
        width="100%"
        wrapClassName="fullscreen-modal"
        :footer="null"
        style="top: 0; padding: 0"
        :closable="false"

    >
      <!-- 悬浮在顶部的按钮 -->
      <div class="floating-top-button">
        <a-button
            type="text"
            @click="openChild = false"
            style="color: #1890ff"
        >
          <template #icon>
            <LeftOutlined/> <!-- 返回图标 -->
          </template>
          返回
        </a-button>
      </div>
      <div class="modal-content-wrapper">
        <div class="scrollable-content">
          <div v-if="isMobile">
            <a-card v-for="(item, rowIdx) in dynamicValidateForm.domains" :key="rowIdx" style="margin-bottom: 10px"
                    class="mobile-table">
              <div v-for="(col, colIdx) in columns" :key="colIdx" class="mobile-table-item">
                <div class="mobile-table-item-content" v-if="col.dataIndex === 'sequence_index_number'">
                  <div>
              <span>
                {{ col.title }}
              </span>
                  </div>
                  <div>
                    <a-tag>{{ rowIdx + 1 }}</a-tag>
                  </div>
                </div>
                <div class="mobile-table-item-content" v-if="col.dataIndex === 'dynamic-opr-button'">
                  <div class="mob-label">
              <span>
                {{ col.title }}
              </span>
                  </div>
                  <a-button v-if="!disabled" type="dashed" @click="removeDomain(item)" danger>
                    <template #icon>
                      <DeleteOutlined/>
                    </template>
                  </a-button>
                </div>
                <div class="mobile-table-item-content"
                     v-if="['sequence_index_number', 'dynamic-opr-button'].indexOf(col.dataIndex) === -1">
                  <div class="mob-label">
              <span
                  v-if="
                  record.list.find((item) => item.model == col.dataIndex) &&
                  record.list.find((item) => item.model == col.dataIndex).rules[0].required
                "
                  style="color: #ff4d4f; margin-right: 4px"
              >*</span
              >
                    <span>
                {{ col.title }}
              </span>
                  </div>

                  <div class="mobile-tanle-form-item">
                    <StFormModelItem
                        :record="record.list.find((item) => item.model == col.dataIndex)"
                        :config="config"
                        :parentDisabled="disabled"
                        :index="record.list.findIndex((item) => item.model == col.dataIndex)"
                        :domains="dynamicValidateForm.domains"
                        :dynamicData="dynamicData"
                        :formData="formData"
                        :formConfig="formConfig"
                        :childTableFieldRecord="record.list"
                        :rowIndex="rowIdx"
                        v-model:value="item[record.list.find((item) => item.model == col.dataIndex).model]"
                        @input="handleInput"
                        :columns="columns"
                        :pagination="pagination"
                        :currentTableData="currentTableData"
                        :colIndex="colIdx"
                    />
                  </div>
                </div>
              </div>
            </a-card>
          </div>
          <a-button type="dashed" :disabled="disabled" @click="addDomain" v-if="!disabled">
            <template #icon>
              <PlusOutlined/>
            </template>
            增加
          </a-button>
        </div>
      </div>

    </a-modal>
  </div>
</template>

<script>
import StFormModelItem from './module/StFormModelItem.vue';
import {v1 as uuidv1} from 'uuid';
import {DeleteOutlined, CopyOutlined, PlusOutlined} from '@ant-design/icons-vue';
import {isMobile} from '/@/utils';

export default {
  name: 'StBatch',
  props: {
    record: {
      type: Object,
    },
    value: {},
    dynamicData: {},
    config: {},
    parentDisabled: {},
    formData: {},
    formConfig: {},
  },
  components: {
    StFormModelItem,
    DeleteOutlined,
    CopyOutlined,
    PlusOutlined,
  },
  watch: {
    value: {
      // value 需要深度监听及默认先执行handler函数
      handler(val) {
        this.dynamicValidateForm.domains = val || [];
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.initTable();
  },
  data() {
    return {
      top: 0,
      openChild: false,
      dynamicValidateForm: {
        domains: [],
      },
      page: 1, //初始页
      size: 5, //每页数据
      pagination: {
        current: 1, //分页的索引
        total: 0,
        pageSize: 10, //每页中显示10条数据
        size: 'small',
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
        showSizeChanger: true,
        showQuickJumper: false,
        showTotal: (total) => `共 ${total} 条数据`,
      },
      currentTableData: [],
      mobileTableData: [],
      mobilePage: {
        page: 1,
        size: 5
      },
    };
  },
  computed: {
    firstData() {
      if (this.dynamicValidateForm.domains.length == 0) {
        return []
      } else {
        return this.dynamicValidateForm.domains.slice(0, 1)
      }
    },
    listLength() {
      return this.record.list.filter((item) => !item.options.hidden).length;
    },
    columns() {
      const columns = [];
      if (!this.record.options.hideSequence) {
        columns.push({
          title: '序号',
          dataIndex: 'sequence_index_number',
          width: '80px',
          align: 'center',
        });
      }

      columns.push(
          ...this.record.list
              .filter((item) => !item.options.hidden)
              .map((item, index) => {
                return {
                  title: item.label,
                  dataIndex: item.model,
                  width: index === this.record.list.length - 1 ? '' : (item.options.childWidth ? item.options.childWidth : '300px'),
                  //customCell:item.customCell,//仅能修改控件底部的样式，没啥用
                };
              })
      );

      if (!this.disabled) {
        columns.push({
          title: '操作',
          dataIndex: 'dynamic-opr-button',
          fixed: 'right',
          width: '80px',
          align: 'center',
        });
      }

      return columns;
    },
    disabled() {
      return this.record.options.disabled || this.parentDisabled;
    },
    isMobile() {
      return isMobile();
    },
  },
  methods: {
    getSerialNumber(index) {
      const {current, pageSize} = this.pagination;
      return (current - 1) * pageSize + index + 1;
    },
    loadMoreHandle() {
      const start = (this.mobilePage.page) * this.mobilePage.size;
      const end = start + this.mobilePage.size;
      this.mobileTableData = this.dynamicValidateForm.domains.slice(0, end);
      this.mobilePage.page++;
    },
    initTable() {
      this.page = this.pagination.current;
      this.size = this.pagination.pageSize;
      this.refreshCurrentTableData();
    },

    initMobileTable() {
      this.mobilePage.page = 1;
      this.mobilePage.size = 5;
      this.mobileTableData = this.dynamicValidateForm.domains.length > this.mobilePage.size ? this.dynamicValidateForm.domains.slice(0, this.mobilePage.size) : this.dynamicValidateForm.domains;
    },

    getPageData(array, pageNumber, pageSize) {
      // 计算开始索引
      const start = (pageNumber - 1) * pageSize;
      // 计算结束索引
      const end = start + pageSize;
      // 返回该页的数据
      return array.slice(start, end);
    },
    tablePaginationChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.page = pagination.current;
      this.size = pagination.pageSize;

      this.refreshCurrentTableData();
      this.pagination.total = pagination.total
    },
    validationSubform() {
      return new Promise((resolve, reject) => {
        this.$refs.dynamicValidateForm
            .validateFields()
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
      });
    },
    resetForm() {
      this.$refs.dynamicValidateForm.resetFields();
    },
    removeDomain(item) {
      const index = this.dynamicValidateForm.domains.indexOf(item);
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1);
      }

      this.refreshCurrentTableData();

      this.handleInput('DELETE');
    },
    addDomain() {
      const data = {};
      this.record.list.forEach((item) => {
        data[item.model] = item.options.defaultValue;
      });

      this.dynamicValidateForm.domains.push({
        ...data,
        key: uuidv1(),
      });

      this.refreshCurrentTableData();

      // 跳转至最后一页;
      if (this.dynamicValidateForm.domains.length % this.pagination.pageSize === 0) {
        this.gotoPageNum(Math.floor(this.dynamicValidateForm.domains.length / this.pagination.pageSize));
      } else {
        this.gotoPageNum(Math.floor(this.dynamicValidateForm.domains.length / this.pagination.pageSize) + 1);
      }

      this.handleInput('ADD');
    },
    handleInput(...args) {
      let params = {};
      if (args.length == 1 && !['ADD', 'DELETE'].includes(args[0])) {
        return false;
      }
      if (args.length == 4) {
        let [value, key, record, tableInfo] = args;
        tableInfo.optType = 'UPDATE';
        params = {value, key, record, tableInfo};
      } else {
        params = {
          value: this.dynamicValidateForm.domains,
          key: this.record.model,
          record: this.record,
          tableInfo: {optType: args[0]}
        };
      }

      this.$emit('update:value', this.dynamicValidateForm.domains);
      this.$emit('change', params.value, this.record.model, this.record, params.tableInfo);
    },
    refreshCurrentTableData() {
      this.currentTableData = this.getPageData(this.dynamicValidateForm.domains, this.pagination.current, this.pagination.pageSize);
    },
    // 跳转至某一页
    gotoPageNum(num) {
      if (num == this.pagination.current) return;
      this.pagination.current = num;
    }
  },
};
</script>
<style scoped lang="less">

.dynamic-opr-button {
  margin-left: 0px;
}

:deep(.css-dev-only-do-not-override-1r8ax8d).ant-table-wrapper .ant-table-thead > tr > th,
:deep(.css-dev-only-do-not-override-1r8ax8d).ant-table-wrapper .ant-table-tbody > tr > td,
:deep(.css-dev-only-do-not-override-1r8ax8d).ant-table-wrapper tfoot > tr > th,
:deep(.css-dev-only-do-not-override-1r8ax8d).ant-table-wrapper tfoot > tr > td {
  padding: 5px 5px;
}

:deep(.css-dev-only-do-not-override-1r8ax8d).ant-table-wrapper .ant-table-pagination.ant-pagination {
  margin: 6px 0;
}

.dynamic-opr-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 16px;
  color: #999;
  transition: all 0.3s;
  margin-left: 6px;
}

.dynamic-opr-button:hover {
  color: #e89;
}

.dynamic-opr-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}

.batch-table {
  display: flex;
  flex-direction: column;

  :deep(.ant-form-item) {
    margin: 0;
  }
}

.mobile-table {
  :deep(.ant-card-body) {
    padding: 15px;
  }

  .mobile-table-item {
    width: 100%;

    .mobile-table-item-content {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;

      .mob-label {
        width: 100px;
      }

      .mobile-tanle-form-item {
        width: calc(100% - 100px);
      }
    }
  }
}

/* 全屏模态框样式 */
:deep(.fullscreen-modal) {
  .ant-modal {
    max-width: 100%;
    width: 100% !important;
    margin: 0;
    top: 0;
    padding-bottom: 0;
    height: 100vh;

    .ant-modal-content {
      height: 100vh;
      display: flex;
      flex-direction: column;

      .ant-modal-body {
        padding: 0; /* 移除默认 padding */
      }
    }
  }
}

/* 滚动容器 */
.modal-scroll-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 可滚动的内容区域 */
.scrollable-content {
  flex: 1;
  overflow-y: auto; /* 允许内容滚动 */
  padding: 1px;
}

/* 悬浮在顶部的按钮容器 */
.floating-top-button {
  position: sticky;
  top: 0;
  z-index: 1000;
  background: #fff;
  padding: 6px 0px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end; /* 按钮靠右 */
}
</style>
