<template>
  <div>

    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.familyConfig.action.add') }}
      </el-button>
    </div>
    <el-alert
      :title="$t('pages.familyConfig.alert.title')"
      type="warning"
      :closable="false"
    >
      {{ $t('pages.familyConfig.alert.singleCreateRule') }}
    </el-alert>
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('pages.familyConfig.loading')"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" :label="$t('pages.familyConfig.table.system')" align="center">
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column prop="userWealthLevel" :label="$t('pages.familyConfig.table.minWealthLevel')" align="center" />
      <el-table-column prop="payCandy" :label="$t('pages.familyConfig.table.createCost')" align="center" />
      <el-table-column fixed="right" :label="$t('pages.familyConfig.table.actions')" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="text" @click.native="handlUpdate(scope.row)">{{ $t('pages.familyConfig.action.edit') }}</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" :label="$t('pages.familyConfig.table.createdAt')" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      :title="$t(textOptTitle)"
      :visible.sync="formVisible"
      :modal-append-to-body="true"
      :append-to-body="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="400px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" label-width="140px" :rules="rules">
          <el-form-item
            :label="$t('pages.familyConfig.form.system')"
            prop="sysOrigin"
          >
            <el-select
              v-model="form.sysOrigin"
              :placeholder="$t('pages.familyConfig.placeholder.system')"
              style="width:100%;"
              class="filter-item"
            >
              <el-option
                v-for="(item, index) in permissionsSysOriginPlatforms"
                :key="index"
                :label="item.label"
                :value="item.value"
                class="filter-item"
              >
                <span style="float: left;"> <sys-origin-icon :icon="item.value" :desc="item.value" /></span>
                <span style="float: left;margin-left:10px">{{ item.label }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.familyConfig.form.wealthLevel')" prop="userWealthLevel">
            <el-input v-model.trim="form.userWealthLevel" type="number" />
          </el-form-item>
          <el-form-item :label="$t('pages.familyConfig.form.createCost')" prop="payCandy">
            <el-input v-model.trim="form.payCandy" type="number" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{ $t('pages.familyConfig.action.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('pages.familyConfig.action.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { pageCreateRule, addOrUpdateCreateRule } from '@/api/family'
import { mapGetters } from 'vuex'
function getFormData() {
  return {
    userWealthLevel: 0,
    sysOrigin: '',
    payCandy: 0,
    id: ''
  }
}
export default {
  name: 'ConfigCreateRole',
  components: {
    Pagination
  },
  data() {
    return {
      thisRow: {},
      formVisible: false,
      textOptTitle: '',
      form: getFormData(),
      submitLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: ''
      },
      listLoading: true,
      searchLoading: false
    }
  },
  computed: {
    rules() {
      return {
        sysOrigin: [
          { required: true, message: this.$t('pages.familyConfig.validation.selectSystem'), trigger: 'blur' }
        ],
        payCandy: [
          { required: true, message: this.$t('pages.familyConfig.validation.enterCost'), trigger: 'blur' }
        ],
        userWealthLevel: [
          { required: true, message: this.$t('pages.familyConfig.validation.enterWealthLevel'), trigger: 'blur' }
        ]
      }
    },
    ...mapGetters(['permissionsSysOriginPlatforms'])
  },
  created() {
    this.renderData(true)
  },
  methods: {
    renderData(isReset) {
      const that = this
      if (isReset === true) {
        that.listQuery.cursor = 1
      }
      that.listLoading = true
      pageCreateRule(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.searchLoading = that.listLoading = false
      }).catch(er => {
        that.searchLoading = that.listLoading = false
      })
    },
    handleSearch() {
      this.searchLoading = true
      this.renderData(true)
    },
    handleCreate() {
      this.textOptTitle = 'pages.familyConfig.dialog.addCreateRule'
      this.formVisible = true
      this.form = getFormData()
    },
    handlUpdate(row) {
      this.textOptTitle = 'pages.familyConfig.dialog.editCreateRule'
      this.formVisible = true
      this.form = Object.assign(this.form, row)
    },
    handleClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    querySearch(queryString, cb) {
      var results = queryString ? this.restaurants.filter(this.createFilter(queryString)) : this.restaurants
      // Return the suggestion list through the callback.
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) || (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          addOrUpdateCreateRule(that.form).then(res => {
            that.$opsMessage.success()
            that.submitLoading = false
            that.formVisible = false
            that.resetForm()
            that.renderData(true)
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
            this.$emit('fail')
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    },
    renderDataSuccess() {
      this.$message({
        message: this.$t('pages.familyConfig.message.success'),
        type: 'success'
      })
      this.renderData()
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}

</style>
