<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :priv="dataID === 'new' ? 'ContentCore.ExtendModelMenu.AddData':'ContentCore.ExtendModelMenu.EditData'" :loading="confirmLoading" @click="confirm"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div>
      <div class="detail-panel">
        <el-form :model="tmpPkData" ref="pkDataForm" label-width="230px" label-suffix="：">
          <el-form-item label="PK值" prop="PKValue" :verify="['NotNull','Regex=^[a-zA-Z0-9_\.\-\/]+$|请输入英文字母、数字、下划线']">
            <el-input v-model="tmpPkData.PKValue"></el-input>
          </el-form-item>
          <div class="filed-group" v-for="group in fieldGroup" :key="group.code">
            <h4 class="group-name">{{group.name}}</h4>
            <z-form-item v-for="field in getGroupFields(group.code)" :data-var="'content['+field.code+']'" :key="field.code" :field="field">
              <component :is="getControlType(field)" v-model="tmpPkData.content[field.code]"
                :config="getControlConfig(field)"></component>
            </z-form-item>
          </div>
          <h3></h3>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import ControlPassword from '../platform/components/control/ControlPassword.vue'
import ControlRadio from '../platform/components/control/ControlRadio.vue'
import ControlCheckbox from '../platform/components/control/ControlCheckbox.vue'
import ControlSelect from '../platform/components/control/ControlSelect.vue'
import ControlText from '../platform/components/control/ControlText.vue'
import ControlTextArea from '../platform/components/control/ControlTextArea.vue'
import ControlNumber from '../platform/components/control/ControlNumber.vue'
import ControlDatePicker from '../platform/components/control/ControlDatePicker.vue'
import ControlUpload from '../platform/components/control/ControlUpload.vue'
import ControlRichText from '../platform/components/control/ControlRichText.vue'
import FormItem from '../platform/components/control/FormItem.vue'
export default {
  components: {
    'control-password': ControlPassword,
    'control-radio': ControlRadio,
    'control-select': ControlSelect,
    'control-text': ControlText,
    'control-text-area': ControlTextArea,
    'control-number': ControlNumber,
    'control-checkbox': ControlCheckbox,
    'control-date-picker': ControlDatePicker,
    'control-date-upload': ControlUpload,
    'control-rich-text': ControlRichText,
    'z-form-item': FormItem
  },

  props: {
    datas: Object,
    modelId: [Number, String],
    dataID: String
  },

  data() {
    return {
      tmpPkData: {PKValue: '', content: {}}, // form表单数据
      fieldGroup: [], // 分组数据
      fields: [], // 字段数据
      confirmLoading: false
    }
  },

  async created() {
    await this.initData()
    this.initFieldWithDefault()
  },

  methods: {
    initFieldWithDefault() {
      this.fieldGroup.forEach(group => {
        group.columns.forEach(field => {
          if (!this.tmpPkData.content[field.code]) {
            Vue.set(this.tmpPkData.content, field.code, field.defaultValue)
          }
        })
      })
    },

    // 提交添加或编辑事件
    async confirm() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['pkDataForm'])
        let res = ''
        this.fields.forEach(val => {
          if (val.controlType === 'Checkbox') {
            if (this.tmpPkData.content[val.code]){
              this.tmpPkData[val.code] = this.tmpPkData.content[val.code].join(',')
            }
          }
        })
        if (this.isEdit()) {
          res = await axios.put(`/ui/contentextends/${this.modelId}/datas/${this.dataID}`, this.tmpPkData)
        } else {
          res = await axios.post(`/ui/contentextends/${this.modelId}/datas`, this.tmpPkData)
        }
        this.confirmLoading = false
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.goBack()
        }
      } catch (e) {
        util.showErrorMessageBox(e)
        this.confirmLoading = false
      }
    },

    async initData() {
      if (this.isEdit()) {
        let res = await axios.get(`/ui/contentextends/${this.modelId}/datas/${this.dataID}`)
        this.tmpPkData = Object.assign({PKValue: this.dataID}, res.data.data)
      }
      await this.loadColumnGroup()
      await this.loadFields()
    },

    // 加载元数据字段分组
    async loadColumnGroup() {
      let res = await axios.get(`/ui/contentextends/${this.modelId}/groups`)
      this.fieldGroup = (res.data.data && res.data.data.length) ? res.data.data : []
    },

    async loadFields() {
      let res = await axios.get(`/ui/contentextends/${this.modelId}/columns`)
      this.fields = (res.data.data && res.data.data.length) ? res.data.data : []
    },

    // 获取某个分组字段
    getGroupFields(code) {
      let tmpFields = this.fields.concat()
      return tmpFields.filter(val => val.groupCode === code)
    },

    // 获取控件类型
    getControlType(field) {
      if (field.controlType === 'Text' && (field.dataType === 'Long' || field.dataType === 'Double')) {
        return 'control-number'
      }
      switch (field.controlType) {
        // case 'Password':
        //   return 'control-password'
        case 'Radio':
          return 'control-radio'
        case 'Select':
          return 'control-select'
        case 'Text':
          return 'control-text'
        case 'TextArea':
          return 'control-text-area'
        case 'Checkbox':
          return 'control-checkbox'
        case 'Date':
          return 'control-date-picker'
        case 'DateTime':
          return 'control-date-picker'
        case 'RichText':
          return 'control-rich-text'
        case 'ImageUpload':
        case 'FileUpload':
        case 'AudioUpload':
        case 'VideoUpload':
          return 'control-date-upload'
        default:
          return ''
      }
    },
    // 获取控件配置
    getControlConfig (field) {
      let config = {
        dataType: field.dataType
      }

      if (field.listOptions) {
        config.listOptions = field.listOptions
      }

      if (field.controlType === 'DateTime') {
        config.type = 'datetime'
      }
      if (['ImageUpload', 'FileUpload', 'AudioUpload', 'VideoUpload'].includes(field.controlType)) {
        config.resourceType = field.controlType.substring(0, field.controlType.length - 6)
      }
      return config
    },

    isEdit() {
      return this.dataID && this.dataID !== 'new'
    },

    goBack() {
      this.$router.back()
    }
  }
}
</script>
<style scoped>
.el-form-item .el-input {
  width: 200px;
  margin-right: 5px;
}
.el-form-item .el-textarea {
  width: 200px;
  margin-right: 5px;
}
.filed-group .group-name{
  padding: 10px 0;
  font-size: 16px;
  font-weight: 700;
  color:#8391A5;
}
</style>
