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

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.productV2.action.add') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="sysOrigin" :label="$t('pages.productV2.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="productPackage" :label="$t('pages.productV2.table.packageName')" align="center" width="250" />
      <el-table-column prop="unitPrice" :label="$t('pages.productV2.table.unitPrice')" align="center" />
      <el-table-column prop="obtainCandy" :label="$t('pages.productV2.table.obtainCandy')" align="center" />
      <el-table-column prop="rewardCandy" :label="$t('pages.productV2.table.rewardCandy')" align="center" />
      <el-table-column prop="platform" :label="$t('pages.productV2.table.platform')" align="center" />
      <el-table-column prop="regionNameStr" :label="$t('pages.productV2.table.region')" align="center" />
      <el-table-column prop="description" :label="$t('pages.productV2.table.description')" align="center" />
      <el-table-column prop="sort" :label="$t('pages.productV2.table.sort')" align="center" />
      <el-table-column prop="createTime" :label="$t('pages.productV2.table.createdAt')" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.productV2.table.actions')" align="center">
        <template slot-scope="scope">
          <div>
            <el-button type="text" @click.native="handlUpdate(scope.row)">{{ $t('pages.productV2.action.edit') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogTitle"
      :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="localizedRules">
          <el-form-item :label="$t('pages.productV2.form.platform')" prop="platform">
            <el-select v-model="form.platform" :placeholder="$t('pages.productV2.placeholder.paymentPlatform')" style="width:100%;">
              <el-option
                v-for="item in platformOriginsV2"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="regionList" :label="$t('pages.productV2.form.region')">
            <el-select v-model="form.regionList" multiple :placeholder="$t('pages.productV2.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 :label="$t('pages.productV2.form.status')" prop="showcase">
            <el-select
              v-model="form.showcase"
              :placeholder="$t('pages.productV2.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 :label="$t('pages.productV2.form.packageName')" prop="productPackage">
            <el-input v-model.trim="form.productPackage" />
          </el-form-item>
          <el-form-item :label="$t('pages.productV2.form.unitPrice')" prop="unitPrice">
            <el-input v-model.trim="form.unitPrice" type="number" />
          </el-form-item>
          <el-form-item :label="$t('pages.productV2.form.obtainCandy')" prop="obtainCandy">
            <el-input v-model.trim="form.obtainCandy" v-number />
          </el-form-item>
          <el-form-item :label="$t('pages.productV2.form.rewardCandy')" prop="rewardCandy">
            <el-input v-model.trim="form.rewardCandy" v-number />
          </el-form-item>
          <el-form-item :label="$t('pages.productV2.form.description')" prop="description">
            <el-input v-model.trim="form.description" />
          </el-form-item>
          <el-form-item :label="$t('pages.productV2.form.sort')" prop="sort">
            <el-input v-model.trim="form.sort" type="number" :placeholder="$t('pages.productV2.placeholder.sort')" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{ $t('pages.productV2.action.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('pages.productV2.action.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { productConfigShowcase, platformOriginsV2 } from '@/constant/type'
import { regionConfigTable } from '@/api/sys'
import { listProduct, addProduct, updateProduct } from '@/api/product'
import { mapGetters } from 'vuex'

function getFormData() {
  return {
    platform: '',
    sysOrigin: '',
    rewardCandy: '',
    obtainCandy: '',
    unitPrice: '',
    productPackage: '',
    description: '',
    showcase: '',
    sort: '',
    id: '',
    regionList: []
  }
}
export default {
  name: 'ProductConfigV2',
  data() {
    return {
      platformOriginsV2,
      productConfigShowcase,
      thisRow: {},
      formVisible: false,
      textOptTitle: '',
      regions: [],
      form: getFormData(),
      submitLoading: false,
      loading: false,
      list: [],
      listQuery: {
        sysOrigin: 'HALAR',
        showcase: true,
        platform: 'AppStore',
        region: ''
      },
      listLoading: true,
      searchLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    dialogTitle() {
      return this.form && this.form.id ? this.$t('pages.productV2.dialog.editTitle') : this.$t('pages.productV2.dialog.addTitle')
    },
    productConfigShowcaseOptions() {
      return this.productConfigShowcase.map(item => ({
        ...item,
        label: this.getShowcaseLabel(item)
      }))
    },
    localizedRules() {
      return {
        sysOrigin: [
          { required: true, message: this.$t('pages.productV2.validation.systemRequired'), trigger: 'blur' }
        ],
        showcase: [
          { required: true, message: this.$t('pages.productV2.validation.statusRequired'), trigger: 'blur' }
        ],
        regionList: [
          { required: true, message: this.$t('pages.productV2.validation.regionRequired'), trigger: 'blur' }
        ],
        productPackage: [
          { required: true, message: this.$t('pages.productV2.validation.packageRequired'), trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: this.$t('pages.productV2.validation.unitPriceRequired'), trigger: 'blur' }
        ],
        obtainCandy: [
          { required: true, message: this.$t('pages.productV2.validation.obtainCandyRequired'), trigger: 'blur' }
        ],
        platform: [
          { required: true, message: this.$t('pages.productV2.validation.platformRequired'), trigger: 'blur' }
        ],
        maxManager: [
          { required: true, message: this.$t('pages.productV2.validation.maxManagerRequired'), trigger: 'blur' }
        ],
        sort: [
          { required: true, message: this.$t('pages.productV2.validation.sortRequired'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const that = this
    const querySystem = this.permissionsSysOriginPlatforms[0]
    if (!querySystem) {
      return
    }
    that.listQuery.sysOrigin = querySystem.value
    that.listRegion()
    that.renderData()
  },
  methods: {
    getShowcaseLabel(item) {
      const key = `pages.productV2.showcase.${item.value}`
      const label = this.$t(key)
      return label === key ? item.name : label
    },
    renderData() {
      const that = this
      that.listLoading = true
      listProduct(that.listQuery).then(res => {
        const { body } = res
        that.list = body
        that.searchLoading = that.listLoading = false
      }).catch(er => {
        that.searchLoading = that.listLoading = false
      })
    },
    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.searchLoading = true
      this.renderData(true)
    },
    handleCreate() {
      this.formVisible = true
      this.form = getFormData()
    },
    handlUpdate(row) {
      this.formVisible = true
      this.form = Object.assign(this.form, row)
    },
    handleClose() {
      this.formVisible = false
      this.resetForm()
    },
    resetForm() {
      this.form = getFormData()
    },
    changeSysOrigin() {
      this.listRegion()
      this.handleSearch()
    },
    submitForm() {
      const that = this
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true
          that.form.sysOrigin = that.listQuery.sysOrigin
          if (!that.form.id) {
            addProduct(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
          }

          updateProduct(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
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}

</style>
