<template>
  <div class="cnf-product-edit">

    <el-dialog
      :title="title + '('+sysOriginName+')'"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="550px"
      top="50px"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="(tabItem, tabIndex) in tabs" :key="tabIndex" :label=" tabItem.title" :name="tabItem.name">
          <div v-loading="submitLoading" style="height: 500px;overflow: auto;">
            <el-form
              :ref="'form_' + tabIndex"
              style="width: 400px; margin-left:50px;"
              :model="tabItem.form"
              :rules="rules"
            >
              <el-form-item v-if="!isEdit" label="关联产品" prop="productId">
                <el-select
                  v-model="tabItem.form.productPoolIndex"
                  v-loading="listProductPoolLoading"
                  placeholder="关联产品"
                  :disabled="isDisabled"
                  class="filter-item"
                  style="width:100%;"
                  @change="productPoolChange"
                >
                  <el-option
                    v-for="(item, index) in productPools"
                    :key="item.id"
                    :value="index"
                    :label="item.productDesc+ '-'+ item.unitPrice + '('+item.productId+')'"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item v-if="!isEdit" label="关联包名" prop="productPackage">
                <el-input v-model.trim="tabItem.form.productPackage" type="text" />
              </el-form-item> -->
              <el-form-item label="获得金币" prop="obtainCandy">
                <el-input v-model.trim="tabItem.form.obtainCandy" :disabled="isDisabled" oninput="value=value.replace(/[^\d^\.]/g,'')" type="text" />
              </el-form-item>
              <el-form-item label="奖励金币" prop="rewardCandy">
                <el-input v-model.trim="tabItem.form.rewardCandy" :disabled="isDisabled" oninput="value=value.replace(/[^\d^\.]/g,'')" type="text" />
              </el-form-item>
              <el-form-item label="优惠比率" prop="discountRate">
                <el-input v-model="tabItem.form.discountRate" v-number :disabled="isDisabled" type="text" />
              </el-form-item>
              <el-form-item label="状态" prop="showcase">
                <el-select
                  v-model="tabItem.form.showcase"
                  :disabled="syncAll"
                  placeholder="状态"
                  class="filter-item"
                  style="width:100%;"
                >
                  <el-option
                    v-for="item in productConfigShowcase"
                    :key="item.value"
                    :value="item.value"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="标签">
                <el-select
                  v-model="tabItem.form.tags"
                  :disabled="isDisabled"
                  clearable
                  placeholder="标签"
                  class="filter-item"
                  style="width:100%;"
                >
                  <el-option
                    v-for="item in productTags"
                    :key="item.value"
                    :value="item.value"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-tooltip placement="top">
        <div slot="content">
          <p v-if="isEdit" class="font-danger">修改操作：需同步平台不存在不会自动创建</p>
          <p v-else>请确认参数无误，同步将锁定参数不可输入！！！</p>
        </div>
        <el-checkbox v-model="syncAll" @click.native.prevent="handleSyncAllClick">同步所有平台</el-checkbox>
      </el-tooltip>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">保存</el-button>
        <el-button @click="handleClose()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { sysOriginPlatforms } from '@/constant/origin'
import { addBatchProductConfigInfo, updateProductConfigInfo, getProductConfigInfo, listProductPool } from '@/api/product'
import { productConfigGroupNames, productConfigShowcase, productTypes, platformOrigins, productTags, productPositions } from '@/constant/type'
function getFormData() {
  return {
    id: '',
    productId: '',
    productPoolIndex: '',
    productPackage: '',
    productType: '',
    description: '',
    groupName: '',
    unitPrice: '',
    obtainCandy: '',
    rewardCandy: '',
    platform: 'iOS',
    sort: '0',
    discountRate: '',
    showcase: true,
    checkProperty: false,
    tags: ''
  }
}

