<!--  -->
<template>
  <van-form
    ref="dataForm"
    :show-error="false"
  >
    <div
      v-for="field in value || []"
      :key="field.index"
    >
      <!-- 业务组件 上传附件 -->
      <upload-attachments
        v-if="field.category === 'business' && field.prop === 'UploadAttachments'"
        :item="field"
        :rules="setRules"
      />
      <!-- 业务组件 升级单上传文件 -->
      <upgrade-upload-attachments
        v-if="field.category === 'business' && field.prop === 'UpgradeUploadAttachments'"
        :item="field"
      />
      <!-- 业务组件 BTCP签收码 -->
      <b-t-c-p-sign-code
        v-if="field.category === 'business' && field.prop === 'BTCPSignCode'"
        :item="field"
      />
      <!-- 业务组件 用户签收 -->
      <b-t-c-p-customer-sign
        v-if="field.category === 'business' && field.prop === 'BTCPCustomerSign'"
        :item="field"
        :so-id="$route.params.id"
        :rules="setRules"
      />
      <!-- 业务组件 订单撤单 -->
      <b-t-c-p-cancel-order
        v-if="field.category === 'business' && field.prop === 'BTCPCancelOrder'"
        :item="field"
        :rules="setRules"
      />
      <!-- 联想换件 -->
      <lenovo-change-parts
        v-if="field.category === 'business' && field.prop === 'LenovoChangeParts'"
        :item="field"
      />
      <!-- 分派工程师 -->
      <engineer-assigner
        v-if="field.category === 'business' && field.prop === 'EngineerAssigner'"
        :item="field"
      />
      <!-- 换件 -->
      <change-parts
        v-if="field.category === 'business' && field.prop === 'ChangeParts'"
        :item="field"
      />
      <!-- 第三方换件 -->
      <offline-change-parts
        v-if="field.category === 'business' && field.prop === 'OfflineChangeParts'"
        :item="field"
      />
      <!-- 签到 -->
      <sign-in
        v-if="field.category === 'business' && field.prop === 'EngineerSignUp'"
        :form-data="formData"
        :item="field"
        @parentGetNode="refresh"
      />
      <!-- 添加非换件 -->
      <no-change-parts
        v-if="field.category === 'business' && field.prop === 'NotChangRec'"
        :item="field"
      />
      <!-- 业务组件 计次类服务产品核销(联想业务) -->
      <calculate-service-products-num-for-lenovo
        v-if="field.category === 'business' && field.prop === 'CalculateServiceProductsNumForLenovo'"
        :item="field"
        :soid="soid"
        :rules="setRules"
      />
      <!-- 业务组件 上门核销码 -->
      <j-d-cancel-code
        v-if="field.category === 'business' && field.prop === 'JDCancelCode'"
        :item="field"
        :rules="setRules"
      />
      <!-- 系统/自定义组件 (category为system/custom) -->
      <form-item
        v-else
        :field="field"
      />
    </div>
  </van-form>
</template>

<script>
import components from '../components'
import FormItem from './form-item'
import cloneDeep from 'lodash/cloneDeep'
import { componentsToTemplate, templateToSubmit } from './../components/utils'
import { Notify } from 'vant'

export default {
  name: 'FormGenerator',
  components: {
    ...components,
    FormItem
  },
  props: {
    // 必传
    value: {
      type: Array,
      default () {
        return []
      },
      require: true
    },
    // 全部流程数据 不传的话会无法判断不支持组件
    formData: {
      type: Array,
      default: () => [],
      require: true
    },
    // 工单号 不需要可以不传
    soid: {
      type: String,
      default () {
        return ''
      },
      require: false
    },
    // 流程名(模板名) 用于弹出不支持组件提示使用
    formDesignerNodeName: {
      type: String,
      default: '',
      require: true
    }
    // 其他参数但是不需要体现在props的非必填项
    // 用于返回按钮是否可以提交的状态 :submit-btn-disabled.sync="submitBtnDisabled"
    //  @refresh="" 和签到业务组件相关
  },
  data () {
    return {
      // 不支持的业务组件
      noSupportComponents: ['EngineerAssignerForLenovo', 'CreateSOProduct', 'SOProductSelect', 'AddTeamWorker',
        'LenovoAddProductSOHandOverInfo', 'LenovoAddCustomerSOHandOverInfo', 'FaultLevel', 'UpgradeFaultLevel',
        'serviceCatalog', 'RecaptionMachineInform', 'RecaptionMachineValidation', 'RecaptionMachineResult',
        'AddServiceRecord', 'SubFaultyPart', 'SubMailRepairMethod', 'CustomerPayment', 'SOExpressPlaceOrder'],
      // 业务组件是否存在节点的Notify
      isExitNotify: false
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      this.initNoSupportComponent()
    },
    // 不支持业务组件功能初始化
    initNoSupportComponent () {
      // 只有第一个的时候弹出全部提示
      if (this.formDesignerNodeName === (this.formData[0].processNodeName || this.formData[0].templateName)) {
        const noSupportComponentNames = []
        this.formData.map(form => {
          const value = form.formTemplate ? form.formTemplate.formTemplateJson ? form.formTemplate.formTemplateJson : [] : []
          value.map(field => {
            if (this.noSupportComponents.includes(field.prop)) {
              noSupportComponentNames.push(field.label)
            }
          })
          // 只要有一个存在节点的Notify就延迟默认的3000毫秒
          if (form.warningMsg && !form.isCompulsaryWarning) {
            this.isExitNotify = true
          }
        })
        if (noSupportComponentNames.length > 0) {
          // 更新按钮是否可以点击
          this.$emit('update:submitBtnDisabled', true)
          const msg = '该工单中"' + noSupportComponentNames.join('、') + '"业务组件不支持,请通过PC端操作'
          if (this.isExitNotify) {
            setTimeout(() => {
              Notify({ type: 'primary', message: msg })
            }, 3000)
          } else {
            Notify({ type: 'primary', message: msg })
          }
        } else {
          this.$emit('update:submitBtnDisabled', false)
        }
      }
    },
    // 业务组件通用校验规则
    setRules (prop, label) {
      const rules = []
      // 为空校验
      if (prop.required) {
        rules.push({
          required: true,
          message: label + '不能为空',
          trigger: 'onChange'
        })
      }
      return rules
    },
    refresh () {
      this.$emit('refresh')
    },
    // 表单验证
    validate () {
      // 提交创建接口
      return new Promise((resolve, reject) => {
        this.$refs.dataForm.validate().then(() => {
          const originalJson = cloneDeep(this.value)
          // 用于模板保存的数据结构
          const templateJson = componentsToTemplate(originalJson)
          // 用于模板保存中的业务组件
          const templateJsonByBusiness = originalJson.filter(item => item.category === 'business').map(item => item.componentInfo)
          // 自定义组件、系统组件-提交的数据格式
          const propertyFeedbackInfo = templateToSubmit(templateJson.filter(item => item.category !== 'business'))
          // 业务组件-提交的数据格式
          const componentFeedbackInfo = templateToSubmit(templateJson.filter(item => item.category === 'business'))
          // 校验通过
          console.log('校验通过')
          resolve({
            originalJson,
            templateJson,
            templateJsonByBusiness,
            propertyFeedbackInfo,
            componentFeedbackInfo
          })
        }).catch(() => {
          reject(new Error('校验不通过'))
        })
      })
    }
  }
}
</script>
<style lang='scss' scoped>

</style>
