<template>
  <div class="pane-wrap right-detail-toolbar">
    <el-toolbar>
      <el-button :disabled="!modelId" priv="ContentCore.ExtendModelMenu.AddData" @click="addPkDataClickHandler">
        <i class="fa fa-plus"></i>添加</el-button>
    </el-toolbar>
    <div>
      <div align="right">
        <el-select class="layout-select" style="max-width:200px;" v-model="search.field" placeholder="请选择字段" :clearable="true" @change="fieldSelectChange">
          <el-option v-for="item in fields" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <component :is="getControlType(searchBarField)" v-model="search.query" :config="getControlConfig(searchBarField)" style="max-width: 220px;"></component>&nbsp;
        <el-button icon="search" @click="searchClickHandler" priv="Platform.Metadata.Edit" title="搜索"></el-button>
      </div>
      <div class="padding-vertical-max">
      <el-table class="extend-model-data-table"
        :data-read-url="getFieldDataUrl"
        :page-size="10"
        ref="dataTable"
        :auto-get-data="false"
        >
        <el-table-column label="PK值">
          <template slot-scope="scope">
            <el-button priv="ContentCore.ExtendModelMenu.EditData" type="text" class="table-title-button" :title="scope.row.PKValue" @click.stop="editPkDataClickHandler(scope.row)">{{scope.row.PKValue}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          v-for="field in fields"
          :key="field.code"
          :prop="field.code"
          :label="field.name">
          <template slot-scope="scope">
          {{scope.row.content[field.code]}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="right">
          <template slot-scope="scope">
            <el-button @click.stop="editPkDataClickHandler(scope.row)" type="text" priv="ContentCore.ExtendModelMenu.EditData" title="修改">
              <i class="fa fa-edit f16"></i></el-button>
            <el-button @click.stop="deletePkDataClickHandler(scope.row)" type="text" priv="ContentCore.ExtendModelMenu.DeleteData" title="删除">
              <i class="fa fa-times f16"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import ControlNumber from '../platform/components/control/ControlNumber.vue'
import ControlDatePicker from '../platform/components/control/ControlDatePicker.vue'
import ControlSelect from '../platform/components/control/ControlSelect.vue'
import ControlText from '../platform/components/control/ControlText.vue'
export default {
  components: {
    'control-select': ControlSelect,
    'control-text': ControlText,
    'control-number': ControlNumber,
    'control-date-picker': ControlDatePicker
  },

  props: {modelId: [String, Number]},

  data() {
    return {
      fields: [], // 字段数据
      pkData: [], // 表格数据
      search: {
        field: '',
        query: '',
        type: '',
        code: ''
      },
      searchBarField: {}
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.loadPKData()
      this.loadFieldList()
    })
  },

  methods: {
    getControlType(field, type) {
      if (
        field.controlType === 'Text' && (field.dataType === 'Long' || field.dataType === 'Double')
      ) {
        return 'control-number'
      }
      switch (field.controlType) {
        case 'Radio':
        case 'Select':
        case 'Checkbox':
          return 'control-select'
        case 'Text':
        case 'TextArea':
        case 'RichText':
          return 'control-text'
        case 'Date':
        case 'DateTime':
          return 'control-date-picker'
        default:
          return ''
      }
    },

    getControlConfig(field) {
      let config = {
        dataType: field.dataType
      }
      if (field.listOptions) {
        config.listOptions = field.listOptions
      }
      if (field.controlType === 'DateTime' || field.controlType === 'Date') {
        config.type = 'daterange'
      }
      if (field.controlType) {
        if (field.controlType.indexOf('Upload') >= 0) {
          config.resourceType = field.controlType.substring(0, field.controlType.length - 6)
        }
      }
      return config
    },

    // 添加或编辑弹框回调
    afterAddOrEdit() {
      this.loadPKData()
    },

    getFieldDataUrl() {
      let searchStart, searchEnd
      if (this.search.type === 'Date' || this.search.type === 'DateTime') {
        if (this.search.query) {
          searchStart = this.search.query[0]
          searchEnd = this.search.query[1]
        }
      }
      let params = {
        searchType: this.search.type,
        searchCode: this.search.code,
        searchQuery: encodeURIComponent(this.search.query),
        searchStart: searchStart,
        searchEnd: searchEnd
      }
      return [`/ui/contentextends/${this.modelId}/datas`, { params: params }]
    },

    fieldSelectChange(val) {
      if (val) {
        this.search.code = val
        Vue.set(this.search, 'query', '')
        this.searchBarField = this.fields.filter(value => value.code === val)[0]
        this.search.type = this.searchBarField.controlType
      } else {
        this.search = {}
        Vue.set(this.search, 'query', '')
      }
    },

    // 添加PKData
    addPkDataClickHandler() {
      this.$router.push({path: `/settings/extendModel/${this.modelId}/data/new`})
    },

    // 编辑PKData
    editPkDataClickHandler(row) {
      if (!row || !row.modelID) {
        util.showErrorMessageBox('数据异常，请重新尝试！')
        return
      }
      this.$router.push({path: `/settings/extendModel/${this.modelId}/data/${row.PKValue}`})
    },

    // 删除PKData
    async deletePkDataClickHandler(row) {
      let PKValues = row && row.PKValue
      if (!PKValues) {
        return
      }
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/contentextends/${this.modelId}/datas/${PKValues}`)
        util.showMessage(res)
        if (res.data.status === 1) {
          this.loadPKData()
        }
      } catch (e) {

      }
    },

    searchClickHandler() {
      this.loadPKData()
    },

    // 加载PKData
    loadPKData() {
      this.$refs.dataTable.getData()
    },

    async loadFieldList() {
      let res = await axios.get(`/ui/contentextends/${this.modelId}/columns`)
      this.fields = (res.data.data && res.data.data.length) ? res.data.data : []
    }
  }
}
</script>
<style scoped>
.el-pagination__rightwrapper {
    float: right;
}
</style>
<style>
.extend-model-data-table .cell {
  overflow: hidden;
  white-space: unset;
}
</style>
