<template>
  <a-collapse v-model:activeKey="activeKey">
    <a-collapse-panel
      key="1"
      :show-arrow="false"
      :header="Language.getNameTrl($i18n.locale, tab)"
    >
      <div v-if="!collapse">
        <div
          class="grid-container"
          :style="{
            'padding-right': showComplexFilterPanel == true ? '360px' : '0px',
          }"
        >
          <div class="grid-item-row1">
            <SimpleFilterPanel
              v-model:searchText="searchText"
              :disabled="showComplexFilterPanel == true"
              :window-no="windowNo"
              :tab-index="tabIndex"
              :filter-schema="tab.filterSchema"
              class="m-row"
              @simple-search="simpleSearch"
              @show-complex-filter-panel="showComplexFilterPanel = true"
            />
          </div>

          <a-space>
            <a-button v-if="canEdit" @click="newModelData">
              {{ $t("lang.subTabGridEdit.create") }}
            </a-button>
            <a-button v-if="canEdit" @click="deleteRecords(true)">
              {{ $t("lang.subTabGridEdit.remove") }}
            </a-button>
            <a-button v-if="canEdit" @click="queryGridData">
              {{ $t("lang.subTabGridEdit.revert") }}
            </a-button>
            <a-button v-if="canEdit" @click="editAllTabData">
              {{ $t("lang.subTabGridEdit.editAll") }}
            </a-button>
            <a-button @click="queryGridData">
              {{ $t("lang.subTabGridEdit.refresh") }}
            </a-button>

            <TabButton
              :show-tab-dto="tab"
              :model-datas="modelDatas"
              :parent-model-data="parentModelData"
              :uuid="uuid"
              :view-type="'Grid'"
              :tab-buttons="tab.tabGridView ? tab.tabGridView.tabButtons : null"
              :curd-window-function-access="curdWindowFunctionAccess"
              @save-view="$emit('saveView')"
              @process-execute-finish="refreshParent"
            />

            <GridColumnDef
              :tab-grid-fields="tabGridFields"
              :window-no="windowNo"
              :tab-index="tabIndex"
              @property-changed="propertyChanged($event)"
            />
          </a-space>

          <div class="grid-item-row3-column1">
            <div class="sub-table-container" :style="{ 'height': modelDatas.length > 0 ? '40vh' : '24vh' }">
              <div
                :id="scrollObject.tableOutDivUuid1"
                ref="tableContainer1"
                class="col-md-12"
              >
                <div :id="scrollObject.tableOutDivUuid2" ref="tableContainer2">
                  <table
                    class="curd-table table-striped table-bordered float-table"
                    :width="tableWidth"
                  >
                    <thead>
                      <GridHeader
                        :is-show-edit="canEdit"
                        :tab-grid-fields="tabGridFields"
                        :window-no="windowNo"
                        :tab-index="tabIndex"
                        :parent-model-data="parentModelDataClone"
                        :is-chinese-english="isChineseEnglish"
                        height="40px"
                        @on-sort="onSort($event)"
                        @property-changed="propertyChanged($event)"
                        @select-all="selectAll($event)"
                        @multiple-select="changeSelectMode($event)"
                      />
                    </thead>
                    <tfoot>
                      <GridFooter
                        v-for="index in [1, 2, 3]"
                        :key="'footer' + index"
                        :tab-grid-fields="tabGridFields"
                        :is-show-edit="canEdit"
                        height="40px"
                      />
                    </tfoot>
                    <tbody>
                      <template v-for="(modelData, index) in modelDatas">
                        <GridBody
                          v-if="
                            modelData.deleted != true &&
                              modelData.visible == true
                          "
                          ref="gridBody1"
                          :key="modelData.id + '_' + index"
                          :is-show-edit="canEdit"
                          :serial-number="
                            index +
                              1 +
                              (pagination.current_page - 1) * pagination.per_page
                          "
                          :window-no="windowNo"
                          :tab-index="tabIndex"
                          :tab-grid-fields="tabGridFields"
                          :model-data="modelData"
                          :parent-model-data="parentModelDataClone"
                          height="40px"
                          :class-name="tab.tabDataSource.className"
                          :scroll-object="scrollObject"
                          :js-url="jsUrl"
                          @delete-record="deleteRecord(modelData, true)"
                          @edit-record="editRecord(modelData, tabGridFields)"
                          @click-model-data="clickModelData(modelData)"
                          @value-changed="
                            valueChanged($event, modelData, index)
                          "
                          @execute-callout="
                            executeCallout($event, modelData, index)
                          "
                        />
                      </template>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          <div
            v-if="tab != null && tab.filterSchema != null"
            class="grid-item-row3-column2"
          >
            <div
              class="toggle-filter-btn"
              @click="showComplexFilterPanel = !showComplexFilterPanel"
            >
              <template v-if="showComplexFilterPanel">
                <RightOutlined />
              </template>
              <template v-else>
                <LeftOutlined />
              </template>
            </div>
          </div>

          <a-drawer
            v-model:open="showComplexFilterPanel"
            :title="$t('lang.subTabGridEdit.advancedSearch')"
            :width="500"
            :footer-style="{ textAlign: 'right' }"
            :mask="false"
            :mask-closable="false"
            @close="showComplexFilterPanel = false"
          >
            <ComplexFilterPanel
              ref="complexFilterPanel"
              :key="'complex-filter-panel-' + windowNo + '-' + tabIndex"
              :window-no="windowNo"
              :tab-index="tabIndex"
              :filter-schema="tab.filterSchema"
              @complex-search="advancedSearchOk"
            />
          </a-drawer>

          <div class="grid-item-row4">
            <div style="float: right">
              <AntdPagination
                ref="paginationRef"
                :pagination="pagination"
                @get-page-params="getPageParams"
              />
            </div>
          </div>
        </div>

        <template v-if="tab.subTabs != undefined">
          <div
            v-for="(subTab, index) in tab.subTabs"
            :key="'sub-tab-' + index"
            class="row"
          >
            <div class="col-md-12">
              <SubTabGridEdit
                :ref="'subTab' + subTab.tabIndex"
                :is-show-edit="canEdit"
                :tab="subTab"
                :parent-model-data="selectModelData"
                :parent-tab="tab"
                :window-no="windowNo"
                :tab-index="subTab.tabIndex"
                @save-view="$emit('saveView')"
                @save-record-event="saveRecordEvent"
                @refresh-parent="refreshParent"
                @property-changed="propertyChanged"
              />
            </div>
          </div>
        </template>

        <Modal
          v-model:show="modal"
          @ok="saveRecord"
          @cancel="discardChildChangedData"
        >
          <template #header> 请选择 </template>
          <div>您修改了子表格的数据，请先‘保存’数据，或者点击‘取消’按钮。</div>
        </Modal>

        <Modal v-model:show="modal1">
          <template #header> 无父页签/父表格的数据 </template>
          <div>请先选择父页签/父表格的数据</div>
        </Modal>

        <Modal v-model:show="modal3">
          <template #header> 数据校验失败 </template>
          <div>子表格的数据存在必填字段没有填写</div>
        </Modal>
      </div>

      <Modal
        v-model:show="modal2"
        :large="true"
        @ok="showAuditPanel = false"
        @cancel="showAuditPanel = false"
      >
        <template #header>
          记录信息{{ currIndex }}/{{ pagination.total }} - {{ tab.name }}
        </template>
        <TabAudit
          v-if="showAuditPanel"
          :tab="tab"
          :model-data="auditModelData"
        />
      </Modal>

      <Loading v-if="loading" />
    </a-collapse-panel>
  </a-collapse>
