<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.payRegionRelation.placeholder.system')"
        style="width: 120px"
        class="filter-item"
        @change="changeSysOrigin"
      >
        <el-option
          v-for="(item, index) in permissionsSysOriginPlatforms"
          :key="index"
          :label="item.label"
          :value="item.value"
        >
          <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-select
        v-model="listQuery.region"
        v-loading="loading"
        :placeholder="$t('pages.payRegionRelation.placeholder.region')"
        style="width:120px;"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in regions"
          :key="index"
          :label="item.regionName"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.showcase"
        :placeholder="$t('pages.payRegionRelation.placeholder.status')"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="item in productConfigShowcaseOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        :loading="loading"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t('pages.payRegionRelation.action.search') }}
      </el-button>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.payRegionRelation.action.add') }}
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      :element-loading-text="$t('pages.payRegionRelation.word.loading')"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" :label="$t('pages.payRegionRelation.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="regionName" :label="$t('pages.payRegionRelation.table.region')" align="center" width="250" />
      <el-table-column prop="relationDesc" :label="$t('pages.payRegionRelation.table.relatedData')" align="center" />
      <el-table-column prop="showcase" :label="$t('pages.payRegionRelation.table.status')" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.showcase ? $t('pages.payRegionRelation.status.enabled') : $t('pages.payRegionRelation.status.disabled') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.payRegionRelation.table.actions')" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="text" @click.native="handlUpdate(scope.row)">{{ $t('pages.payRegionRelation.action.edit') }}</el-button>
          </div>
        </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="40%"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" label-width="110px" :rules="rules">
          <el-form-item prop="region" :label="$t('pages.payRegionRelation.form.region')">
            <el-select v-model="form.regionId" :placeholder="$t('pages.payRegionRelation.placeholder.select')" style="width:100%;">
              <el-option
                v-for="(item, index) in regions"
                :key="index"
                :label="item.regionName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.id" prop="relationIds" :label="$t('pages.payRegionRelation.form.enabledCountries')">
            <el-select v-model="form.relationIds" :placeholder="$t('pages.payRegionRelation.placeholder.select')" style="width:100%;">
              <el-option
                v-for="(item, index) in countryList"
                :key="index"
                :label="item.country.countryName"
                :value="item.id"
              >
                <span style="float: left;">
                  <img :src="item.country.nationalFlag" style="width: 28px; height: 18px;margin: 0px 2px;">
                </span>
                <span style="float: left;margin-left:10px">{{ item.country.countryName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!form.id" prop="relationIds" :label="$t('pages.payRegionRelation.form.enabledCountries')">
            <el-select v-model="form.relationIds" multiple :placeholder="$t('pages.payRegionRelation.placeholder.select')" style="width:100%;">
              <el-option
                v-for="(item, index) in countryList"
                :key="index"
                :label="item.country.countryName"
                :value="item.id"
              >
                <span style="float: left;">
                  <img :src="item.country.nationalFlag" style="width: 28px; height: 18px;margin: 0px 2px;">
                </span>
                <span style="float: left;margin-left:10px">{{ item.country.countryName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.payRegionRelation.form.status')" prop="showcase">
            <el-select
              v-model="form.showcase"
              :placeholder="$t('pages.payRegionRelation.placeholder.status')"
              class="filter-item"
              style="width:100%;"
            >
              <el-option
                v-for="item in productConfigShowcaseOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{ $t('pages.payRegionRelation.action.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('pages.payRegionRelation.action.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { productConfigShowcase } from '@/constant/type'
import { listPayOpenCountry } from '@/api/sys-pay'
import Pagination from '@/components/Pagination'
import { regionRelationTable, updateRegionRelation, addRegionRelation, regionConfigTable } from '@/api/sys'
import { mapGetters } from 'vuex'

function getFormData() {
  return {
    id: '',
    sysOrigin: '',
    regionId: '',
    groupType: 'OPEN_PAY_COUNTRY',
    relationIds: [],
    showcase: true
  }
}
export default {
  name: 'RegionRelation',
  components: { Pagination },
  data() {
    return {
      productConfigShowcase,
      loadingCountry: false,
      thisRow: {},
      formVisible: false,
      textOptTitle: 'pages.payRegionRelation.dialog.addTitle',
      regions: [],
      countryList: [],
      form: getFormData(),
      submitLoading: false,
      loading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        sysOrigin: 'HALAR',
        groupType: 'OPEN_PAY_COUNTRY',
        relationId: '',
        region: '',
        showcase: true
      }
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    productConfigShowcaseOptions() {
      return this.productConfigShowcase.map(item => ({
        ...item,
        label: this.getShowcaseName(item.value, item.name)
      }))
    },
    rules() {
      return {
        relationIds: [
          { required: true, message: this.$t('pages.payRegionRelation.validation.selectRelatedData'), trigger: 'blur' }
        ],
        regionId: [
          { required: true, message: this.$t('pages.payRegionRelation.validation.selectRegion'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const that = this
    that.listRegion()
    that.loadOpenCountry()
    that.renderData()
  },
  methods: {
    renderData(isClean) {
      const that = this
      if (isClean === true) {
        that.list = []
        that.listQuery.cursor = 1
      }
      that.loading = true
      regionRelationTable(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.loading = false
      }).catch(er => {
        that.loading = false
        console.error(er)
      })
    },
    loadOpenCountry() {
      const that = this
      that.loading = true
      listPayOpenCountry().then(res => {
        that.loading = false
        that.countryList = res.body || []
      }).catch(er => {
        that.loading = false
        console.error(er)
      })
    },
    listRegion() {
      const that = this
      that.loading = true
      regionConfigTable({ 'sysOrigin': that.listQuery.sysOrigin }).then(res => {
        that.regions = res.body || []
        that.loading = false
      }).catch(er => {
        that.loading = false
      })
    },
    handleSearch() {
      this.loading = false
      this.renderData(true)
    },
    handleCreate() {
      this.textOptTitle = 'pages.payRegionRelation.dialog.addTitle'
      this.formVisible = true
      this.form.relationIds = []
      this.form = getFormData()
    },
    handlUpdate(row) {
      this.textOptTitle = 'pages.payRegionRelation.dialog.editTitle'
      this.formVisible = true
      this.form = Object.assign(this.form, row)
      this.form.relationIds = row.relationId
    },
    handleClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    changeSysOrigin() {
      this.listRegion()
      this.handleSearch()
    },
    getShowcaseName(value, fallback) {
      const key = `pages.payRegionRelation.statusOptions.${value}`
      const translatedName = this.$t(key)
      return translatedName === key ? fallback : translatedName
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          that.form.sysOrigin = that.listQuery.sysOrigin
          if (!that.form.id) {
            addRegionRelation(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')
            })
            return
          }
          that.form.relationIds = [that.form.relationIds]
          updateRegionRelation(that.form).then(res => {
            that.$opsMessage.success()
            that.submitLoading = false
            that.formVisible = false
            that.resetForm()
            that.renderData(false)
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
            this.$emit('fail')
          })
        } else {
          console.error('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}

</style>
