<template>
  <sd-detail-form
    v-show="initialled"
    ref="docform"
    :page-id="this.$route.query.pageId"
    :record-id="this.$route.query.projectId ? this.$route.query.projectId : null"
    :class="$style.form"
    :read-only="false"
    @close="close(true)"
    @saved="saved"
    @actionBtnClick="actionBtnClick"
  >
    <template v-slot="{ formData, model, fields }">
      <table>
        <tr>
          <td style="border: none">
            <audit-advanced-group
              :expand="expand"
              expand-str="expand"
              group-label="分组信息"
              @changedClick="changedClick"
            ></audit-advanced-group>
          </td>
        </tr>
      </table>

      <table v-show="expand">
        <tr>
          <td colspan="4" :class="$style.subTable">
            <sd-form-by-builder
              v-if="initialled"
              :form-data="formData.pageFormData"
            ></sd-form-by-builder>
          </td>
        </tr>
      </table>
    </template>
  </sd-detail-form>
</template>

<script>
import { message } from '@/common/one-ui'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import CpmService from '../../cpm-service'
import components from './_import-components/audit-cpm-project-group-import'
import auditCpmProjectGroupService from './audit-cpm-project-group-service'

export default {
  name: 'AuditCpmProjectGroup',
  metaInfo: {
    title: '项目分组',
  },
  components: {
    auditAdvancedGroup,
    ...components,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      expand: true,
      initialled: false,
      deptFw: undefined,
    }
  },
  mounted() {
    const ini = setInterval(() => {
      if (
        this.$refs.docform &&
        (this.$refs.docform.$refs.form || this.$refs.docform.$refs.sdForm)
      ) {
        try {
          // 设置被检查单位选择范围
          this.setDeptData(this.$route.query.projectId)
          clearInterval(ini)
        } catch {}
      }
    }, 100)
  },
  methods: {
    // 设置被检查单位选择范围
    setDeptData(projectId) {
      if (projectId) {
        // 获取项目信息
        const childTableData = this.$refs.docform.getFieldValue('CPM_SUB_PROJECT')
        CpmService.getProjectData(projectId).then((res) => {
          const checkdeptnames = res.data[0].checkedDeptNames
          const checkdeptcodes = res.data[0].checkedDeptIds
          const names = checkdeptnames.split(',')
          const codes = checkdeptcodes.split(',')
          const deptFw = []
          names.forEach((n, index) => {
            deptFw.push({
              type: 'Group',
              name: n,
              code: codes[index],
            })
          })
          this.deptFw = deptFw
          childTableData.forEach((item) => {
            item.CHECKED_DEPT_OPT_FW = JSON.stringify(deptFw)
          })
          this.$refs.docform.setFieldValue('CPM_SUB_PROJECT', childTableData)
          this.filter(this.$refs.docform.formData.pageFormData)
          this.initialled = true
        })
      }
    },
    saved() {
      // 保存成功后
      message.success({ content: '保存成功', key: 'messagekey' })
      // 保存成功之后，更新分组数据
      auditCpmProjectGroupService.saveSubProjectLeader(this.$route.query.projectId)
    },
    close(flag) {
      window.close()
    },
    filter(pageFormData) {
      // 升级新加的参数，使用这个判断是否展示这个字段
      this.$refs.docform.$refs.form.displayExprResults.CPM_SUB_PROJECT = 'true'
      const formData = pageFormData
      formData.pageFieldInfos.forEach((item) => {
        if (item.name !== 'CPM_SUB_PROJECT') {
          item.attrFD.hidden = true
        } else {
          item.attrFD.hidden = false
          item.attr.dync?.forEach((item) => {
            if (item.name === 'CHECKED_DEPT_OPT_FW') {
              item.attr.defaultValue = JSON.stringify(this.deptFw)
            }
          })
        }
      })
      return formData
    },
    actionBtnClick(evt, btn) {
      if (btn.buttonId === 'save') {
        // 停止默认事件，走自己的保存
        evt.preventDefault()
        // 判断表中是否有重复
        let flag = true
        // 判断子表是否都已填完
        const btnList = document.querySelectorAll('.operation_sd-child-table_common')
        btnList.forEach((item) => {
          if (item.innerHTML.includes('保存')) {
            flag = false
          }
        })
        if (!flag) {
          message.warning('请保存编辑行，再执行此操作', 1)
          return
        }
        const ulist = this.$refs.docform.getFieldValue('CPM_SUB_PROJECT')
        let tsxx = ''
        ulist.forEach((i) => {
          if (
            ulist.filter((u) => u.CHECKED_DEPT_ID && u.CHECKED_DEPT_ID === i.CHECKED_DEPT_ID)
              .length > 1
          ) {
            flag = false
            tsxx = '分组表中被检查单位重复，请检查数据'
          }
        })
        if (!flag) {
          message.warning(tsxx, 1)
        } else {
          // 进行保存
          ulist.forEach((item) => {
            item.CHECKED_DEPT_OPT_FW = '[]'
          })
          this.$refs.docform.setFieldValue('CPM_SUB_PROJECT', ulist)
          this.$refs.docform.saveBtnClick()
        }
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.form {
  :global(.ant-form-item-control-wrapper) {
    margin: auto;
    width: 100% !important;
    text-align: center;
  }
  :global(.ant-form-item-control) {
    margin-top: 10px;
  }
}
.sub-table {
  table {
    width: 100%;
  }
}
</style>