</template>

<script>
import Common from '../../common/Common.js';

import FieldUtil from '../../resource/dictionary/FieldUtil.js';
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import WindowServerUtil from '../../resource/dictionary/WindowServerUtil.js';

import ProcessReportResource from '../../api/dic/ProcessReportResource.js';
import CurdWindowEditResource from '../../api/dic/CurdWindowEditResource.js';
import Context from '../common/Context.js';
import Language from '../../common/Language.js';

import SimpleFilterPanel from '../filter/SimpleFilterPanel.vue';

import GridHeader from '../tabGridView/GridHeader.vue';
import GridBody from '../tabGridView/GridBody.vue';
import GridFooter from '../tabGridView/GridFooter.vue';
import GridColumnDef from '../tabGridView/GridColumnDef.vue';
import GridColumnDefUtil from '../tabGridView/GridColumnDef.js';
import TabButton from '../tabView/TabButton.vue';

import TabAudit from '../tabView/TabAudit.vue';
import ComplexFilterPanel from '../filter/ComplexFilterPanel.vue';
import JsUtil from '../../common/JsUtil.js';
import { Notify, Uuid } from 'pc-component-v3';
import { LeftOutlined, RightOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
export default {
  name: 'SubTabGridEdit',

  components: {
    TabButton,
    GridHeader,
    GridBody,
    GridFooter,
    GridColumnDef,
    TabAudit,
    SimpleFilterPanel,
    ComplexFilterPanel,
    LeftOutlined,
    RightOutlined,
    ExclamationCircleOutlined,
    Modal,
  },

  props: {
    windowNo: {
      type: String,
      default: null,
    },
    tabIndex: {
      type: Number,
      default: null,
    },
    tab: {
      type: Object,
      default: function () {
        return null;
      },
    },
    parentTab: {
      type: Object,
      default: function () {
        return null;
      },
    },
    parentModelData: {
      type: Object,
      default: function () {
        return null;
      },
    },
    curdWindowFunctionAccess: {
      type: Object,
      default: function () {
        return null;
      },
    },
    isShowEdit: {
      type: Boolean,
      default: null,
    },
    jsUrl: {
      type: String,
      default: null,
    },
    isChineseEnglish: {
      type: Boolean,
      default: null,
    },
  },

  emits: [
    'saveView',
    'changeRootParentModelData',
    'saveRecordEvent',
    'propertyChanged',
  ],

  data: function () {
    this.Language = Language;
    return {
      tabGridFields: WindowClientUtil.getGridField(this.tab), //字段
      modelDatas: [],
      collapse: false,
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        // last_page: 5, // required
      },
      sortStr: '', // 排序
      selectModelData: {}, // 当前选择的ModelData
      prepareSelectModelData: {}, // 选中ModelData，未生效前的数据
      sortStyle: ' ASC', //排列方式
      uuid: Uuid.createUUID(), // 创建UUID
      scrollObject: {
        // 表格滚动
        tableOutDivUuid1: Uuid.createUUID(), // table 的 uuid
        tableOutDivUuid2: Uuid.createUUID(), // table 外部 DIV 的 uuid
      },
      multipleSelect: true,
      showAuditPanel: false,
      auditModelData: {},
      currIndex: 0,
      showComplexFilterPanel: false, // 是否显示复杂查询面板
      parentModelDataClone: null,
      loading: false,
      modal: false,
      modal1: false,
      modal2: false,
      modal3: false,
      activeKey: ['1'],
      searchText: '', // 简单过滤条件
    };
  },

  computed: {
    tableWidth: function () {
      // 第一列和第二列
      var totalWidth = 30 + 95;
      if (this.tabGridFields != null && this.tabGridFields.length != 0) {
        this.tabGridFields.forEach(function (gridFieldItem) {
          // 列显示的时候才计算宽度
          if (gridFieldItem.visible) {
            totalWidth += Number(gridFieldItem.width);
          }
        });
      }
      return totalWidth + 'px';
    },

    /**
     * 表格是否可编辑
     * @return
     */
    canEdit: function () {
      if (this.isShowEdit == false) {
        return false;
      }
      if (
        this.tab != undefined &&
        this.tab.tabDataSource != null &&
        this.tab.tabDataSource.readOnly == false
      ) {
        return true;
      }
      return false;
    },

    parentModelDataStringCopy() {
      return JSON.stringify(this.parentModelData);
    },
  },

  watch: {
    parentModelDataStringCopy: {
      handler: function (newValue, oldValue) {
        if (newValue != oldValue) {
          this.parentModelDataClone = JSON.parse(newValue);
        }
      },
      deep: true,
    },

    // 监控父页签的数据，如果父页签的数据发生改变，则更新列表
    parentModelData: {
      handler: function (newValue, oldValue) {
        let needQuery = true;
        console.log(newValue);
        if (newValue != null && newValue.restore == true) {
          needQuery = false;
        }

        if (needQuery) {
          this.$nextTick(function () {
            this.queryGridData();
          });
        }
      },
      immediate: true,
    },

    showComplexFilterPanel: function (newValue, oldValue) {
      localStorage.setItem(
        'showComplexFilterPanel',
        newValue ? 'true' : 'false',
      );
    },
  },

  mounted: function () {
    var _self = this;

    console.log('SubTabGridEdit mounted.');

    this.tabGridFields = WindowClientUtil.getGridField(this.tab);
    GridColumnDefUtil.restoreTabGridFieldDef(
      this.windowNo,
      this.tabIndex,
      this.tabGridFields,
    );
    _self.showComplexFilterPanel =
      localStorage.getItem('showComplexFilterPanel') == 'true';
  },

  methods: {
    getContext: Context,

    auditData: function () {
      var _self = this;
      var selectedDatas = [];
      _self.modelDatas.forEach(function (modelData) {
        if (modelData.select == true) {
          selectedDatas.push(modelData);
        }
      });
      if (selectedDatas.length == 0 || selectedDatas.length > 1) {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.subTabGridEdit.describe1'),
          true,
        );
      } else {
        _self.auditModelData = selectedDatas[0];

        var index = _self.modelDatas.indexOf(_self.auditModelData);
        if (index < 0) {
          index = 1;
        }
        _self.currIndex =
          (_self.pagination.current_page - 1) * _self.pagination.per_page +
          1 +
          index;
        _self.showAuditPanel = true;
        _self.modal2 = true;
      }
    },

    // 改变多选/单选
    changeSelectMode: function (val) {
      this.multipleSelect = val;
    },

    newModelData: function () {
      var _self = this;
      // 如果 parentModelData 无数据，则不允许新建
      if (
        this.parentModelData == undefined ||
        this.parentModelData.id == undefined
      ) {
        this.modal1 = true;
      } else {
        _self.loading = true;
        WindowServerUtil.newModelData(
          _self.windowNo,
          _self.tabIndex,
          null,
          function (response) {
            _self.loading = false;

            if (response.errorCode != 0) {
              Notify.error('数据新建异常', response.errorMessage, false);
              return;
            }
            let modelData = response.data;

            modelData.editMode = true;
            modelData.visible = true;
            modelData.tabIndex = _self.tabIndex;
            modelData.changed = true;
            _self.modelDatas[_self.modelDatas.length] = modelData;
          },
          function () {
            _self.loading = false;
          },
        );
      }
    },

    /**
     * 将fieldValue添加到新的modelData中
     * @param {Object} fieldName
     * @param {Object} fieldValue
     */
    newModelDataFieldValue: function (fieldName, fieldValue) {
      var _self = this;
      // 如果 parentModelData 无数据，则不允许新建
      if (
        this.parentModelData == undefined ||
        this.parentModelData.id == undefined
      ) {
        this.modal1 = true;
      } else {
        _self.loading = true;
        WindowServerUtil.newModelData(
          _self.windowNo,
          _self.tabIndex,
          null,
          function (response) {
            _self.loading = false;

            if (response.errorCode != 0) {
              Notify.error('数据新建异常', response.errorMessage, false);
              return;
            }
            let modelData = response.data;

            modelData.editMode = true;
            modelData.visible = true;
            modelData.tabIndex = _self.tabIndex;
            modelData.data[fieldName] = fieldValue;
            _self.modelDatas[_self.modelDatas.length] = modelData;
          },
          function () {
            _self.loading = false;
          },
        );
      }
    },

    gridSizeSelect: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
      // 刷新界面
      // this.queryGridData();
    },

    // 页数改变
    getPageParams: function (page, pageSize) {
      this.pagination.current_page = page;
      this.pagination.per_page = pageSize;
      this.queryGridData();
    },

    // 改变表格行元素的编辑状态
    editRecord: function (modelData, fieldItems) {
      if (modelData.visible == null) {
        modelData.visible = true;
      }
      if (modelData.editMode == undefined) {
        modelData.editMode = true;
      } else {
        var flag = true;
        if (modelData.editMode == true && fieldItems) {
          fieldItems.forEach(function (fieldItem) {
            if (fieldItem.mandatory == true) {
              if (
                FieldUtil.isSelectType(fieldItem) ||
                FieldUtil.isSearchType(fieldItem)
              ) {
                var idValue =
                  modelData.data == undefined ||
                  modelData.data[fieldItem.fieldName] == undefined
                    ? undefined
                    : modelData.data[fieldItem.fieldName].id;
                if (idValue == undefined || idValue == '' || idValue < 1) {
                  flag = false;
                }
              } else {
                var stringValue =
                  modelData.data == undefined ||
                  modelData.data[fieldItem.fieldName] == undefined
                    ? ''
                    : modelData.data[fieldItem.fieldName].displayValue[0];
                if (stringValue == undefined || stringValue === '') {
                  flag = false;
                }
              }
            }
          });
          if (!flag) {
            this.modal3 = true;
            return;
          }
        }
        modelData.editMode = !modelData.editMode;
      }
      modelData.changed = true;
      var index = this.modelDatas.indexOf(modelData);
      if (index != -1) {
        this.modelDatas[index] = modelData;
      }
    },

    // 值改变事件
    valueChanged: function (event, modelData, index) {
      var _self = this;
      var gridFieldItem = event.gridFieldItem;
      var newFieldValue = event.newFieldValue;
      var oldFieldValue = modelData.data[gridFieldItem.fieldName];
      if (FieldUtil.isFieldValueEqual(newFieldValue, oldFieldValue) == false) {
        modelData.data[gridFieldItem.fieldName] = newFieldValue;
        // modelData.data[gridFieldItem.fieldName] = newFieldValue;
        if (
          gridFieldItem.calloutProcessReportNo != undefined &&
          gridFieldItem.calloutProcessReportNo != null
        ) {
          _self.callout(gridFieldItem.calloutProcessReportNo, modelData, index);
        }

        if (
          gridFieldItem.calloutLogical != undefined &&
          gridFieldItem.calloutLogical != null &&
          gridFieldItem.calloutLogical != ''
        ) {
          _self.executeCalloutJs(
            gridFieldItem,
            gridFieldItem.calloutLogical,
            modelData,
          );
        }

        // 遍历所有的字段，判断是否有动态约束
        // 如果有关联的动态约束，则清空字段
        var fieldName0 = gridFieldItem.fieldName;
        _self.tabGridFields.forEach(function (item) {
          var fieldName1 = item.fieldName;
          var dynamicValidFields = item.dynamicValidFields;
          if (
            fieldName0 != fieldName1 &&
            dynamicValidFields != undefined &&
            dynamicValidFields.indexOf(fieldName0) >= 0
          ) {
            modelData.data[fieldName1].id = undefined;
            if (modelData.data[fieldName1].displayValue != undefined) {
              modelData.data[fieldName1].displayValue.splice(
                0,
                modelData.data[fieldName1].displayValue.length,
              );
            } else {
              modelData.data[fieldName1].displayValue = [];
            }
            _self.modelDatas[index] = modelData;
          }
        });
      }
    },

    /**
     * 执行JS Callout
     */
    executeCalloutJs: function (gridFieldItem, scriptText, modelData) {
      var _self = this;

      let functionName =
        gridFieldItem.fieldName.replace('.', '_') + '_calloutjs';
      let exeuteFunction = function () {
        let actions = {
          changeParentModelData: _self.changeParentModelData,
          modelDatas: _self.modelDatas,
        };
        let context = new _self.getContext(modelData, actions);
        try {
          _self[functionName](context);
        } catch (error) {
          console.error(error);
          Notify.error(
            '数据字典定义异常',
            '【' +
              scriptText +
              '】Callout前端逻辑定义异常,请联系管理员检查数据字典的定义。',
            false,
          );
        }
      };

      if (_self[functionName] == null) {
        // 执行服务端的脚本
        const jsUrl = _self.jsUrl;
        if (jsUrl == null || jsUrl == undefined) {
          Notify.error(
            '数据字典定义异常',
            '【' +
              scriptText +
              '】Callout前端逻辑的JS文件不存在,请联系管理员检查数据字典是否存在JS文件。',
            false,
          );
          return;
        }
        let promise = JsUtil.dynamicLoadJsFunction(jsUrl, scriptText);
        promise.then(
          targetFunction => {
            if (targetFunction == null) {
              Notify.error(
                '数据字典定义异常',
                '【' +
                  scriptText +
                  '】Callout前端逻辑定义异常,请联系管理员检查数据字典的定义。',
                false,
              );
              return;
            }

            _self[functionName] = targetFunction;
            exeuteFunction();
          },
          errorData => {
            console.error(errorData);
          },
        );
      } else {
        exeuteFunction();
      }
    },

    /**
     * 修改父页签的数据
     */
    changeParentModelData: function (fieldName, fieldValue) {
      let param = {
        fieldName: fieldName,
        fieldValue: fieldValue,
      };
      this.$emit('changeRootParentModelData', param);
    },

    /**
     * callout
     * @param  {[type]} calloutProcessReportNo [description]
     * @return {[type]}                  [description]
     */
    callout: function (calloutProcessReportNo, modelData, index, isBtn) {
      var _self = this;
      if(isBtn) _self.loading = true;
      // 查询流程和报表的定义
      ProcessReportResource.uniqueByNo(calloutProcessReportNo).then(
        response => {
          if (response.errorCode != 0) {
            Notify.error('流程和报表获取错误', response.errorMessage, true);
            return;
          }
          const successData = response.data;
          if (successData == null) {
            return;
          }

          // 执行服务端的脚本
          ProcessReportResource.runCallout(
            calloutProcessReportNo,
            modelData,
          ).then(
            successData => {
              if (successData && successData.modelData) {
                var newModelData = successData.modelData;
                newModelData.editMode = modelData.editMode;
                newModelData.visible = modelData.visible;
                _self.modelDatas[index] = newModelData;
              }
              _self.loading = false;
            },
            errorData => {
              _self.loading = false;
              Common.processException(errorData);
            },
          );
        },
        errorData => {
          _self.loading = false;
          Common.processException(errorData);
        },
      );
    },

    /**
     * 获取子页签所有的数据
     */
    getAllModelData: function () {
      var _self = this;
      // 发生改变的modelData
      var allModelDatas = [];
      this.modelDatas.forEach(function (tempModelData) {
        allModelDatas.push(tempModelData);
      });
      return allModelDatas;
    },

    // 获取发生改变的数据
    getChangedModelData: function () {
      var _self = this;
      // 发生改变的modelData
      var changedModelDatas = [];
      this.modelDatas.forEach(function (tempModelData) {
        if (tempModelData === _self.selectModelData) {
          var subTabChangedData = _self.getSubTabChangedData();
          if (subTabChangedData.length > 0) {
            tempModelData.changed = true;
            tempModelData.saveDatas = subTabChangedData;
          } else {
            tempModelData.saveDatas = null;
          }
        }

        if (tempModelData.changed == true) {
          changedModelDatas.push(tempModelData);
        }
      });
      return changedModelDatas;
    },

    // 获取子页签发生改变的数据
    getSubTabChangedData: function () {
      var subTabChangedRecords = [];
      if (this.tab.subTabs != undefined) {
        for (var index = 0; index < this.tab.subTabs.length; index++) {
          var subTabId = 'subTab' + this.tab.subTabs[index].tabIndex;
          var modelDatas = this.$refs[subTabId][0].getChangedModelData();
          if (modelDatas != undefined && modelDatas.length > 0) {
            modelDatas.forEach(function (modelData) {
              subTabChangedRecords.push(modelData);
            });
          }
        }
      }
      return subTabChangedRecords;
    },

    // 删除数据
    deleteRecord: function (modelData, isAlert) {
      var _self = this;
      var index = this.modelDatas.indexOf(modelData);
      if (index == -1) {
        return;
      }

      if (isAlert) {
        // 获取数据改动的数量
        var changedCount = 0;
        for (var i = 0, len = _self.modelDatas.length; i < len; i++) {
          if (_self.modelDatas[i].changed == true) {
            changedCount++;
          }
        }
        var message = '';
        if (changedCount > 0) {
          message = _self.$t('lang.subTabGridEdit.describe2', {
            changedCount: changedCount,
          });
        }

        message =
          message +
          _self.$t('lang.subTabGridEdit.someWhatThree');
        Modal.confirm({
          title: _self.$t('lang.subTabGridEdit.deleteConfirmation'),
          icon: createVNode(ExclamationCircleOutlined),
          content: message,
          okText: _self.$t('lang.subTabGridEdit.determine'),
          okType: 'danger',
          cancelText: _self.$t('lang.subTabGridEdit.cancel'),
          onOk() {
            _self.deleteRecord(modelData,false);
          },
          onCancel() {
            console.log('Cancel');
          },
        });
        return;
      }

      if (modelData.id < 0) {
        this.modelDatas.splice(index, 1);
        return;
      }

      modelData.deleted = true;
      modelData.changed = true;
    },

    // 删除选择的数据(多删)
    deleteRecords: function (isAlert) {
      var _self = this;
      // 待删除的数据集合
      var dataPrepareDelete = [];
      _self.modelDatas.forEach(function (modelData) {
        if (modelData.select == true) {
          dataPrepareDelete.push(modelData);
        }
      });

      if (dataPrepareDelete.length == 0) {
        Notify.error(
          _self.$t('lang.subTabGridEdit.noDataSelected'),
          _self.$t('lang.subTabGridEdit.describe3'),
          false,
        );
        return;
      }

      if (isAlert) {
        Modal.confirm({
          title: _self.$t('lang.subTabGridEdit.deleteConfirmation'),
          icon: createVNode(ExclamationCircleOutlined),
          content: _self.$t('lang.subTabGridEdit.someWhatOne') +
            dataPrepareDelete.length +
            _self.$t('lang.subTabGridEdit.someWhatTwo'),
          okText: _self.$t('lang.subTabGridEdit.determine'),
          okType: 'danger',
          cancelText: _self.$t('lang.subTabGridEdit.cancel'),
          onOk() {
            _self.deleteRecords(false);
          },
          onCancel() {
            console.log('Cancel');
          },
        });
        return;
      }

      for (var index = 0; index < dataPrepareDelete.length; index++) {
        if (dataPrepareDelete[index].id < 0) {
          var index1 = _self.modelDatas.indexOf(dataPrepareDelete[index]);
          if (index1 >= 0) {
            _self.modelDatas.splice(index1, 1);
          }
        } else {
          dataPrepareDelete[index].deleted = true;
          dataPrepareDelete[index].changed = true;
        }
      }
    },

    /**
     * 子页签触发父页签刷新
     * @return {[type]} [description]
     */
    refreshParent: function () {
      var _self = this;
      //   _self.queryGridData();
      _self.$emit('processExecuteFinish');
    },

    // 根据查询参数获取数据模型
    queryGridData: function () {
      var _self = this;

      // 如果没有父页签的数据，则清空界面
      if (
        _self.parentModelData == undefined ||
        _self.parentModelData.id == undefined
      ) {
        _self.modelDatas.splice(0, _self.modelDatas.length);
        _self.selectModelData = {};
        return;
      }

      // 简单过滤条件

      // 简单过滤条件
      let simpleFilterCondition = null;
      let filterParams = null;
      if (_self.showComplexFilterPanel == true) {
        if (_self.$refs.complexFilterPanel != null) {
          filterParams = _self.$refs.complexFilterPanel.getFilterParams();
        }
      } else {
        simpleFilterCondition = _self.searchText;
      }

      // 首先判断是否有未保存的数据
      // 如果有未保存的数据，则不能从服务器上进行查询
      for (let row = 0, len = _self.modelDatas.length; row < len; row++) {
        let rowData = _self.modelDatas[row];
        if (rowData.id < 0 && rowData.deleted != true) {
          // 数据未保存，且未删除
          let rowDataStr = JSON.stringify(rowData);
          if (rowDataStr.indexOf(simpleFilterCondition) >= 0) {
            rowData.visible = true;
          } else {
            rowData.visible = false;
          }
        }
        // 如果表格数据已经保存过了，那么直接移除掉。
        if (rowData.id > 0) {
          _self.modelDatas.splice(row, 1);
          row--;
          len--;
        }
      }

      var tabQueryParam = {
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        windowNo: _self.windowNo,
        tabIndex: _self.tabIndex,
        parentColumnId:
          _self.parentModelData == undefined
            ? undefined
            : _self.parentModelData.id,
        filterParams: filterParams,
        simpleFilterCondition: simpleFilterCondition,
        sortStr: _self.sortStr,
      };
      _self.loading = true;

      $.ajax({
        url: Common.getApiURL('CurdWindowResource/tabData'),
        type: 'post',
        contentType: 'application/json',
        data: JSON.stringify(tabQueryParam),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (response) {
          _self.loading = false;
          if (response.errorCode != 0) {
            Notify.error('Error', response.errorMessage, false);
            return;
          }
          const data = response.data;
          var modelDatas = data.dataList;
          WindowClientUtil.setViewDisplayAttribute(
            modelDatas,
            'editMode',
            false,
          );
          WindowClientUtil.setViewDisplayAttribute(modelDatas, 'select', false);
          WindowClientUtil.setViewDisplayAttribute(modelDatas, 'visible', true);

          //绑定数据模型信息
          //绑定数据模型信息
          modelDatas.forEach(function (modelDataItem) {
            _self.modelDatas.push(modelDataItem);
          });
          _self.pagination.total = data.totalSize;
          // _self.pagination.last_page = Math.ceil(
          //   data.totalSize / data.range.length,
          // );

          // 恢复选定的数据
          if (modelDatas == undefined || modelDatas.length == 0) {
            _self.selectModelData = {};
          } else {
            if (
              _self.selectModelData != undefined &&
              _self.selectModelData.id != undefined
            ) {
              var lastSelectedId = _self.selectModelData.id;
              modelDatas.forEach(function (tempData) {
                if (tempData.id == lastSelectedId) {
                  _self.selectModelData = tempData;
                  _self.selectModelData.select = true;
                }
              });
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 点击了ModelData属性
    clickModelData: function (modelData) {
      var _self = this;
      var currentIsSelect = modelData.select;
      if (!_self.multipleSelect) {
        _self.modelDatas.forEach(function (item) {
          item.select = false;
        });
      }
      _self.prepareSelectModelData = modelData;
      _self.prepareSelectModelData.select = currentIsSelect;
      _self.checkChildrenTabIsChanged();
    },

    // 检查子页签数据是否发生改变
    checkChildrenTabIsChanged: function () {
      // 获取子页签的数据
      var changedModelDatas = this.getSubTabChangedData();
      if (changedModelDatas != undefined && changedModelDatas.length > 0) {
        // 弹出对话框,是否保存数据，或者放弃
        // 如果点击保存数据，则触发父页签保存数据
        this.modal = true;
        // 如果点击放弃，则放弃页签改变的数据
      } else {
        // 无改变的数据
        this.discardChildChangedData();
      }
    },

    // 冒泡传递保存事件
    saveRecord: function () {
      this.prepareSelectModelData.changed = true;
      this.prepareSelectModelData = {};
      this.$emit('saveRecordEvent', this.parentModelData);
    },

    onSort: function (gridFieldItem) {
      var _self = this;

      var hasChangedModelData = _self.hasChangedModelData();

      // 存在未保存的数据
      if (hasChangedModelData == true) {
        Notify.error(
          _self.$t('lang.subTabGridEdit.describe4'),
          _self.$t('lang.subTabGridEdit.describe5'),
          false,
        );
        return;
      }

      // add by jack 20241108
      // 如果是操作列不进行排序
      if (gridFieldItem.fieldName == null || gridFieldItem.fieldName == '-') {
        return;
      }

      if (
        gridFieldItem.entityFieldNames != undefined &&
        gridFieldItem.entityFieldNames.length > 0
      ) {
        _self.sortStr =
          gridFieldItem.fieldName +
          '.' +
          gridFieldItem.entityFieldNames[gridFieldItem.entityFieldIndex] +
          _self.sortStyle;
      } else {
        _self.sortStr = gridFieldItem.fieldName + _self.sortStyle;
      }

      _self.queryGridData();
      _self.sortStyle = _self.sortStyle == ' ASC' ? ' DESC' : ' ASC';
    },

    /**
     * 判断是否存在未保存的数据
     * @return {Boolean} [description]
     */
    hasChangedModelData: function () {
      var _self = this;
      // 检查是否存在未保存的数据
      var hasChangedModelData = false;
      for (var i = 0, len = _self.modelDatas.length; i < len; i++) {
        if (_self.modelDatas[i].changed == true) {
          hasChangedModelData = true;
          break;
        }
        if (_self.modelDatas[i].id < 0) {
          hasChangedModelData = true;
          break;
        }
      }

      return hasChangedModelData;
    },

    saveRecordEvent: function (modelData) {
      modelData.changed = true;
      this.$emit('saveRecordEvent', this.parentModelData);
    },

    // 放弃子页签修改的数据
    discardChildChangedData: function () {
      this.prepareSelectModelData.select = !this.prepareSelectModelData.select;
      if (this.prepareSelectModelData.select) {
        this.selectModelData = this.prepareSelectModelData;
      } else {
        this.selectModelData = {};
      }
      this.prepareSelectModelData = {};
    },

    // 显示状态发生改变
    propertyChanged: function (gridFieldItem) {
      GridColumnDefUtil.saveGridFieldDef(
        this.windowNo,
        this.tabIndex,
        gridFieldItem,
      );
      GridColumnDefUtil.restoreTabGridFieldDef(
        this.windowNo,
        this.tabIndex,
        this.tabGridFields,
      );
      this.$emit('propertyChanged', gridFieldItem);

      /* WindowClientUtil.gridFieldItemPropertyChanged(gridFieldItem);
                   this.tabGridFields.forEach(function (item) {
                       WindowClientUtil.restoreGridFieldItemAttr(item);
                   });*/
    },

    performValidate: function () {
      var _self = this;
      var validateResults = [];
      if (this.$refs.gridBody1 != undefined) {
        for (
          var i = 0;
          (i < this.$refs.gridBody1.length) & (i < _self.modelDatas.length);
          i++
        ) {
          if (_self.modelDatas[i].changed == true) {
            var validateResults1 = this.$refs.gridBody1[i].performValidate();
            validateResults = validateResults.concat(validateResults1);
          }
        }
        var validateResults2 = this.getSubTabValidePromise();
        validateResults = validateResults.concat(validateResults2);
      }
      return validateResults;
    },

    // 获取子页签发生改变的数据
    getSubTabValidePromise: function () {
      var validateResults = [];
      if (this.tab.subTabs != undefined) {
        for (var index = 0; index < this.tab.subTabs.length; index++) {
          var subTabId = 'subTab' + this.tab.subTabs[index].tabIndex;
          var validatePromises = this.$refs[subTabId][0].performValidate();
          validateResults = validateResults.concat(validatePromises);
        }
      }
      return validateResults;
    },

    // 添加 modelData
    addModelData: function (modelData) {
      // 如果 parentModelData 无数据，则不允许新建
      this.modelDatas[this.modelDatas.length] = modelData;
      if (modelData.saveDatas != undefined && modelData.saveDatas.length > 0) {
        modelData.saveDatas.forEach(function (saveData) {
          // 恢复子页签的数据
          var subTabId = 'subTab' + saveData.tabIndex;
          this.$refs[subTabId][0].addModelData(saveData);
        });
      }
    },

    /**
     * 替换modeldatas数据
     */
    replaceModelDatas: function (modelDatas) {
      let _self = this;
      this.modelDatas.splice(0, this.modelDatas.length);
      modelDatas.forEach(modelData => {
        _self.addModelData(modelData);
      });
    },

    /**
     * 全选/取消全选
     * @param  {Boolean} val 状态
     * @return {void}
     */
    selectAll: function (val) {
      var _self = this;
      if (_self.multipleSelect) {
        _self.modelDatas.forEach(function (item) {
          item.select = val;
        });
      }
    },

    /**
     * 点击编辑全部按钮
     */
    editAllTabData: function () {
      var _self = this;
      _self.modelDatas.forEach(function (item) {
        item.editMode = true;
        item.changed = true;
        item.visible = true;
      });
    },

    /**
     * 简单搜索
     */
    simpleSearch: function (filterParams) {
      var _self = this;
      _self.pagination.current_page = 1;
      _self.queryGridData();
    },

    /**
     * 高级搜索
     */
    advancedSearchOk: function () {
      var _self = this;
      _self.pagination.current_page = 1;
      _self.queryGridData();
    },

    /**
     * 执行Callout
     */
    executeCallout: function (gridFieldItem, modelData, index, isBtn) {
      var _self = this;
      if (gridFieldItem.calloutProcessReportNo != null) {
        _self.callout(gridFieldItem.calloutProcessReportNo, modelData, index, isBtn);
      }
    },

    /**
     * 修改根ModelData的字段数据
     * @param { String } fieldName 字段名称
     * @param { com.leanwo.prodog.restful.base.model.FieldValue } fieldValue 字段的值
     * @author YangZhiJie 20211012
     *
     */
    changeRootParentModelData: function (fieldName, fieldValue) {
      this.$emit('changeRootParentModelData', {
        fieldName: fieldName,
        fieldValue: fieldValue,
      });
    },
  },
};
</script>

<style scoped>
.fixed-table {
  table-layout: fixed;
}

.toolbar-button-group-left {
  float: left;
}

.toolbar-button-group-right {
  float: right;
}

.table-tr-eidt {
  height: 38px;
}

.table-toolbar {
  width: 100%;
}

.m-row {
  margin-bottom: 15px;
}

.a-audit {
  cursor: pointer;
}

th {
  background-color: #f7f7f7;
}
.toggle-filter-btn {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px;
  transition: all 0.3s;
}

.toggle-filter-btn:hover {
  color: var(--ant-primary-color);
  background-color: rgba(0, 0, 0, 0.04);
}

:deep(.anticon) {
  font-size: 12px;
}
</style>

<style scoped>
.grid-container {
  margin-top: 10px;
  display: grid;
  grid-template-columns: auto 17px 0px;
  grid-template-rows: 40px 40px auto 40px;
  gap: 5px;
  justify-items: stretch;
  align-items: stretch;
}

.grid-item-row1 {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 1;
  grid-column-end: 4;
}

.grid-item-row2 {
  grid-row-start: 2;
  grid-row-end: 3;
  grid-column-start: 1;
  grid-column-end: 4;
}

.grid-item-row3-column1 {
  grid-row-start: 3;
  grid-row-end: 4;
  grid-column-start: 1;
  grid-column-end: 2;
  overflow: auto;
}

.grid-item-row3-column2 {
  grid-row-start: 3;
  grid-row-end: 4;
  grid-column-start: 2;
  grid-column-end: 3;
  overflow: hidden;

  border: 1px solid #ddd;
  border-radius: 4px;
}

.grid-item-row4 {
  grid-row-start: 4;
  grid-row-end: 5;
  grid-column-start: 1;
  grid-column-end: 4;
}

.sub-table-container {
  overflow: auto;
  margin-left: -15px;
}
</style>