<template>
  <div class="app-commodity">
    <div class="filter-container">
      <el-select
        v-model="listQuery.type"
        style="width: 200px"
        class="filter-item"
        @change="changeType"
      >
        <el-option v-for="(item,index) in productTypeConfs" :key="index" :label="getProductTypeName(item)" :value="item.value" />
      </el-select>
      <el-select
        v-model="listQuery.applicationId"
        :placeholder="$t('pages.payApplication.placeholder.application')"
        style="width: 200px"
        class="filter-item"
        collapse-tags
        @change="changeApplication"
      >
        <el-option
          v-for="item in appInfo.appList"
          :key="item.id"
          :label="item.appName"
          :value="item.id"
        >
          <span style="float: left;"> <sys-origin-icon :icon="item.appCode" :desc="item.appCode" /></span>
          <span style="float: left;margin-left:10px">{{ item.appName }}</span>
        </el-option>
      </el-select>
      <el-select
        v-model="listQuery.payCountryId"
        v-loading="loadingCountry"
        :placeholder="$t('pages.payApplication.placeholder.country')"
        style="width: 200px"
        class="filter-item"
        clearable
        @change="changeCountry"
      >
        <el-option
          v-for="item in countryList"
          :key="getPayCountryId(item)"
          :label="getCountryName(item)"
          :value="getPayCountryId(item)"
        >
          <span v-if="getCountryIcon(item)" style="float: left;"> <img :src="getCountryIcon(item)" width="30"></span>
          <span style="float: left;margin-left:10px">{{ getCountryName(item) }}</span>
        </el-option>
      </el-select>
      <el-select
        v-if="selectedApp.appCode === 'ASWAT'"
        v-model="listQuery.regionId"
        v-loading="loading"
        :placeholder="$t('pages.payApplication.placeholder.region')"
        style="width:120px;"
        class="filter-item"
        @change="changeRegion"
      >
        <el-option
          v-for="(item, index) in regions"
          :key="index"
          :label="item.regionName"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.shelf"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index ) in shelfStatusOptions"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model.trim="listQuery.id"
        v-number
        :placeholder="$t('pages.payApplication.placeholder.productId')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t('pages.payApplication.action.search') }}
      </el-button>
      <el-button
        class="filter-item"
        type="warning"
        icon="el-icon-refresh"
        :loading="syncRateLoading"
        @click="syncExchangeRate"
      >
        同步全球汇率
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        :disabled="!listQuery.regionId"
        @click="createCommodity"
      >
        {{ $t('pages.payApplication.action.add') }}
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column :label="$t('pages.payApplication.table.region')" prop="regionName" align="center" />
      <el-table-column :label="$t('pages.payApplication.table.country')" align="center" width="180">
        <template slot-scope="scope">
          <span v-if="getCommodityCountryIcon(scope.row)" style="display:inline-block;margin-right:6px;vertical-align:middle;">
            <img :src="getCommodityCountryIcon(scope.row)" width="28">
          </span>
          <span>{{ getCommodityCountryName(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.payApplication.table.goldAmount')" prop="content" align="center" />
      <el-table-column :label="$t('pages.payApplication.table.rewardAmount')" prop="awardContent" align="center" />
      <el-table-column :label="$t('pages.payApplication.table.priceUsd')" prop="amountUsd" align="center" />
      <el-table-column :label="$t('pages.payApplication.table.shelf')" prop="shelf" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelf"
            :active-value="true"
            :inactive-value="false"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.payApplication.table.actions')" align="center" width="80">
        <template slot-scope="scope">
          <el-button type="text" @click="clickEditCommodity(scope.row)">{{ $t('pages.payApplication.action.edit') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <edit-form
      v-if="appCommodityEditFormVisible"
      :row="selectedEditFrom"
      :country-list="countryList"
      @close="appCommodityEditFormVisible=false"
      @success="editFromSuccess"
    />
  </div>
</template>
<script>
import { regionConfigTable } from '@/api/sys'
import { productTypeConfs } from '@/constant/type'
import { pagePayCommodity, listPayOpenCountry, listPayOpenCountryByRegionId, switchShelfCommodity, syncPayOpenCountryExchangeRate } from '@/api/sys-pay'
import Pagination from '@/components/Pagination'
import EditForm from './edit-form'

export default {
  name: 'AppPaycommodityV2',
  components: { Pagination, EditForm },
  props: {
    appInfo: {
      type: Object,
      require: true,
      default: () => {}
    }
  },
  data() {
    return {
      productTypeConfs,
      shelfStatus: [
        { value: true, labelKey: 'pages.payApplication.shelfStatus.true' },
        { value: false, labelKey: 'pages.payApplication.shelfStatus.false' }
      ],
      appCommodityEditFormVisible: false,
      selectedEditFrom: {},
      selectedCountry: {},
      selectedApp: {},
      selectedRegion: '',
      regions: [],
      syncRateLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 30,
        id: '',
        applicationId: '',
        payCountryId: '',
        shelf: true,
        type: 'GOLD',
        regionId: ''
      },
      listLoading: false,
      countryList: [],
      loadingCountry: false,
      loading: false
    }
  },
  computed: {
    shelfStatusOptions() {
      return this.shelfStatus.map(item => ({
        ...item,
        label: this.$t(item.labelKey)
      }))
    }
  },
  watch: {
    appInfo: {
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.selectedApp = newVal.appSelect
        this.listQuery.applicationId = this.selectedApp.id
      },
      immediate: true
    }
  },
  created() {
    this.listRegion()
  },
  methods: {
    getProductTypeName(item) {
      const key = `pages.payApplication.productTypes.${item.value}`
      const label = this.$t(key)
      return label === key ? item.name : label
    },
    handleSwitchChange(row) {
      switchShelfCommodity(row.id, row.shelf)
        .then((res) => {})
        .catch(er => {
          row.shelf = !row.shelf
        })
    },
    changeType() {
      this.renderData()
    },
    changeApplication(val) {
      this.selectedApp = this.appInfo.appList.filter(item => item.id === val)[0]
      this.countryList = []
      this.selectedCountry = {}
      this.listQuery.payCountryId = ''
      this.listRegion()
    },
    changeCountry(val) {
      this.selectedCountry = this.getCountryByPayCountryId(val) || {}
      this.renderData()
    },
    loadOpenCountry(regionId) {
      const that = this
      that.loadingCountry = true
      const request = regionId ? listPayOpenCountryByRegionId(regionId) : listPayOpenCountry()
      request.then(res => {
        that.loadingCountry = false
        that.countryList = that.normalizeList(res.body)
        if (that.listQuery.payCountryId && !that.getCountryByPayCountryId(that.listQuery.payCountryId)) {
          that.listQuery.payCountryId = ''
          that.selectedCountry = {}
        }
      }).catch(er => {
        that.loadingCountry = false
        console.error(er)
      })
    },
    listRegion() {
      const that = this
      that.loading = true
      regionConfigTable({ 'sysOrigin': that.selectedApp.appCode }).then(res => {
        that.regions = res.body || []
        that.selectedRegion = that.regions[0]
        that.listQuery.regionId = that.selectedRegion ? that.selectedRegion.id : ''
        that.loading = false
        that.loadOpenCountry(that.listQuery.regionId)
      }).catch(er => {
        that.loading = false
        that.loadOpenCountry()
      })
    },
    changeRegion(val) {
      this.selectedRegion = this.regions.filter(item => item.id === val)[0]
      this.listQuery.payCountryId = ''
      this.selectedCountry = {}
      this.loadOpenCountry(val)
    },
    renderData(isClean) {
      const that = this
      that.listLoading = true
      if (isClean === true) {
        that.list = []
        that.listQuery.cursor = 1
      }
      pagePayCommodity(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleSearch() {
      this.renderData(true)
    },
    syncExchangeRate() {
      this.syncRateLoading = true
      syncPayOpenCountryExchangeRate().then(res => {
        const count = res.body || 0
        this.$opsMessage.success(`已同步 ${count} 个国家汇率`)
        this.syncRateLoading = false
        this.loadOpenCountry(this.listQuery.regionId)
      }).catch(er => {
        this.syncRateLoading = false
        console.error(er)
      })
    },
    handleClose() {
      // 去除校验
      this.$refs.form.clearValidate()
      this.formVisible = false
    },
    createCommodity() {
      this.selectedEditFrom = {
        'applicationId': this.listQuery.applicationId,
        'amountUsd': '',
        'selectApp': this.selectedApp,
        'payCountryIds': this.listQuery.payCountryId ? [this.listQuery.payCountryId] : []
      }
      if (this.selectedApp.appCode === 'ASWAT') {
        this.selectedEditFrom.regionId = this.selectedRegion.id
        this.selectedEditFrom.regionName = this.selectedRegion.regionName
      }
      this.appCommodityEditFormVisible = true
    },
    clickEditCommodity(row) {
      const that = this
      that.appCommodityEditFormVisible = true
      that.selectedEditFrom = Object.assign({}, row)
      that.selectedEditFrom.selectApp = this.selectedApp
      that.selectedEditFrom.country = that.getEditFromCountry(row)
      if (this.selectedApp.appCode === 'ASWAT') {
        this.selectedEditFrom.regionId = this.selectedRegion.id
        this.selectedEditFrom.regionName = this.selectedRegion.regionName
      }
    },
    editFromSuccess() {
      this.appCommodityEditFormVisible = false
      this.renderData()
    },
    normalizeList(body) {
      if (Array.isArray(body)) {
        return body
      }
      if (body && Array.isArray(body.records)) {
        return body.records
      }
      return []
    },
    getPayCountryId(item) {
      return item ? (item.id || item.payCountryId || '') : ''
    },
    getCountryBase(item) {
      return (item && (item.country || item.payCountry || item.countryInfo || item.sysCountryCode)) || {}
    },
    getCountryName(item) {
      if (!item) {
        return ''
      }
      const country = this.getCountryBase(item)
      return country.aliasName || country.countryName || country.enName || item.payCountryName || item.countryName || item.aliasName || item.enName || ''
    },
    getCountryIcon(item) {
      if (!item) {
        return ''
      }
      const country = this.getCountryBase(item)
      return country.nationalFlag || country.icon || item.nationalFlag || item.countryNationalFlag || item.payCountryNationalFlag || item.icon || ''
    },
    getCountryByPayCountryId(payCountryId) {
      if (!payCountryId) {
        return null
      }
      return this.countryList.find(item => String(this.getPayCountryId(item)) === String(payCountryId))
    },
    getCommodityCountrySource(row) {
      const payCountryId = row && row.payCountryId ? row.payCountryId : this.listQuery.payCountryId
      return this.getCountryByPayCountryId(payCountryId) || row || this.selectedCountry || {}
    },
    getCommodityCountryName(row) {
      return this.getCountryName(row) || this.getCountryName(this.getCommodityCountrySource(row)) || '-'
    },
    getCommodityCountryIcon(row) {
      return this.getCountryIcon(row) || this.getCountryIcon(this.getCommodityCountrySource(row))
    },
    getEditFromCountry(row) {
      const countrySource = this.getCommodityCountrySource(row)
      return {
        'icon': this.getCountryIcon(row) || this.getCountryIcon(countrySource),
        'currency': (row && row.currency) || countrySource.currency || '',
        'exchangeRate': (row && (row.usdExchangeRate || row.exchangeRate)) || countrySource.usdExchangeRate || '',
        'countryName': this.getCountryName(row) || this.getCountryName(countrySource)
      }
    }
  }
}
</script>
<style scoped lang="scss">
  .bottom {
    color: #666;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 25px;
    .line {
      display: flex;
      >div {
        width: 100%;
      }
    }
  }

</style>
