<template>
  <div class="edit-form application-commodity-edit-from">
    <el-dialog
      :visible="true"
      :modal-append-to-body="true"
      :append-to-body="true"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="80%"
      top="20px"
    >
      <div slot="title">
        <div class="flex-l">
          <sys-origin-icon :icon="row.selectApp.appCode" :desc="row.selectApp.appName" />
          {{ isUpdate ? $t('pages.payApplication.dialog.editProduct') : $t('pages.payApplication.dialog.createProduct') }}
        </div>
      </div>
      <div class="form-edit">
        <el-form ref="form" :model="form" :rules="localizedRules" label-width="100px">
          <el-form-item v-if="row.selectApp.appCode === 'ASWAT'" :label="$t('pages.payApplication.form.region')">
            <div class="flex-l">{{ regionName }}</div>
          </el-form-item>
          <el-form-item v-if="!isUpdate" label="支持国家" prop="payCountryIds">
            <el-select v-model="form.payCountryIds" multiple filterable collapse-tags style="width:100%" placeholder="请选择支持国家">
              <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-form-item>
          <el-form-item v-else :label="$t('pages.payApplication.form.saleCountry')">
            <div class="flex-l">
              <img v-if="rowCountry.icon" :src="rowCountry.icon" width="40"> {{ rowCountry.countryName || '-' }}
            </div>
          </el-form-item>
          <el-form-item :label="$t('pages.payApplication.form.status')" prop="shelf">
            <el-select
              v-model="form.shelf"
              style="width:100%"
            >
              <el-option
                v-for="(item, index ) in shelfStatusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!isUpdate" :label="$t('pages.payApplication.form.productType')" prop="type">
            <el-select v-model="form.type" style="width:100%">
              <el-option v-for="(item,index) in productTypeConfs" :key="index" :label="getProductTypeName(item)" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.payApplication.form.goldAmount')" prop="content">
            <el-input v-model="form.content" v-number :placeholder="$t('pages.payApplication.placeholder.goldAmount')" />
          </el-form-item>
          <el-form-item :label="$t('pages.payApplication.form.rewardAmount')" prop="awardContent">
            <el-input v-model="form.awardContent" v-number :placeholder="$t('pages.payApplication.placeholder.rewardAmount')" />
          </el-form-item>
          <el-form-item :label="$t('pages.payApplication.form.salePrice')" prop="amountUsd">
            <el-input v-model.trim="form.amountUsd" :placeholder="$t('pages.payApplication.placeholder.salePrice')" class="input-with-select" maxlength="10" @change="changeAmount">
              <template slot="append">USD</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="false" :label="$t('pages.payApplication.form.paymentChannel')">
            <div v-loading="associateLoading" />
            <el-collapse v-if="supportAmounts && supportAmounts.length > 0" v-model="activeNames">
              <el-collapse-item v-for="(item,index) in supportAmounts" :key="index" :name="item.channel.channelCode">
                <template slot="title">
                  <div class="flex-l">
                    <img class="channel-icon" :src="item.channel.channelIcon" alt="icon" width="30" height="30">
                    <div style="width: 100%;" class="channel-name nowrap-ellipsis">{{ item.channel.channelName }}</div>
                  </div>
                </template>
                <el-row v-for="(aItem,aIndex) in item.countryChannels" :key="aIndex" class="channel-item">
                  <el-col :md="8" class="col">
                    <div class="flex-l margin-top-10">
                      <img class="channel-icon" :src="aItem.payFactory.factoryIcon" alt="icon" width="30" height="30">
                      <div class="channel-name nowrap-ellipsis">{{ aItem.payFactory.factoryName }}</div>
                    </div>
                  </el-col>
                  <el-col :md="8" class="col" style="text-align: left;">
                    <div>{{ $t('pages.payApplication.form.salePrice') }}: <strong>{{ computedAmount }}</strong> {{ row.country.currency }}</div>
                    <div>{{ $t('pages.payApplication.form.salePrice') }}: <strong>{{ amountUsd }}</strong> USD</div>
                  </el-col>
                  <el-col :md="8" class="col" style="text-align: left;">
                    <div>
                      {{ $t('pages.payApplication.form.minLimit') }}: <strong>{{ aItem.countryChannelDetails.computedMinLimit }}</strong> {{ row.country.currency }}{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.maxLimit') }}: <strong>{{ aItem.countryChannelDetails.computedMaxLimit }} </strong>{{ row.country.currency }}{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.dailyLimit') }}: <strong>{{ aItem.countryChannelDetails.computedDailyLimit }} </strong>{{ row.country.currency }}
                    </div>
                    <div>
                      {{ $t('pages.payApplication.form.minLimit') }}: <strong>{{ aItem.countryChannelDetails.factoryMinLimit }}</strong> USD{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.maxLimit') }}: <strong>{{ aItem.countryChannelDetails.factoryMaxLimit }}</strong> USD{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.dailyLimit') }}: <strong>{{ aItem.countryChannelDetails.factoryDailyLimit }}</strong> USD
                    </div>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer">
        <el-button @click="handleClose()">{{ $t('pages.payApplication.action.cancel') }}</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm()">{{ $t('pages.payApplication.action.save') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { productTypeConfs } from '@/constant/type'
