<template>
  <div>
    <a-space
      v-if="
        showTabDto != undefined &&
          showTabDto.tabGridView &&
          tabButtons != undefined
      "
      style="margin-right: 8px"
    >
      <template v-for="item in tabButtons" :key="item.id">
        <a-button
          v-if="
            item.subMenu != true &&
              (viewType == 'Grid' ||
                (viewType == 'EditForm' && item.editMode == true) ||
                (viewType == 'Form' && item.editMode != true)) &&
              item.invisible == false
          "
          @click="execute(item)"
        >
          {{ Language.getNameTrl($i18n.locale, item) }}
        </a-button>
      </template>
    </a-space>

    <a-space>
      <a-button v-if="'EditForm' != viewType" @click="exportConfirm">
        <template #icon>
          <ExportOutlined />
        </template>
        {{ $t("lang.tabButton.export") }}
      </a-button>
      <a-button
        v-if="mWindow && mWindow.dataTemplateIds != undefined"
        @click="importData"
      >
        <template #icon>
          <ImportOutlined />
        </template>
        {{ $t("lang.tabButton.import") }}
      </a-button>
      <a-button v-if="'Form' == viewType || 'Grid' == viewType" @click="notify">
        <template #icon>
          <MessageOutlined />
        </template>
        {{ $t("lang.tabButton.notice") }}
      </a-button>

      <a-button v-if="'EditForm' != viewType && isOpen" @click="documentOpen">
        <template #icon>
          <FileDoneOutlined />
        </template>

        {{ $t("lang.tabButton.open") }}
      </a-button>
      <a-button v-if="'EditForm' != viewType && isClose" @click="documentClose">
        <template #icon>
          <FileExcelOutlined />
        </template>

        {{ $t("lang.tabButton.close") }}
      </a-button>

      <a-dropdown v-if="tabButtons && tabButtons.length > 3" :trigger="['click']">
        <template #overlay>
          <a-menu>
            <template v-for="(item, index) in tabButtons" :key="index">
              <a-menu-item
                v-if="
                  showTabDto.tabGridView &&
                    item.subMenu == true &&
                    (viewType == 'Grid' ||
                      (viewType == 'EditForm' && item.editMode == true) ||
                      (viewType == 'Form' && item.editMode != true)) &&
                    item.invisible == false
                "
                @click="execute(item)"
              >
                {{ Language.getNameTrl($i18n.locale, item) }}
              </a-menu-item>
            </template>
          </a-menu>
        </template>
        <a-button>
          {{ $t("lang.tabButton.other") }}
          <CaretDownOutlined />
        </a-button>
      </a-dropdown>

      <template v-else>
        <template v-for="item in tabButtons" :key="item.id">
          <a-button
            v-if="
              showTabDto.tabGridView &&
                item.subMenu == true &&
                (viewType == 'Grid' ||
                  (viewType == 'EditForm' && item.editMode == true) ||
                  (viewType == 'Form' && item.editMode != true)) &&
                item.invisible == false
            "
            @click="execute(item)"
          >
            {{ Language.getNameTrl($i18n.locale, item) }}
          </a-button>
        </template>
      </template>
    </a-space>

    <a-modal
      v-model:open="modal"
      width="100%"
      :title="$t('lang.tabButton.executeResult')"
      @ok="modal = false"
    >
      <ProcessReportResultPreview
        v-if="
          processReportResult != null &&
            (processReportResult.reportResults != null ||
              processReportResult.processResult != null)
        "
        :process-report-result="processReportResult"
        :pdf-only="false"
        :excel-only="false"
      />
    </a-modal>

    <a-modal
      v-model:open="notificationModal"
      :title="$t('lang.tabButton.sendNotice')"
    >
      <NotificationPanel ref="notificationPanel" />

      <template #footer>
        <a-button @click="sendNotification">
          {{ $t("lang.tabButton.send") }}
        </a-button>
        <a-button @click="cancelNotification">
          {{ $t("lang.tabButton.cancel") }}
        </a-button>
      </template>
    </a-modal>

    <Loading v-if="loading" />
  </div>

  <!-- 资产卡片主卡转副卡 -->
  <a-modal
    v-model:open="cardConversionOpen"
    width="75%"
    :mask-closable="false"
    :footer="null"
    title="选择附属主卡"
    @cancel="cardConversionOpen = false"
    @ok="cardConversionOpen = false"
  >
    <InfoWindow
      v-if="cardConversionOpen"
      ref="infoRef"
      :info-window-no="infoWindowNo"
      :is-search-widget="true"
    >
      <template #customButton>
        <a-button type="primary" @click="getSelectModelData">
          确认转为附卡
        </a-button>
      </template>
    </InfoWindow>
  </a-modal>
