<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 v-if="selectAppInfo.appCode" :icon="selectAppInfo.appCode" :desc="selectAppInfo.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 :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 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 :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> {{ rowCountry.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> {{ rowCountry.currency }}{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.maxLimit') }}: <strong>{{ aItem.countryChannelDetails.computedMaxLimit }} </strong>{{ rowCountry.currency }}{{ $t('pages.payApplication.word.separator') }}
                      {{ $t('pages.payApplication.form.dailyLimit') }}: <strong>{{ aItem.countryChannelDetails.computedDailyLimit }} </strong>{{ rowCountry.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'
import { addOrUpdatePayCommodity, listCountrytSupportAmountChannels } from '@/api/sys-pay'
export default {
  props: {
    row: {
      type: Object,
      require: false,
      default: () => ({})
    }
  },
  data() {
    return {
      productTypeConfs,
      form: {
        applicationId: '',
        payCountryId: '',
        content: '',
        awardContent: '',
        amountUsd: '',
        type: ''
      },
      activeNames: '',
      submitLoading: false,
      associateLoading: false,
      supportAmounts: [],
      computedAmount: '',
      amountUsd: ''
    }
  },
  computed: {
    selectAppInfo() {
      return (this.row && this.row.selectApp) || {}
    },
    rowCountry() {
      const country = (this.row && this.row.country) || {}
      return {
        icon: country.icon || country.nationalFlag || '',
        currency: country.currency || '',
        countryName: country.countryName || country.aliasName || country.enName || ''
      }
    },
    isUpdate() {
      return this.row && this.row.id
    },
    localizedRules() {
      const commonRules = [
        { required: true, message: this.$t('pages.payApplication.validation.requiredField'), trigger: 'blur' }
      ]
      return {
        applicationId: commonRules,
        payCountryId: commonRules,
        content: commonRules,
        awardContent: commonRules,
        type: 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)
        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')
    },
    changeAmount(val) {
      if (!val || !validPositiveNumberPointTwo(val)) {
        this.supportAmounts = []
        this.computedAmount = ''
        this.amountUsd = ''
        return
      }
      this.loadSupportAmountChannels()
    },
    loadSupportAmountChannels() {
      const that = this
      if (!that.row.payCountryId || !validPositiveNumberPointTwo(that.form.amountUsd)) {
        that.associateLoading = false
        that.supportAmounts = []
        that.computedAmount = ''
        that.amountUsd = ''
        return
      }
      that.associateLoading = true
      listCountrytSupportAmountChannels(that.row.payCountryId, that.form.amountUsd)
        .then(res => {
          that.associateLoading = false
          const { channels, computedAmount, amountUsd } = res.body || {}
          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>
