<template>
  <div>
    <a-form-model
      v-if="loaded"
      ref="selectForm"
      :zIndex="1001"
      :model="form"
      :rules="rules">
      <a-row :gutter="16">
        <x-form-item
          v-for="(item, index) in realJsonData"
          :key="index"
          :attr="item"
          :disabled="itemDisabled(item)"
          :files="files"
          :form="form"
          :images="images"
          :service-name="serviceName"
          :xl="12"
          :xxl="8"
          mode="新增/修改"
        />
      </a-row>
    </a-form-model>
  </div>
</template>
<script>
import XFormItem from '@vue2-client/base-client/components/common/XForm/XFormItem'
import { formatDate } from '@vue2-client/utils/util'
import { mapState } from 'vuex'
import { post } from '@vue2-client/services/api'

export default {
  name: 'XAddNativeFormOA',
  components: {
    XFormItem
  },
  data () {
    return {
      // 内容加载是否完成
      loaded: false,
      // 表单Model
      form: {},
      // 修改有文件得表单时使用
      files: [],
      images: [],
      // 校验
      rules: {}
    }
  },
  computed: {
    // 过滤出用于新增/修改场景的表单项
    realJsonData: function () {
      return this.jsonData.filter(function (item) {
        return item.addOrEdit && item.addOrEdit !== 'no' && item.addOrEdit !== 'silenceAdd' && item.addOrEdit !== 'version'
      })
    },
    // 过滤出用于静默新增场景的表单项
    silenceAddJsonData: function () {
      return this.jsonData.filter(function (item) {
        return item.addOrEdit === 'silenceAdd'
      })
    },
    // 过滤出版本号表单项
    versionJsonData: function () {
      return this.jsonData.filter(function (item) {
        return item.addOrEdit === 'version'
      })
    },
    ...mapState('account', { currUser: 'user' })
  },
  props: {
    jsonData: {
      type: Array,
      default: () => {
        return []
      }
    },
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
    // 业务类型
    businessType: {
      type: String,
      default: ''
    },
    // 修改操作前查询出的业务数据
    modifyModelData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 新增或修改业务是否执行中
    loading: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    // 固定新增表单
    fixedAddForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    nowStepContent: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  watch: {
    visible (rel) {
      if (rel) {
        this.formItemLoad()
      }
    }
  },
  mounted () {
    this.formItemLoad()
    // if (this.nowStepContent) {
    //   this.form = this.nowStepContent
    // }
  },
  methods: {
    formItemLoad () {
      const formData = Object.assign({}, this.fixedAddForm)
      for (let i = 0; i < this.realJsonData.length; i++) {
        const item = this.realJsonData[i]
        formData[item.model] = undefined
        // 处理表单校验情况
        if (item.rule) {
          this.rules[item.model] = []
          const required = item.rule.required ? item.rule.required === true || item.rule.required === 'true' : false
          let trigger
          let message
          if (required) {
            switch (item.type) {
              case 'select':
              case 'checkbox':
              case 'radio':
              case 'treeSelect':
              case 'rangePicker':
              case 'monthPicker':
              case 'yearPicker':
              case 'datePicker':
              case 'file':
              case 'image':
              case 'citySelect':
              case 'addressSearch':
              case 'personSetting':
                message = '请选择' + item.name
                trigger = 'change'
                break
              default:
                message = '请输入' + item.name
                trigger = 'blur'
            }
            this.rules[item.model].push({
              required: true,
              message: message,
              trigger: trigger
            })
          }

          switch (item.rule.type) {
            case 'number':
            case 'integer':
            case 'float': {
              let defaultValue
              let message
              switch (item.rule.type) {
                case 'number':
                  message = '数字'
                  defaultValue = 0
                  break
                case 'integer':
                  message = '整数'
                  defaultValue = 0
                  break
                case 'float':
                  message = '小数'
                  defaultValue = 0.0
                  break
              }
              this.rules[item.model].push({
                type: item.rule.type,
                message: item.name + '必须为' + message,
                transform: (value) => {
                  if (value && value.length !== 0) {
                    return Number(value)
                  } else {
                    return defaultValue
                  }
                },
                trigger: 'blur'
              })
            }
              break
          }
        }
      }
      this.form = formData
      if (this.modifyModelData.data) {
        this.files = this.modifyModelData.files
        this.images = this.modifyModelData.images
        if (Object.keys(this.modifyModelData.data).length > 0) {
          this.getModifyModelData()
        }
      }
      this.loaded = true
    },
    itemDisabled (value) {
      return (this.businessType === '新增' && value.addOrEdit === 'edit') ||
          (this.businessType === '修改' && value.addOrEdit === 'add')
    },
    async onSubmit () {
      this.$refs.selectForm.validate(async valid => {
        for (const key of Object.keys(this.form)) {
          if (this.form[key] === null || this.form[key] === '') {
            this.form[key] = undefined
          }
        }
        const requestForm = Object.assign({}, this.form)
        // 追加静默新增字段
        if (this.businessType === '新增') {
          for (const item of this.silenceAddJsonData) {
            switch (item.silencePurpose) {
              case 'createTime':
                requestForm[item.model] = formatDate('now')
                break
              case 'operator':
                requestForm[item.model] = this.currUser.name
                break
              case 'operatorId':
                requestForm[item.model] = this.currUser.id
                break
              case 'orgId':
                requestForm[item.model] = this.currUser.orgid
                break
            }
          }
          // 通过请求追加静默新增：自定义字段
          for (const item of this.silenceAddJsonData.filter((item) => item.silencePurpose === 'customize')) {
            requestForm[item.model] = await this.getSilenceSource(item.silenceSource, requestForm)
          }
        }
        const data = {
          valid: valid,
          form: requestForm
        }
        this.$emit('onSubmit', data)
      })
    },
    /**
     * 获取通过logic静默新增的字段
     * @param logicName logic名称
     * @param requestParameters 请求参数
     */
    async getSilenceSource (logicName, requestParameters) {
      const result = await post('/api/' + this.serviceName + '/logic/' + logicName, requestParameters)
      return result
    },
    /**
     * 获取被修改记录数据
     * @param modifyModelData 被修改记录的数据
     */
    getModifyModelData () {
      for (let i = 0; i < this.realJsonData.length; i++) {
        if (['FilesId', 'Images'].includes(this.realJsonData[i])) {
          // 附件需要跳过 因为会通过 modifyModelData中的files,images属性给upload赋值
          // 新增修改表单每次提交时只会提交最新添加的文件
          continue
        }
        const item = this.realJsonData[i]
        if (this.modifyModelData.data[item.model] || this.modifyModelData.data[item.model] === 0) {
          if (this.modifyModelData.data[item.model] instanceof Array) {
            this.form[item.model] = this.modifyModelData.data[item.model]
          } else {
            this.form[item.model] = this.modifyModelData.data[item.model] + ''
          }
        } else {
          this.form[item.model] = undefined
        }
      }
      // 追加版本号信息
      for (const item of this.versionJsonData) {
        if (!this.modifyModelData.data[item.model]) {
          this.form[item.model] = 0
        } else {
          this.form[item.model] = this.modifyModelData.data[item.model] + ''
        }
      }
    },
    onClose () {
      this.$emit('update:visible', false)
    }
  }
}
</script>
