<template>
  <sd-webflow
    ref="webflow"
    :class="$style.webflow"
    :validate-form="validForm"
    @actionBtnClick="actionBtnClick"
  >
    <template v-slot:extra-tabs="{ FlowData }">
      <!-- 增加的tab页默认在最后，通过sd-before、sd-after可以指定位置 -->
      <a-tab-pane key="other" :tab="tabTitle" sd-before="sdFlowchart">
        <!-- 关联案件组件 -->
        <law-case-report-relate-doc
          v-model="relatedDoc"
          :flow-data="FlowData"
          :fields="
            FlowData.processFormData.processFormPropertyValues.find(
              (item) => item.name === 'LAW_CASE_RELATED'
            ).attrFD.dync
          "
          :related.sync="relatedDoc"
          @update:related="fnRelatedDoc"
        ></law-case-report-relate-doc>
      </a-tab-pane>
    </template>
    <template v-slot:form="{ model, FlowData }">
      <!-- 案由监听 -->
      <action-name-watcher :model="model" @actionNameChange="actionNameChange" />
      <field-watcher
        :model="model"
        @fieldChange="fieldChange"
        @caseTypeChange="caseTypeChange"
        @courtChange="courtChange"
      />
      <sd-form-by-builder
        :class="$style.builderTable"
        :form-data="filter(FlowData.processFormData)"
      />
      <form-watcher :flow-data="FlowData" :model="model" @change="lawChange"></form-watcher>
    </template>
  </sd-webflow>
</template>

<script>
import { message } from '@/common/one-ui'
import lawCaseReportRelateDoc from './law-case-report-relate-doc.vue'
import components from './_import-components/law-case-report-form-import'