</template>

<script>
import Common from '../../common/Common.js';
import DownloadService from '../../resource/file/DownloadService.js';
import CustomerWindowResource from '../../api/dic/CustomerWindowResource.js';
import HtmlWindowResource from '../../api/dic/HtmlWindowResource.js';
import ProcessReportResource from '../../api/dic/ProcessReportResource.js';
import UserStorageResource from '../../api/base/UserStorageResource.js';
import Language from '../../common/Language.js';
import { Notify, Uuid } from 'pc-component-v3';
import dayjs from 'dayjs';
import { turnMasterCard } from '../../api/finance/AssetCard.js';
import NotificationPanel from '../../customer/NotificationPanel.vue';
import { IFrameUtil } from 'pc-component-v3';
import {
  ExportOutlined,
  ImportOutlined,
  MessageOutlined,
  FileDoneOutlined,
  FileExcelOutlined,
  CaretDownOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

export default {
  components: {
    NotificationPanel,
    ExportOutlined,
    ImportOutlined,
    MessageOutlined,
    FileDoneOutlined,
    FileExcelOutlined,
    CaretDownOutlined,
  },

  props: {
    showTabDto: {
      type: Object,
      default: function () {
        return null;
      },
    },
    parentModelData: {
      type: Object,
      default: function () {
        return null;
      },
    },
    modelData: {
      type: Object,
      default: function () {
        return null;
      },
    },
    modelDatas: {
      type: Array,
      default: function () {
        return null;
      },
    },
    uuid: {
      type: String,
      default: null,
    },
    viewType: {
      type: String,
      default: null,
    },
    type: {
      type: String,
      default: null,
    },
    simpleFilterParams: {
      type: String,
      default: null,
    },
    complexFilterParams: {
      type: Array,
      default: () => {
        return [];
      },
    },
    mWindow: {
      type: Object,
      default: function () {
        return null;
      },
    },
    tabButtons: {
      type: Array,
      default: function () {
        return null;
      },
    },
    curdWindowFunctionAccess: {
      type: Object,
      default: function () {
        return null;
      },
    },
  },
  emits: ['saveView', 'processExecuteFinish', 'modelDataChanged'],

  data: function () {
    this.Language = Language;
    return {
      processReportResult: {},
      openWindow: null,
      loading: false,
      modal: false,
      notificationModal: false,
      cardConversionOpen: false,
      infoWindowNo: '20240922_095937',
    };
  },

  computed: {
    isShow: function () {
      if (this.showTabDto == undefined) {
        return false;
      } else if (this.tabButtons == undefined) {
        return false;
      } else if (this.tabButtons.length == 0) {
        return false;
      }
      return true;
    },
    /**
     * 判断打开按钮是否显示（单据处于已审批状态且关闭时间不为空）
     * @author LeiGuoXian
     * @date 2021-09-26
     */
    isOpen: function () {
      var _self = this;
      if (_self.parentModelData != undefined) {
        if (
          _self.parentModelData.data != undefined &&
          _self.parentModelData.data.documentStatus != undefined &&
          _self.parentModelData.data.documentStatus.displayValue[0] ==
            'APPROVED' &&
          _self.parentModelData.data.closeDate != undefined
        ) {
          return true;
        } else {
          return false;
        }
      } else {
        if (
          _self.modelData != undefined &&
          _self.modelData.data != undefined &&
          _self.modelData.data.documentStatus != undefined &&
          _self.modelData.data.documentStatus.displayValue[0] == 'APPROVED' &&
          _self.modelData.data.closeDate != undefined &&
          _self.modelData.data.closeDate.displayValue.length != 0
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    /**
     * 判断关闭按钮是否显示（单据处于已审批状态且关闭时间为空）
     * @author LeiGuoXian
     * @date 2021-09-26
     */
    isClose: function () {
      var _self = this;
      if (_self.parentModelData != undefined) {
        if (
          _self.parentModelData.data != undefined &&
          _self.parentModelData.data.documentStatus != undefined &&
          _self.parentModelData.data.documentStatus.displayValue[0] ==
            'APPROVED' &&
          _self.parentModelData.data.closeDate != undefined
        ) {
          return true;
        } else {
          return false;
        }
      } else {
        if (
          _self.modelData != undefined &&
          _self.modelData.data != undefined &&
          _self.modelData.data.documentStatus != undefined &&
          _self.modelData.data.documentStatus.displayValue[0] == 'APPROVED' &&
          _self.modelData.data.closeDate != undefined &&
          _self.modelData.data.closeDate.displayValue.length == 0
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
  },
  watch: {},

  methods: {
    /**
     * CURD单据关闭（关闭后不能被下流单据引用，已经生单的单据不受影响）
     *
     * @author LeiGuoXian
     * @date 2021-09-26
     */
    documentClose: function () {
      var _self = this;
      var windowNo = this.$route.params.windowNo;
      var tabIndex = _self.showTabDto.tabIndex;
      var recordId = null;
      var closeRecordIds = [];
      if (tabIndex == 0) {
        recordId = _self.modelData.id;
      } else if (tabIndex == 1) {
        recordId = _self.parentModelData.id;
        if (_self.modelDatas == undefined || _self.modelDatas.length == 0) {
          Notify.error(
            _self.$t('lang.Notify.error'),
            _self.$t('lang.tabButton.describe1'),
            false,
          );
          return;
        } else {
          _self.modelDatas.forEach(function (item) {
            if (item.select == true) {
              closeRecordIds.push(item.id);
            }
          });
          if (closeRecordIds.length == 0) {
            Notify.error(
              _self.$t('lang.Notify.error'),
              _self.$t('lang.tabButton.describe2'),
              false,
            );
            return;
          }
        }
      }
      var documentCloseRequest = {
        windowNo: windowNo,
        tabIndex: tabIndex,
        documentRecordId: recordId,
        closeRecordIds: closeRecordIds,
      };
      $.ajax({
        url: Common.getApiURL('documentResource/documentClose'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(documentCloseRequest),
        success: function (data) {
          if (data.errcode == 0) {
            Notify.success(_self.$t('lang.Notify.success'), data.errmsg, false);
          } else {
            Notify.error(_self.$t('lang.Notify.prompt'), data.errmsg, false);
          }
          _self.$emit('processExecuteFinish');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * CURD单据打开（打开后可以被下流单据引用）
     *
     * @author LeiGuoXian
     * @date 2021-09-26
     */
    documentOpen: function () {
      var _self = this;
      var windowNo = this.$route.params.windowNo;
      var tabIndex = _self.showTabDto.tabIndex;
      var recordId = null;
      var openRecordIds = [];
      if (tabIndex == 0) {
        recordId = _self.modelData.id;
      } else if (tabIndex == 1) {
        recordId = _self.parentModelData.id;
        if (_self.modelDatas == undefined || _self.modelDatas.length == 0) {
          Notify.error(
            _self.$t('lang.Notify.error'),
            _self.$t('lang.tabButton.describe1'),
            false,
          );
          return;
        } else {
          _self.modelDatas.forEach(function (item) {
            if (item.select == true) {
              openRecordIds.push(item.id);
            }
          });
          if (openRecordIds.length == 0) {
            Notify.error(
              _self.$t('lang.Notify.error'),
              _self.$t('lang.tabButton.describe2'),
              false,
            );
            return;
          }
        }
      }
      var documentOpenRequest = {
        windowNo: windowNo,
        tabIndex: tabIndex,
        documentRecordId: recordId,
        openRecordIds: openRecordIds,
      };
      $.ajax({
        url: Common.getApiURL('documentResource/documentOpen'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(documentOpenRequest),
        success: function (data) {
          if (data.errcode == 0) {
            Notify.success(_self.$t('lang.Notify.success'), data.errmsg, false);
          } else {
            Notify.error(_self.$t('lang.Notify.prompt'), data.errmsg, false);
          }
          _self.$emit('processExecuteFinish');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 获取想要成为哪个卡片的附属卡片
    getSelectModelData: function () {
      const _self = this;
      const card = this.$refs.infoRef.getSelectedModelDatas();
      if (!card || !card.length) {
        message.warning('未选择卡片，请至少选择一个卡片作为主卡。');
        return;
      }
      const parentId = card[card.length - 1].id;
      const recordIds = [_self.modelData.id];
      const params = { parentId, recordIds };
      turnMasterCard(params).then(
        successData => {
          if (successData.errorCode === 0) {
            message.success('转为附属卡片成功。');
            _self.cardConversionOpen = false;
            _self.$emit('processExecuteFinish');
          } else {
            message.warning(successData.errorMessage);
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    //跳转或执行流程
    execute: function (tabButton) {
      var _self = this;
      // 资产卡片转为副卡
      if (tabButton.name === '转为附卡') {
        _self.cardConversionOpen = true;
        return;
      }
      if (
        tabButton.customerWindowNo != undefined &&
        tabButton.customerWindowNo != ''
      ) {
        CustomerWindowResource.uniqueByNo(tabButton.customerWindowNo).then(
          successData => {
            if (successData.errorCode == 0) {
              tabButton.customerWindowRouteUrl = successData.data.routeUrl;
              if (tabButton.customerWindowNo == '20221101_151823') {
                localStorage.setItem(
                  'AssetInstance_ComplexFilterParams',
                  JSON.stringify(_self.complexFilterParams),
                );
                localStorage.setItem(
                  'AssetInstance_SimpleFilterParams',
                  _self.simpleFilterParams,
                );
              }
              //跳转到tabButton.routeUrl
              if (this.viewType == 'Form' || this.viewType == 'EditForm') {
                this.switchFormRoute(tabButton);
              } else if (this.viewType == 'Grid') {
                this.switchFormRoute(tabButton);
              }
            } else {
              Notify.error(
                _self.$t('lang.Notify.error'),
                successData.errorMessage,
                true,
              );
            }
          },
          errorData => {
            Common.processException(errorData);
          },
        );
      } else if (
        tabButton.processReportNo != undefined &&
        tabButton.processReportNo != ''
      ) {
        // 判断流程报表是否有参数
        // 如果有参数则直接跳转到流程和报表的界面。
        if (
          tabButton.routerRedirect == undefined ||
          tabButton.routerRedirect == false
        ) {
          this.executeProcess(tabButton);
        } else {
          this.$router.push({
            path: '/desktop/process-report/' + tabButton.processReportNo,
          });
        }
      } else if (tabButton.htmlWindowNo != undefined) {
        HtmlWindowResource.uniqueByNo(tabButton.htmlWindowNo).then(
          response => {
            if (response.errorCode != 0) {
              Notify.error(
                _self.$t('lang.Notify.dataDictionaryError'),
                response.errorMessage,
                true,
              );
              return;
            }

            const htmlWindowDto = response.data;
            if (htmlWindowDto != undefined) {
              var htmlWindowUrl = htmlWindowDto.htmlFileName;
              var autoCloseInterval = htmlWindowDto.autoCloseInterval;
              var regExp = new RegExp('[{].*?[}]', 'g');
              var result = htmlWindowUrl.match(regExp);
              if (htmlWindowUrl != undefined && htmlWindowUrl != '') {
                for (var index = 0, len = result.length; index < len; index++) {
                  var tempResult = result[index];
                  console.log('{' + tempResult + '}匹配');
                  if (tempResult == '{URL}') {
                    htmlWindowUrl = htmlWindowUrl.replace(
                      '{URL}',
                      Common.getHostPageBaseURL(),
                    );
                  } else if (tempResult == '{RecordIds}') {
                    if (this.viewType == 'Grid') {
                      var recordIds = '';
                      if (_self.modelDatas && _self.modelDatas.length > 0) {
                        _self.modelDatas.forEach(function (item) {
                          if (item.select) {
                            recordIds += item.id + ',';
                          }
                        });
                      }
                      if (recordIds != null && recordIds.length > 0) {
                        recordIds = recordIds.substring(
                          0,
                          recordIds.length - 1,
                        );
                      } else {
                        Notify.error(
                          _self.$t('lang.Notify.error'),
                          _self.$t('lang.tabButton.describe3'),
                          true,
                        );
                        return;
                      }
                      htmlWindowUrl = htmlWindowUrl.replace(
                        '{RecordIds}',
                        recordIds,
                      );
                    } else {
                      var recordId = _self.modelData.id;
                      htmlWindowUrl = htmlWindowUrl.replace(
                        '{RecordIds}',
                        recordId,
                      );
                    }
                  } else if (tempResult == '{Token}') {
                    htmlWindowUrl = htmlWindowUrl.replace(
                      '{Token}',
                      Common.getToken(),
                    );
                  } else {
                    if (_self.selectedModelDatas.length == 0) {
                      Notify.error(
                        _self.$t('lang.Notify.error'),
                        _self.$t('lang.tabButton.describe3'),
                        true,
                      );
                      return;
                    } else if (_self.selectedModelDatas.length > 1) {
                      Notify.error(
                        _self.$t('lang.Notify.error'),
                        _self.$t('lang.tabButton.describe2'),
                        true,
                      );
                      return;
                    }
                    var tempResult1 = tempResult
                      .replace('{', '')
                      .replace('}', '');
                    htmlWindowUrl = htmlWindowUrl.replace(
                      tempResult,
                      _self.getFirstSelectModelDataFieldValue(tempResult1),
                    );
                  }
                }

                var openWindow = window.open(htmlWindowUrl);

                // 自动关闭
                if (autoCloseInterval != undefined) {
                  setTimeout(function () {
                    openWindow.close();
                    openWindow = undefined;
                  }, autoCloseInterval * 1000);
                }
              }
            }
          },
          errorData => {
            Common.processException(errorData);
          },
        );
      }
    },

    autoCloseOpenWindow: function () {
      if (this.openWindow != null) {
        this.openWindow.close();
        this.openWindow = null;
      }
    },

    /**
     * 导出确认
     */
    exportConfirm: function () {
      var _self = this;
      if (
        _self.curdWindowFunctionAccess.canExport != null &&
        _self.curdWindowFunctionAccess.canExport === true
      ) {
        Notify.show({
          title: _self.$t('lang.TabButton.dataExport'), //title
          message: _self.$t('lang.TabButton.DataExport'),
          buttons: [
            {
              label: _self.$t('lang.TabButton.exportMasterTableData'),
              action: function (dialog) {
                _self.exportData(false);
                dialog.close();
              },
            },
            {
              label: _self.$t('lang.TabButton.exportAllData'),
              action: function (dialog) {
                _self.exportData(true);
                dialog.close();
              },
            },
            {
              label: _self.$t('lang.TabButton.cancel'),
              action: function (dialog) {
                dialog.close();
              },
            },
          ],
        });
      } else {
        Notify.error(
          _self.$t('lang.tabButton.describe4'),
          _self.$t('lang.tabButton.describe5'),
          false,
        );
      }
    },
    /**
     * 导出数据
     * @param exportSubTabData 是否导出子页签数据
     */
    exportData: function (exportSubTabData) {
      var _self = this;
      var downloadUrl = null;
      var token = Common.getToken();
      var windowNo = this.$route.params.windowNo;
      var recordId = null;
      if (_self.modelData != undefined) {
        recordId = _self.modelData.id;
      }

      var uuid = _self.uuid;
      var obj = {
        windowNo: windowNo,
        tabIndex: _self.showTabDto.tabIndex,
        recordId: recordId,
        token: token,
        simpleFilterCondition: _self.simpleFilterParams,
        filterParams: _self.complexFilterParams,
      };

      let url = null;
      if (recordId == null) {
        url = Common.getApiURL('exportResource/exportWindowData');
      } else {
        url = Common.getApiURL('exportResource/exportSingleWindowData');
      }
      url += '?exportSubTabData=' + exportSubTabData;

      let formParameterName = 'exportQueryParamStr';
      let formParameterValue = JSON.stringify(obj);

      var data = formParameterName + '=' + formParameterValue;
      var timeStr = dayjs().format('_YYYYMMDD_hhmmss');

      var fileName =
        _self.showTabDto == null
          ? '导出数据' + timeStr + '.xlsx'
          : _self.showTabDto.name + timeStr + '.xlsx';
      DownloadService.postDownloadFile(url, data, fileName);
    },

    importData: function () {
      var _self = this;
      var uuid = _self.uuid;
      if (
        _self.mWindow != undefined &&
        _self.mWindow.dataTemplateIds != undefined
      ) {
        var data = JSON.stringify(_self.mWindow.dataTemplateIds);
        this.$router.push({
          path: '/desktop/data-import-panel',
          query: { dataTemplateIds: data },
        });
      }
    },
    // 切换到Form表单的路由
    switchFormRoute: function (tabButton) {
      const _self = this;
      var routeDate = {
        path: tabButton.customerWindowRouteUrl,
        params: {
          processReportId: tabButton.processReportId,
          modelData: this.modelData,
        },
      };
      // 请勿修改，会影响生单的功能
      var uuid = _self.uuid;
      if (uuid != undefined) {
        routeDate.path = routeDate.path + '/' + uuid;
      }

      this.$emit('saveView');

      const frameUrl = Common.getRedirectUrl(
        '#' + routeDate.path + '?processReportId=' + tabButton.processReportId,
      );

      // 供子页面iframe调用，修改modelData，(举例：生单界面修改参数)。
      window.modelDataChanged = this.modelDataChanged;

      window.getModelData = this.getModelData;
      let modelData = JSON.stringify(this.modelData);
      console.log(modelData);
      localStorage.setItem(_self.uuid + '#GenerateDocumentTool', modelData);

      var iWidth = 1280; //弹出窗口的宽度;
      var iHeight = 720; //弹出窗口的高度;
      var iTop = (window.screen.availHeight - 30 - iHeight) / 2; //获得窗口的垂直位置;
      var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //获得窗口的水平位置;
      window.open(
        frameUrl,
        '_blank',
        'height=' +
          iHeight +
          ',innerHeight=' +
          iHeight +
          ',width=' +
          iWidth +
          ',innerWidth=' +
          iWidth +
          ',top=' +
          iTop +
          ',left=' +
          iLeft +
          ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no',
      );
      // window.open(frameUrl);
    },

    modelDataChanged: function (newModelData) {
      const _self = this;
      _self.$emit('modelDataChanged', newModelData);
    },

    getModelData: function () {
      const _self = this;
      return _self.$parent.getModelData();
    },

    // 执行Form流程
    executeFormProcess: function (tabButton) {
      var _self = this;
      //执行流程
      if (_self.modelData.id == undefined) {
        Notify.error(
          _self.$t('lang.tabButton.describe6'),
          _self.$t('lang.tabButton.describe7'),
          false,
        );
        return;
      }

      //执行流程
      var processResultData = {
        processReportId: tabButton.processReportId,
        modelData: _self.modelData,
      };
      _self.loading = true;

      $.ajax({
        url: Common.getApiURL('ProcessReportResource/runProcess'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(processResultData),
        success: function (successData) {
          _self.loading = false;
          if (successData.errorCode == 0) {
            _self.modal = true;
            _self.processReportResult = successData.data;

            if (
              _self.processReportResult.reportResults != undefined &&
              _self.processReportResult.reportResults.length > 0
            ) {
              _self.processReportResult.reportResults.forEach(function (
                item,
                index,
              ) {
                item.previewIndex = 1;
                if (index == 0) {
                  item.showPreview = true;
                } else {
                  item.showPreview = false;
                }
              });
            }
            _self.$emit('processExecuteFinish');
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 执行流程
    executeProcess: function (tabButton) {
      var _self = this;

      // if (_self.viewType == 'EditForm' || _self.viewType == 'Form') {
      //     let processResultData = {
      //         "processReportNo": tabButton.processReportNo,
      //         "modelData": _self.modelData
      //     }

      //     _self.loading=true;

      //     ProcessReportResource.runProcess(processResultData).then(successData => {
      //         _self.modal = true;
      //         _self.loading=false;
      //         _self.processReportResult = successData;
      //         _self.$emit("processExecuteFinish");
      //     }, errorData => {
      //         _self.loading=false;
      //         Common.processException(errorData);
      //     });
      // } else {
      var ids = [];
      if (_self.modelDatas) {
        _self.modelDatas.forEach(function (modelData) {
          if (modelData.select == true) {
            ids.push(modelData.id);
          }
        });
      } else if (_self.modelData) {
        ids.push(_self.modelData.id);
      }
      _self.loading = true;

      ProcessReportResource.runProcessByIds(
        tabButton.processReportNo,
        ids,
      ).then(
        successData => {
          _self.modal = true;
          _self.loading = false;
          _self.processReportResult = successData;

          if (
            _self.processReportResult.reportResults != undefined &&
            _self.processReportResult.reportResults.length > 0
          ) {
            _self.processReportResult.reportResults.forEach(function (
              item,
              index,
            ) {
              if (item.reportDefinitionType !== 'ExcelReport') {
                item.previewIndex = 1;
              } else {
                item.previewIndex = 2;
              }
              if (index == 0) {
                item.showPreview = true;
              } else {
                item.showPreview = false;
              }
            });
          }

          _self.$emit('processExecuteFinish');
        },
        errorData => {
          _self.loading = false;
          Common.processException(errorData);
        },
      );
      // }
    },

    // 通知
    notify: function () {
      var _self = this;
      _self.notificationModal = true;
    },
    // 发送通知
    sendNotification: function () {
      var _self = this;
      var notification = _self.$refs.notificationPanel.getNotification();
      var recordIds = [];
      if (_self.viewType == 'Grid') {
        if (_self.modelDatas && _self.modelDatas.length > 0) {
          _self.modelDatas.forEach(function (item) {
            if (item.select) {
              recordIds.push(item.id);
            }
          });
        }
      } else if (_self.viewType == 'Form') {
        recordIds.push(_self.$route.params.recordId);
      }
      if (recordIds.length == 0) {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.tabButton.describe7'),
          true,
        );
        return;
      }
      if (notification.userIds == null || notification.userIds.length == 0) {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.tabButton.describe8'),
          true,
        );
        return;
      }
      if (notification.theme == null || notification.theme.trim() == '') {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.tabButton.describe9'),
          true,
        );
        return;
      }
      if (notification.content == null || notification.content.trim() == '') {
        Notify.error(
          _self.$t('lang.Notify.error'),
          _self.$t('lang.tabButton.describe10'),
          true,
        );
        return;
      }
      var windowNo = _self.$route.params.windowNo;
      var tabIndex = _self.showTabDto.tabIndex;
      notification.windowNo = windowNo;
      notification.tabIndex = tabIndex;
      notification.recordIds = recordIds;
      notification.className = _self.showTabDto.className;

      _self.loading = true;
      $.ajax({
        url: Common.getApiURL('notificationResource/send'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(notification),
        success: function (data) {
          _self.loading = false;
          _self.notificationModal = false;
          Notify.success(
            _self.$t('lang.tabButton.describe11'),
            _self.$t('lang.tabButton.describe12'),
            true,
          );
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    // 取消发送
    cancelNotification: function () {
      this.notificationModal = false;
    },
  },
};
</script>

<style scoped>
.floatTop {
  z-index: 1002;
}

:deep(.btn-group) {
  margin: -2px;
}

.tab_button {
  color: black;
  margin-left: 4px;
}

:deep(.ant-breadcrumb-link :first-child) {
  color: #4ca4f7;
}
</style>