export default {
  name: 'CnfProductEdit',
  props: {
    sysOrigin: {
      type: String,
      required: true
    },
    platform: {
      type: String,
      required: true
    },
    editId: {
      type: String,
      required: false,
      default: null
    }
  },
  data() {
    var commonRequiredParams = [{ required: true, message: '必填参数不可为空', trigger: 'blur' }]
    return {
      productPools: [],
      title: '添加',
      tabs: [],
      productPositions,
      productTags,
      platformOrigins,
      productConfigShowcase,
      productConfigGroupNames,
      productTypes,
      syncAll: false,
      activeName: 'iOS',
      form: getFormData(),
      submitLoading: false,
      rules: {
        productId: commonRequiredParams,
        productPackage: commonRequiredParams,
        productType: commonRequiredParams,
        description: commonRequiredParams,
        groupName: commonRequiredParams,
        unitPrice: commonRequiredParams,
        obtainCandy: commonRequiredParams,
        rewardCandy: commonRequiredParams,
        platform: commonRequiredParams,
        sort: commonRequiredParams,
        discountRate: commonRequiredParams,
        showcase: commonRequiredParams,
        positionIndex: commonRequiredParams
      },
      sysOriginPlatformMap: {},
      sysOriginName: ''
    }
  },
  computed: {
    isEdit() {
      return this.editId && this.editId.length > 0
    },
    isDisabled() {
      return this.syncAll && !this.isEdit
    }
  },
  watch: {
    platform: {
      handler(newVal) {
        this.activeName = newVal
        this.addTab(newVal, getFormData())
      },
      immediate: true
    },
    editId: {
      handler(newVal) {
        if (newVal) {
          this.title = '修改'
          this.submitLoading = true
          getProductConfigInfo(newVal).then(res => {
            this.submitLoading = false
            this.tabs[0].form = res.body
          }).catch(er => {
            this.submitLoading = false
          })
          return
        }
        this.title = '添加'
      },
      immediate: true
    }
  },
  created() {
    const that = this
    sysOriginPlatforms.forEach(item => {
      that.sysOriginPlatformMap[item.value] = item
    })
    that.sysOriginName = that.sysOriginPlatformMap[that.sysOrigin].label
    that.listProductPoolLoading = true
    listProductPool().then(res => {
      that.listProductPoolLoading = false
      const { body } = res
      that.productPools = body || []
    }).catch(er => {
      that.listProductPoolLoading = false
    })
  },
  methods: {
    addTab(platform, form) {
      form.productPackage = ''
      form.platform = platform
      this.tabs.push({
        title: platform,
        name: platform,
        form
      })
    },
    handleClose() {
      this.$emit('close')
    },
    handleSyncAllClick() {
      if (this.tabs.length === 1) {
        this.$refs['form_0'][0].validate(valid => {
          if (valid) {
            if (!this.isEdit) {
              this.syncAll = true
              this.addTab(this.allPlatform(), deepClone(this.tabs[0].form))
              return
            }
            this.syncAll = !this.syncAll
            return
          }
          this.syncAll = false
        })
        return
      }
      this.syncAll = !this.syncAll
      this.tabs = this.tabs.slice(0, 1)
      this.activeName = this.platform
    },
    allPlatform() {
      return this.platform === 'iOS' ? 'Android' : 'iOS'
    },
    handleGroupNameChange(value) {
      if (value === 'VIP') {
        this.form.showcase = true
      }
    },
    getSubmitParams() {
      return this.tabs.map(item => item.form)
    },
    submitForm() {
      const that = this
      let index = 0
      let checkParamPass = true
      for (const key in that.$refs) {
        if (that.$refs[key] && that.$refs[key].length > 0) {
          that.$refs[key][0].validate(valid => {
            if (!valid) {
              checkParamPass = false
              that.activeName = that.tabs[index].name
              return
            }
          })
          ++index
        }
      }

      if (checkParamPass === true) {
        if (!that.editId) {
          addBatchProductConfigInfo({
            sysOrigin: that.sysOrigin,
            configs: that.getSubmitParams()
          }).then(res => {
            that.submitLoading = false
            that.handleClose()
            that.$emit('success')
          }).catch(er => {
            that.submitLoading = false
            console.error(er)
            that.$emit('fail')
          })
          return
        }
        updateProductConfigInfo({ sysProductConfig: that.tabs[0].form, sync: that.syncAll }).then(res => {
          that.submitLoading = false
          that.handleClose()
          that.$emit('success')
        }).catch(er => {
          that.submitLoading = false
          console.error(er)
          that.$emit('fail')
        })
      }

      return
    },
    productPoolChange(value) {
      const firstForm = this.tabs[0].form
      var item = this.productPools[value]
      firstForm.sysOrigin = this.sysOrigin
      firstForm.productId = item.productId
      firstForm.productType = item.productType
      firstForm.description = item.productDesc
      firstForm.groupName = item.groupName
      firstForm.unitPrice = item.unitPrice
    }
  }
}
</script>