import { deepClone } from '@/utils'
import { validPositiveNumberPointTwo } from '@/utils/validate'
// listCountrytSupportAmountChannels
import { addOrUpdatePayCommodity } from '@/api/sys-pay'
export default {
  props: {
    row: {
      type: Object,
      require: false,
      default: () => {}
    },
    countryList: {
      type: Array,
      require: false,
      default: () => []
    }
  },
  data() {
    return {
      shelfStatus: [
        { value: true, labelKey: 'pages.payApplication.shelfStatus.true' },
        { value: false, labelKey: 'pages.payApplication.shelfStatus.false' }
      ],
      productTypeConfs,
      form: {
        applicationId: '',
        content: '',
        awardContent: '',
        amountUsd: '',
        type: '',
        payCountryIds: [],
        regionId: '',
        shelf: true
      },
      regionName: '',
      activeNames: '',
      submitLoading: false,
      associateLoading: false,
      supportAmounts: [],
      computedAmount: '',
      amountUsd: ''
    }
  },
  computed: {
    isUpdate() {
      return this.row && this.row.id
    },
    rowCountry() {
      const country = (this.row && this.row.country) || {}
      return {
        icon: country.icon || country.nationalFlag || '',
        currency: country.currency || '',
        countryName: country.countryName || country.aliasName || country.enName || ''
      }
    },
    shelfStatusOptions() {
      return this.shelfStatus.map(item => ({
        ...item,
        label: this.$t(item.labelKey)
      }))
    },
    localizedRules() {
      const commonRules = [
        { required: true, message: this.$t('pages.payApplication.validation.requiredField'), trigger: 'blur' }
      ]
      return {
        applicationId: commonRules,
        payCountryIds: commonRules,
        content: commonRules,
        awardContent: commonRules,
        type: commonRules,
        shelf: commonRules,
        amountUsd: {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (validPositiveNumberPointTwo(value)) {
              return callback()
            }
            return callback(new Error(this.$t('pages.payApplication.validation.positiveNumberPointTwo')))
          }
        }
      }
    }
  },
  watch: {
    row: {
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.form = deepClone(newVal)
        if (!this.form.payCountryIds || this.form.payCountryIds.length === 0) {
          this.$set(this.form, 'payCountryIds', this.form.payCountryId ? [this.form.payCountryId] : [])
        }
        if (!this.form.awardContent && this.form.awardContent !== 0) {
          this.$set(this.form, 'awardContent', '0')
        }
        if (this.form.shelf === '' || this.form.shelf === undefined || this.form.shelf === null) {
          this.$set(this.form, 'shelf', true)
        }
        if (!this.form.type) {
          this.$set(this.form, 'type', 'GOLD')
        }
        this.regionName = newVal.regionName
        this.loadSupportAmountChannels()
      },
      immediate: true
    }
  },
  methods: {
    getProductTypeName(item) {
      const key = `pages.payApplication.productTypes.${item.value}`
      const label = this.$t(key)
      return label === key ? item.name : label
    },
    handleClose() {
      this.$emit('close')
    },
    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 || ''
    },
    changeAmount(val) {
      if (!val || !validPositiveNumberPointTwo(val)) {
        this.supportAmounts = []
        this.computedAmount = ''
        this.amountUsd = ''
        return
      }
      this.loadSupportAmountChannels()
    },
    loadSupportAmountChannels() {
      const that = this
      that.associateLoading = true
      // listCountrytSupportAmountChannels(that.row.payCountryId, that.form.amountUsd)
      //   .then(res => {
      //     that.associateLoading = false
      //     const { channels, computedAmount, amountUsd } = res.result || {}
      //     that.supportAmounts = channels || []
      //     that.computedAmount = computedAmount
      //     that.amountUsd = amountUsd
      //   }).catch(er => {
      //     that.associateLoading = false
      //     console.error(er)
      //   })
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return
        }
        that.submitLoading = true
        addOrUpdatePayCommodity(that.form).then(res => {
          that.$opsMessage.success()
          that.submitLoading = false
          that.$emit('success')
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fail')
        })
      })
    }

  }
}
</script>
<style scoped lang="scss">
.dark-theme {
  .application-commodity-edit-from  {
    .channel-item {
      background-color: #4b5055 !important;
    }
  }
}

.application-commodity-edit-from {
  .channel-item {
    background-color: #ebf0f5;
  }
}
</style>
<style scoped lang="scss">
.form-edit {
  max-height: 70vh;
  overflow: auto;
  padding: 0px 20px;
  .channel-name {
    padding: 0px 5px;
  }
  .channel-icon {
      border-radius: 50%;
  }
  .col {
      padding: 0px 10px;
      text-align: center;
  }
  .margin-top-10 {
      margin-top: 10px;
  }
  .channel-item {
      padding: 10px 0px;
      border-radius: 5px;
  }
}

</style>
