<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页
      </el-button>
      <span class="button-separator"></span>
      <el-button :loading="confirmLoading" @click="confirmPkDataClickHandler" priv="Platform.Metadata.EditData">
        <i class="fa fa-save"></i>保 存
      </el-button>
    </el-toolbar>
    <div class="detail-panel form-panel">
      <el-form :model="tmpPkData" ref="pkDataForm" label-width="230px" class="metadata-data-from" label-suffix="：">
        <el-form-item label="PK值" prop="PKValue" :verify="['NotNull']">
          <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-from-item v-for="field in getGroupFields(group.code)" :key="field.ID" :field="field">
            <component :is="getControlType(field)" v-model="tmpPkData.content[field.code]"
              :config="getControlConfig(field)"></component>
          </z-from-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import ControlPassword from './components/control/ControlPassword.vue'
import ControlRadio from './components/control/ControlRadio.vue'
import ControlCheckbox from './components/control/ControlCheckbox.vue'
import ControlSelect from './components/control/ControlSelect.vue'
import ControlText from './components/control/ControlText.vue'
import ControlTextArea from './components/control/ControlTextArea.vue'
import ControlNumber from './components/control/ControlNumber.vue'
import ControlDatePicker from './components/control/ControlDatePicker.vue'
import ControlUpload from './components/control/ControlUpload.vue'
import ControlRichText from './components/control/ControlRichText.vue'
import FromItem from './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-from-item': FromItem
  },
  props: {
    pk: {
      type: [Number, String],
      default: 0
    },
    modelID: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      datas: {},
      tempData: {},
      tmpPkData: { PKValue: '', content: {} }, //  form表单数据
      oldPKValue: 0, //  编辑时的PKValue
      fieldGroup: [], //  分组数据
      fields: [], //  字段数据
      tempFields: [],
      confirmLoading: false
    }
  },
  created() {
    this.beforeDialogOpen()
  },
  methods: {
    async loadDataByPKValue() {
      let res = await axios.get(`/ui/metamodels/${this.modelID}/datas/${this.pk}`)
      this.tmpPkData = res.data.data ? res.data.data : {}
    },
    async loadFieldList() {
      let res = await axios.get(`/ui/metamodels/${this.modelID}/columns`)
      this.tempFields = res.data.data && res.data.data.length ? res.data.data : []
    },
    // 提交添加或编辑事件
    async confirmPkDataClickHandler() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['pkDataForm'])
        let res = ''
        if (this.pk === 'new') {
          res = await axios.post(`/ui/metamodels/${this.modelID}/datas`, this.tmpPkData)
        } else {
          res = await axios.put(`/ui/metamodels/${this.modelID}/datas/${this.pk}`, this.tmpPkData)
        }
        this.confirmLoading = false
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.$router.back()
        }
      } catch (e) {
        util.showErrorMessageBox(e)
        this.confirmLoading = false
      }
    },
    async beforeDialogOpen() {
      if (this.pk === 'new') {
        await this.loadFieldList()
        let pk = {
          PKValue: '',
          content: {}
        }
        this.tempFields.forEach(val => {
          switch (val.dataType) {
            case 'Long':
              pk.content[val.code] = 0
              break
            case 'Double':
              pk.content[val.code] = 0.0
              break
            case 'Datetime':
              pk.content[val.code] = new Date()
              break
            default:
              pk.content[val.code] = val.defaultValue || ''
              break
          }
          if (val.controlType === 'Checkbox') {
            pk.content[val.code] = []
          }
        }, this)
        this.tmpPkData = pk
        this.oldPKValue = !pk.PKValue ? 0 : pk.PKValue
      } else if (this.pk !== 0) {
        await this.loadDataByPKValue()
      }
      this.loadColumnGroup()
      this.loadFields()
    },
    // 加载元数据字段分组
    async loadColumnGroup() {
      let res = await axios.get(`/ui/metamodels/${this.modelID}/groups`)
      this.fieldGroup = res.data.data && res.data.data.length ? res.data.data : []
    },
    async loadFields() {
      let res = await axios.get(`/ui/metamodels/${this.modelID}/columns`)
      this.fields = res.data.data && res.data.data.length ? res.data.data : []
    },
    // 获取某个分组字段
    getGroupFields(groupCode) {
      let tmpFields = this.fields.concat()
      return tmpFields.filter(val => val.groupCode === groupCode)
    },
    // 获取控件类型
    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.dataType = 'DateTime'
      }
      if (['ImageUpload', 'FileUpload', 'AudioUpload', 'VideoUpload'].includes(field.controlType)) {
        config.resourceType = field.controlType.substring(0, field.controlType.length - 6)
      }
      return config
    }
  }
}
</script>
<style>
.metadata-data-from .el-form-item .el-input {
  width: 330px;
  margin-right: 5px;
}
.metadata-data-from .el-form-item .el-textarea {
  width: 330px;
  margin-right: 5px;
}
.metadata-data-from .filed-group .group-name {
  padding: 10px 0;
  font-size: 16px;
  font-weight: 700;
  color: #8391a5;
}
</style>
