// 此文件存放交易流转的一些公共方法
import Api from '~/service/Api';
import Utils from "../utils"
export default {
  methods: {
    // 提交
    handleSubmit() {
      this.handleCheck(true).then(async () => {
        let params = {
          ...this.model,
          // gidgrp: {
          //   ...this.model.gidgrp,
          //   ...this.model.gitp
          // },
          transName: this.trnName,
          userId: window.sessionStorage.userId || 'ZL',
        }
        // 精简cfagit
        if (params.cfagit && params.cfagit.cfaflg !== '1') {
          delete params.cfagit
        }
        // 精简cnybop
        if (params.cnybop && params.cnybop.vouflg !== '1') {
          delete params.cnybop.cnyvou
        }
        const res = await Api.post(`/service/${this.trnName}/save`, params);
        if (res.respCode === SUCCESS) {
          this.$notify({
            title: '成功',
            message: '提交成功',
            type: 'success',
          });
          this.$store.dispatch("TagsView/delView", this.$route)
          this.$router.push('/taskList')
          this.$store.commit("setTaskListTabVal", 'trnrel');
        }
      })
    },
    // 检核
    handleCheck(isSubmit) {
      return new Promise((resolve) => {
        // 前端检验
        this.$refs['modelForm'].validate(async (validStatic) => {
          if (validStatic) {
            const loading = this.loading('正在校验数据');
            const rtnmsg = await Api.post(`/service/${this.trnName}/checkAll`, {
              ...this.model,
              transName: this.trnName,
              userId: window.sessionStorage.userId || 'ZL',
            });
            loading.close()
            if (rtnmsg.respCode === SUCCESS) {
              let errorRules = rtnmsg.data;
              let keysList = Object.keys(errorRules)
              // 如果后端返回的对象为空,则后端校验成功
              if (errorRules && !keysList.length) {
                // 清除之前的校验状态
                this.$refs['modelForm'].clearValidate();
                if (!isSubmit) {
                  this.$notify({
                    title: "成功",
                    message: "校验成功",
                    type: "success",
                  });
                }
                resolve()
                return
              }
              const tab = this.showBackendErrors(errorRules)
              if (tab) {
                // tab切换之后,需出发tab-click的事件
                if (tab.name !== this.tabVal) {
                  this.isChecking = true
                  this.tabClick(tab);
                }
                this.$notify({
                  title: "错误",
                  message: "校核失败",
                  type: "error",
                });
                return
              } 
            }
          } else {
            // 前端校验失败
            this.$notify({
              title: '失败',
              message: '校验失败',
              type: 'error',
            });
            this.showFrontendErrors()
          }
        })
      })
    },
    // 前端校验失败时候,tab和Collapse组件效果处理
    showFrontendErrors () {
      this.$nextTick(() => {
        let fields = this.$refs['modelForm'].fields
        fields.map((fieldItem) => {
          if (fieldItem.validateState === 'error') {
            let parentVC = fieldItem
            let firstErrorTab = null
            let collapsePanel = null
            while(!firstErrorTab) {
              const vcName = parentVC.$options.componentName
              // 没有Tabs的表单
              if (vcName === "ElForm") {
                  break;
              }
              if (vcName === "ElTabPane") {
                  firstErrorTab = parentVC
                  break;
              }
              if (vcName === "ElCollapseItem") {
                  collapsePanel = parentVC;
              }
              parentVC = parentVC.$parent;
            }
            if (firstErrorTab) {
              const tabs = firstErrorTab.$parent
              tabs.currentName = firstErrorTab.name
            }
            if (collapsePanel && collapsePanel.collapse.activeNames.indexOf(collapsePanel.name) < 0) {
              collapsePanel.collapse.activeNames.push(collapsePanel.name)
            }
          }
        })
        let isError = document.querySelectorAll('.is-error')
        isError[0].scrollIntoView({
          block: 'center',
          behavior: 'smooth'
        })
      })
    },
    // 后端校验
    showBackendErrors(fieldErrors) {
      // 清除之前的校验状态
      if (!this.$refs.modelForm) {
        return
      }
      if (!this.isChecking) {
        this.$refs.modelForm.clearValidate();
      } else {
        // 当 checkAll 操作时,由面板切换所触发的 executeRule 请求时,不清空 checkAll 的错误信息
        this.isChecking = false;
      }
      const fields = this.$refs.modelForm.fields;
      console.log('backFileds', fields)
      const tab = Utils.positioningErrorMsg(fieldErrors, fields);
      return tab;
    },
    // 暂存
    async handleStash() {
      const loading = this.loading('正在暂存数据');
      let params = {
        ...this.model,
          transName: this.trnName,
          userId: window.sessionStorage.userId || 'ZL',
        spt: JSON.parse(localStorage.getItem('row_' + this.trnName)) || {},
  
      }
      const res = await Api.post(`/service/${this.trnName}/txnHold`, params);
      if (res.respCode === SUCCESS) {
        this.$notify({
          title: '成功',
          message: '暂存成功',
          type: 'success',
        });
        this.$router.push('/taskList')
      }
      loading.close();
    },
    async handlePass(data) {
      this.$store.state.Transaction.operateFuns[data.operateId]["pass"]()
    },
    async handleRefuse(data) {
      this.$store.state.Transaction.operateFuns[data.operateId]["refuse"]()
    },
  }
}