<template>
  <sd-webflow ref="webflow">
    <template v-slot:form="{ model, FlowData }">
      <sd-form-by-builder
        ref="builderform"
        :form-data="FlowData.processFormData"
        @changedClick="changebj"
      />
    </template>
  </sd-webflow>
</template>

<script>
import CpmService from '../../cpm-service'
import components from './_import-components/cpm-check-plan-form-import'

export default {
  name: 'CpmCheckPlanForm',
  metaInfo: {
    title: 'CpmCheckPlanForm',
  },
  components,
  data() {
    return {}
  },
  mounted() {
    if (this.$route.query.extParams) {
      const ep = JSON.parse(this.$route.query.extParams)
      if (ep.SUB_PROJECT_ID !== '1') {
        this.initData(ep.SUB_PROJECT_ID, true, false)
      } else {
        this.initData(ep.PROJECT_ID, true, true)
      }
    } else {
      setTimeout(() => {
        const projectId = this.$refs.webflow.getFieldValue('PROJECT_ID')
        const subprojectId = this.$refs.webflow.getFieldValue('SUB_PROJECT_ID')
        if (subprojectId !== null && subprojectId !== '1') {
          this.initData(subprojectId, false, false)
        } else {
          this.initData(projectId, false, true)
        }
      }, 2000)
    }
  },
  methods: {
    // 初始化项目信息
    initData(projectId, flag, flagz) {
      const org = []
      if (projectId) {
        // 获取项目信息
        CpmService.getProjectData(projectId, flagz).then((res) => {
          const title = res.data[0].title
          if (flag) this.$refs.webflow.setFieldValue('PROJECT_NAME', title)
          const checkdeptnames = res.data[0].checkedDeptNames
          let checkdeptcodes = []
          if (res.data[0].checkedDeptCodes) {
            checkdeptcodes = res.data[0].checkedDeptCodes
          } else {
            checkdeptcodes = res.data[0].checkedDeptIds
          }
          const names = checkdeptnames.split(',')
          const codes = checkdeptcodes.split(',')
          const orgfw = []
          names.forEach((n, index) => {
            orgfw.push({
              type: 'Group',
              name: n,
              code: codes[index],
            })
          })
          this.$refs.webflow.setFieldValue('CHECKED_DEPT_FW', orgfw)
          if (flag) {
            if (names.length > 1) {
              this.$refs.webflow.setFieldValue('CHECKED_DEPT', org)
            } else {
              names.forEach((n, index) => {
                org.push({
                  type: 'GROUP',
                  name: n,
                  code: codes[index],
                })
              })
              this.$refs.webflow.setFieldValue('CHECKED_DEPT', org)
            }
          }
        })
      }
    },
    changebj() {
      console.log('---change')
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