export default {
  name: 'LawCaseReportForm',
  metaInfo: {
    title: '案件上报',
  },
  components: {
    actionNameWatcher: {
      props: ['model'],
      created() {
        this.$watch(
          () => {
            return this.model.ACTION_NAME
          },
          (nVal, oVal) => {
            this.$emit('actionNameChange', nVal, oVal)
          },
          { immediate: false }
        )
      },
      render: () => {},
    },
    fieldWatcher: {
      props: ['model'],
      created() {
        this.$watch(
          () => {
            return this.model.OWNER_POSITION
          },
          (nVal, oVal) => {
            this.$emit('fieldChange', nVal, oVal)
          },
          { immediate: false }
        )
        this.$watch(
          () => {
            return this.model.CASE_TYPE
          },
          () => {
            this.$emit('caseTypeChange', this.model.CASE_TYPE)
          },
          { immediate: false }
        )
        this.$watch(
          () => {
            return this.model.COURT
          },
          () => {
            this.$emit('courtChange', this.model.COURT)
          },
          { immediate: false }
        )
      },
      render: () => {},
    },
    lawCaseReportRelateDoc,
    formWatcher: {
      props: ['model', 'flowData'],
      created() {
        this.$watch(
          () => this.model.LAW_CASE_LAWYER,
          () => this.$emit('change', this.model.LAW_CASE_LAWYER, this.flowData),
          { immediate: true }
        )
      },
      render: () => {},
    },
    ...components,
  },
  data() {
    return {
      tabTitle: '关联案件',
      relatedDoc: [],
      isError: false,
    }
  },
  mounted() {
    const ini = setInterval(() => {
      if (
        this.$refs.webflow &&
        (this.$refs.webflow.$refs.form || this.$refs.webflow.$refs.sdForm)
      ) {
        clearInterval(ini)
        this.relatedDoc = this.$refs.webflow.getFieldValue('LAW_CASE_RELATED') || []
        this.setTabTitle()
      }
    }, true)
  },
  methods: {
    courtChange() {
      // 自定义组件不会直接校验，加校验
      this.$refs.webflow.validateField('COURT')
    },
    caseTypeChange() {
      this.$refs.webflow.setFieldValue('ACTION_NAME', '')
      this.$refs.webflow.setFieldValue('ACTION_CODE', '')
    },
    actionNameChange(nval, lval) {
      if (!nval) return
      // 自定义组件不会直接校验，加校验
      this.$refs.webflow.validateField('ACTION_NAME')
    },
    // 监听我方诉讼地位
    fieldChange(nVal, oVal) {
      if (this.isError) {
        message.warning('请保存编辑行，再执行此操作', 1)
        this.isError = false
        return
      }
      let save = false
      document.querySelectorAll('.operation_sd-child-table_common').forEach((item) => {
        if (item.innerHTML.includes('保存')) {
          save = true
        }
      })
      if (save) {
        this.$refs.webflow.setFieldValue('OWNER_POSITION', oVal)
        this.isError = true
        return
      }
      this.isError = false
      this.$refs.webflow.setFieldValue('LAW_CASE_PLAINTIFF', [])
      this.$refs.webflow.setFieldValue('LAW_CASE_DEFENDANT', [])
      this.$refs.webflow.setFieldValue('LAW_CASE_THREE', [])
      this.$nextTick()
    },
    lawChange(data, flowData) {
      // 外聘律师变化时
      if (data && data.length >= 2 && document.querySelector('.hidden-second-btn')) {
        document
          .querySelector('.hidden-second-btn')
          .setAttribute(
            'class',
            document
              .querySelector('.hidden-second-btn')
              .className.replace('hidden-second-btn', 'hidden-first-btn')
          )
      } else if (data && data.length < 2 && document.querySelector('.hidden-first-btn')) {
        document
          .querySelector('.hidden-first-btn')
          .setAttribute(
            'class',
            document
              .querySelector('.hidden-first-btn')
              .className.replace('hidden-first-btn', 'hidden-second-btn')
          )
      }
    },
    actionBtnClick(e, btn) {
      // 暂存也更新设置对方当事人
      if (btn.button.fakeId === 'save') {
        this.setParty()
        // 暂存需要判断案件类型必填
        e.waitUntil(
          new Promise((resolve) => {
            e.defaultPrevented = true
            this.$refs.webflow
              .validateField('CASE_TYPE')
              .then((res) => {
                e.defaultPrevented = false
                resolve(true)
              })
              .catch((e) => {
                resolve(false)
              })
          })
        )
      } else if (btn.button.fakeId === 'we-doc$close') {
        this.$refs.webflow.close()
        window.parent.opener = null
        window.parent.open('', '_self')
        window.parent.close()
      }
    },
    // 提交方法，设置对方当事人
    validForm() {
      // 受理机构必填
      const COURT = this.$refs.webflow.getFieldValue('COURT')
      const CASE_TYPE = this.$refs.webflow.getFieldValue('CASE_TYPE')
      if (!COURT && CASE_TYPE !== 'XS') {
        message.warning('请选择受理机构', 1)
        return new Promise((resolve, reject) => {
          resolve(false)
        })
      }
      // 判断外聘律师重复
      let isRepeat = false
      const LAW_CASE_LAWYER = this.$refs.webflow.getFieldValue('LAW_CASE_LAWYER')
      if (LAW_CASE_LAWYER) {
        LAW_CASE_LAWYER.forEach((item) => {
          if (
            LAW_CASE_LAWYER.filter((l) => {
              return l.LAWYER_ID === item.LAWYER_ID
            }).length > 1
          ) {
            isRepeat = true
          }
        })
        if (isRepeat) {
          message.warning('外聘律师重复，请重新选择', 1)
          return new Promise((resolve, reject) => {
            resolve(false)
          })
        }
      }
      // 设置对方当事人
      this.setParty()
      return new Promise((resolve, reject) => {
        resolve(true)
      })
    },
    // 设置对方当事人
    setParty() {
      const OWNER_POSITION = this.$refs.webflow.getFieldValue('OWNER_POSITION')
      let userList = []
      if (OWNER_POSITION === 'yg/sqr') {
        // 原告
        userList = this.$refs.webflow.getFieldValue('LAW_CASE_DEFENDANT') || []
      } else if (OWNER_POSITION === 'bg/bsqr') {
        // 被告
        userList = this.$refs.webflow.getFieldValue('LAW_CASE_PLAINTIFF') || []
      }
      let userName = []
      if (userList.length > 0) {
        userName = userList.map((item) => item.USER_NAME)
      }
      this.$refs.webflow.setFieldValue('OPPOSITE_PARTY', userName.join(','))
    },
    fnRelatedDoc(data) {
      this.$refs.webflow.setFieldValue('LAW_CASE_RELATED', data)
      this.setTabTitle()
    },
    setTabTitle() {
      if (this.relatedDoc.length > 0) {
        this.tabTitle = '关联案件' + ' (' + this.relatedDoc.length + ')'
      } else {
        this.tabTitle = '关联案件'
      }
    },
    filter(pageFormData) {
      const formData = pageFormData
      formData.processFormPropertyValues.forEach((item) => {
        // 案件类型
        if (item.name === 'CASE_TYPE' && formData.beanId !== null) {
          item.readonly = true
        }
        // 外聘律师
        if (item.name === 'LAW_CASE_LAWYER') {
          item.attrFD.formItemProps.inputProps.class = 'hidden-second-btn'
        }
        // 关联文件
        if (item.name === 'LAW_CASE_RELATED') {
          item.attrFD.formItemProps.inputProps.class = this.$style.relateTable
        }
      })
      return formData
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.webflow {
  :global(.ant-space-horizontal) {
    :global(.ant-space-item):nth-child(4) {
      display: none;
    }
  }
  :global(.hidden-first-btn) {
    :global(.header_sd-child-table_common) {
      :global(.ant-space-item) {
        &:first-child {
          display: none;
        }
      }
    }
  }
  :global(.hidden-second-btn) {
    :global(.header_sd-child-table_common) {
      :global(.ant-space-item) {
        &:nth-child(2) {
          display: none;
        }
      }
    }
  }
  .relate-table {
    display: none;
  }
  .builder-table {
    & > tr {
      &:last-child {
        display: none;
      }
    }
  }
}
</style>
