<template>
  <div class="pet-edit">
    <el-drawer
      title="宠物信息编辑"
      :visible="true"
      :before-close="handleClose"
      :wrapper-closable="false"
      size="450px"
    >
      <div class="body">
        <el-form ref="petPoolForm" :model="petPoolForm" :rules="petPoolFormRules" label-width="110px" :disabled="submitLoading">
          <div class="blockquote">宠物资料</div>
          <el-form-item label="归属系统" prop="sysOrigin">
            <el-select
              v-model="petPoolForm.sysOrigin"
              :disabled="!isAdd"
              placeholder="归属系统"
              style="width: 100%"
              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-form-item>
          <el-form-item label="宠物Code" prop="petCode">
            <el-input v-model.trim="petPoolForm.petCode" placeholder="宠物Code" class="input-with-select" maxlength="50" :disabled="!isAdd" />
          </el-form-item>
          <el-form-item label="宠物名称" prop="petName">
            <el-input v-model.trim="petPoolForm.petName" placeholder="宠物名称" class="input-with-select" maxlength="50" />
          </el-form-item>
          <el-form-item label="展示顺序" prop="level">
            <el-input-number v-model="petPoolForm.level" controls-position="right" :min="1" :max="99999" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="上/下架" prop="shelf">
            <el-radio-group v-model="petPoolForm.shelf">
              <el-radio :label="true">上架</el-radio>
              <el-radio :label="false">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item v-if="isAdd" label="同步所有" prop="sync">
            <el-radio-group v-model="petPoolForm.sync">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <div class="blockquote">养成奖励</div>
          <el-form-item label="养成奖励" prop="rewardGroupId">
            <el-button type="text" :disabled="!petPoolForm.sysOrigin" @click="associatedResourcesVisable=true">选择</el-button>
            <div class="reward flex-l">
              <div v-for="(sItem, sIndex) in (selectSourceGroup || {}).rewardConfigList" :key="sIndex" class="origin-source">
                <div v-if="sItem.type === 'GOLD'">
                  <img src="@/assets/gold_icon.png" style="width: 50px; height: 50px">
                  <div class="nowrap-ellipsis"><a :title="sItem.content">{{ sItem.content }}</a></div>
                </div>
                <div v-else-if="sItem.type === 'DIAMOND'">
                  <img src="@/assets/diamond_icon.png">
                  <div class="nowrap-ellipsis"><a :title="sItem.content">{{ sItem.content }}</a></div>
                </div>
                <div v-else-if="sItem.type === 'ROOM_BADGE'">
                  <img src="@/assets/room_badge_icon.png">
                  <div class="nowrap-ellipsis"><a :title="sItem.content">{{ sItem.content }}</a></div>
                </div>
                <div v-else-if="sItem.type === 'SPECIAL_ID'">
                  <img src="@/assets/special_id.png" style="width:50px;height:50px;cursor: pointer;">
                  <div class="nowrap-ellipsis"><a :title="sItem.content">{{ sItem.content }}</a></div>
                </div>
                <div v-else class="preview-img">
                  <el-image
                    style="width: 50px; height: 50px"
                    :src="sItem.cover"
                    :preview-src-list="[sItem.cover]"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" />
                    </div>
                  </el-image>
                  <div class="preview-svga">
                    <svgaplayer
                      type="popover"
                      :url="sItem.sourceUrl"
                    />
                  </div>
                  <div v-if="sItem.type === 'BADGE'" class="nowrap-ellipsis">
                    <a :title="sItem.quantity ? sItem.quantity + '天' : '永久'">
                      <span>{{ sItem.type === 'ROOM_BADGE' ? 'R' : 'U' }}</span>{{ sItem.quantity ? sItem.quantity + '天' : '永久' }}
                    </a>
                  </div>
                  <div v-else class="nowrap-ellipsis">
                    <a :title="sItem.quantity">{{ sItem.quantity }} 天</a>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="blockquote">阶段信息</div>
        <el-tabs v-model="petStageActiveName">
          <el-tab-pane v-for="(item,index) in petStage" :key="index" :name="item.key">
            <span slot="label"><i v-if="item.validNotPass" class="el-icon-warning font-danger" /> {{ item.label }}</span>
            <el-form :ref="'petStageForm_' + item.key" :model="item.form" :rules="petStageRule" label-width="110px" :disabled="submitLoading">
              <el-form-item label="喂养次数" prop="upgradeFeedingNum">
                <el-col :span="20">
                  <el-input-number v-model="item.form.upgradeFeedingNum" controls-position="right" :min="0" :max="99999" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="宠物升级需要喂养的总次数" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="喂养粮食" prop="foodFeedingNum">
                <el-col :span="20">
                  <el-input-number v-model="item.form.foodFeedingNum" controls-position="right" :min="0" :max="999999" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="每次喂养需要消费的粮食数量" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="产生收益" prop="revenue">
                <el-col :span="20">
                  <el-input-number v-model="item.form.revenue" controls-position="right" :min="0" :max="999999" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="到达收益时间后的产出" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="收益数量" prop="revenueNum">
                <el-col :span="20">
                  <el-input-number v-model="item.form.revenueNum" controls-position="right" :min="1" :max="2" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="参数的收益数量=收益间隔/this；目前最大支持1～2" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="收益间隔(M)" prop="revenueIntervalMinute">
                <el-col :span="20">
                  <el-input-number v-model="item.form.revenueIntervalMinute" controls-position="right" :min="1" :max="99999" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="产生收益时间，this/收益数量" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="喂食间隔(M)" prop="feedingIntervalMinute">
                <el-col :span="20">
                  <el-input-number v-model="item.form.feedingIntervalMinute" controls-position="right" :min="1" :max="99999" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="每次喂食的间隔分钟" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="免费喂食次数" prop="freeFeedingNum">
                <el-col :span="20">
                  <el-input-number v-model="item.form.freeFeedingNum" controls-position="right" :min="0" :max="4" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="1天可以免费喂养次数,0~4" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item label="加速粮食数" prop="accelerateFeed">
                <el-col :span="20">
                  <el-input-number v-model="item.form.accelerateFeed" controls-position="right" :min="0" :max="1000000" style="width: 100%;" />
                </el-col>
                <el-col :span="4" style="text-align:center;">
                  <el-tooltip effect="dark" content="喂养加速:已喂养次数 * this" placement="top-start">
                    <i class="el-icon-question" style="font-size: 30px;padding-top: 2px;cursor:pointer;" />
                  </el-tooltip>
                </el-col>
              </el-form-item>
              <el-form-item v-if="item.key !== 'four'" label="封面图" prop="cover">
                <el-upload
                  :disabled="coverUploadLoading"
                  :file-list="item.coverFileList"
                  :class="{'upload-but-hide': !!item.form.cover }"
                  action=""
                  list-type="picture-card"
                  :http-request="(file) => uploadCover(file, item)"
                  :show-file-list="!!item.form.cover"
                  :on-remove="()=> handleCoverFileRemove(item)"
                  accept="image/*"
                >
                  <i slot="default" v-loading="item.uploadLoading" class="el-icon-plus" />
                </el-upload>
              </el-form-item>
              <el-form-item v-if="item.key !== 'four'" label="资源图" prop="sourceUrl">
                <el-upload
                  :disabled="item.sourceLoading"
                  :class="{'upload-but-hide': !!item.form.sourceUrl}"
                  action=""
                  :http-request="(file)=>sourceUpload(file,item)"
                  :on-remove="()=>handleSourceFileRemove(item)"
                  :show-file-list="!!item.form.sourceUrl"
                  :file-list="item.sourceUrlFileList"
                  accept=".svga,.pag"
                >
                  <div class="upload-but">
                    <el-button :loading="item.sourceLoading" size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传svga/pag文件</div>
                  </div>
                </el-upload>
                <svgaplayer v-if="item.form.sourceUrl" :url="item.form.sourceUrl" />
              </el-form-item>

            </el-form>
          </el-tab-pane>
        </el-tabs>

        <el-form ref="petUnlockConditionFrom" :model="petUnlockConditionFrom" label-width="0px" :disabled="submitLoading">
          <div class="blockquote">解锁条件</div>
          <div v-if="petUnlockConditionFrom.forms.length <= 0" style="text-align: center;padding: 0px 0px 20px 0px;">
            <el-button type="primary" @click="addPetUnlockCondition">添加条件</el-button>
          </div>
          <div v-else>
            <el-form-item v-for="(item,index) in petUnlockConditionFrom.forms" :key="index" required>
              <el-row :gutter="10">
                <el-col :span="7">
                  <el-form-item :prop="'forms.' + index+'.conditionType'" :rules="{ required: true, message: '必填类型不可为空', trigger: 'blur'}">
                    <el-select
                      v-model="item.conditionType"
                      placeholder="类型"
                      style="width: 100%"
                      class="filter-item"
                      clearable
                    >
                      <el-option
                        v-for="(type, typeIndex) in petUnlockConditions"
                        :key="typeIndex"
                        :label="type.name"
                        :value="type.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item :prop="'forms.' + index+'.unit'" :rules="{ required: true, message: '必填类型不可为空', trigger: 'blur'}">
                    <el-select
                      v-model="item.unit"
                      placeholder="条件"
                      style="width: 100%"
                      class="filter-item"
                      clearable
                    >
                      <el-option
                        v-for="(type, typeIndex) in unitConditions"
                        :key="typeIndex"
                        :label="type.name"
                        :value="type.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item :prop="'forms.' + index+'.quantity'" :rules="{ required: true, message: '必填类型不可为空', trigger: 'blur'}">
                    <el-input-number v-model="item.quantity" controls-position="right" :min="1" :max="999999" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <div v-if="petUnlockConditionFrom.forms.length === 1" class="flex-c">
                    <i class="el-icon-circle-plus" style="font-size: 30px;cursor: pointer;" @click="addPetUnlockCondition()" />
                    <i class="el-icon-delete-solid font-danger" style="font-size: 30px;cursor: pointer;" @click="removePetUnlockCondition(item, index)" />
                  </div>
                  <div v-else class="flex-c">
                    <i v-if="petUnlockConditionFrom.forms.length - 1 === index" class="el-icon-circle-plus" style="font-size: 30px;cursor: pointer;" @click="addPetUnlockCondition()" />
                    <i class="el-icon-delete-solid font-danger" style="font-size: 30px;cursor: pointer;" @click="removePetUnlockCondition(item, index)" />
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </el-form>

        <div class="drawer-footer">
          <el-button v-loading="submitLoading" :disabled="submitLoading" type="primary" @click="submitForm()">保存</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </div>
      </div>

      <associated-resources
        v-if="associatedResourcesVisable"
        :sys-origin="petPoolForm.sysOrigin"
        @select="selectSource"
        @close="associatedResourcesVisable=false;"
      />
    </el-drawer>
  </div>
</template>
<script>
import { addPet } from '@/api/pet'
import { petUnlockConditions, unitConditions } from '@/constant/type'
import { deepClone, getElementUiUploadFile } from '@/utils'
import AssociatedResources from '@/components/data/AssociatedResources'
import { mapGetters } from 'vuex'
const getPetStageFrom = () => {
  return {
    level: '',
    stage: '',
    cover: '',
    sourceUrl: '',
    upgradeFeedingNum: '',
    foodFeedingNum: '',
    revenue: '',
    revenueNum: '',
    revenueIntervalMinute: '',
    feedingIntervalMinute: '',
    freeFeedingNum: '',
    accelerateFeed: ''
  }
}

const getPetUnlockConditions = () => {
  return {
    conditionType: '',
    unit: '',
    quantity: ''
  }
}
export default {
  components: { AssociatedResources },
  props: {
    row: {
      type: Object,
      require: false,
      default: () => {}
    }
  },
  data() {
    const commonRules = [
      { required: true, message: '必填字段不可为空', trigger: 'blur' }
    ]

    return {
      stages: ['EGGING', 'CHILDHOOD', 'ALDULT', 'FINISH'],
      coverUploadLoading: false,
      unitConditions,
      petUnlockConditions,
      petUnlockConditionFrom: {
        forms: []
      },
      petStageActiveName: 'one',
      petStage: [
        {
          label: '卵化',
          key: 'one',
          uploadLoading: false,
          coverFileList: [],
          sourceLoading: false,
          sourceUrlFileList: [],
          validNotPass: false,
          form: getPetStageFrom()
        },
        {
          label: '幼年',
          key: 'two',
          uploadLoading: false,
          sourceLoading: false,
          validNotPass: false,
          form: getPetStageFrom()
        },
        {
          label: '成年',
          key: 'three',
          uploadLoading: false,
          sourceLoading: false,
          validNotPass: false,
          form: getPetStageFrom()
        },
        {
          label: '兑换',
          key: 'four',
          uploadLoading: false,
          sourceLoading: false,
          validNotPass: false,
          form: getPetStageFrom()
        }
      ],
      petStageRule: {
        cover: commonRules,
        // sourceUrl: commonRules,
        upgradeFeedingNum: commonRules,
        foodFeedingNum: commonRules,
        revenue: commonRules,
        revenueNum: commonRules,
        revenueIntervalMinute: commonRules,
        feedingIntervalMinute: commonRules,
        freeFeedingNum: commonRules,
        accelerateFeed: commonRules
      },
      selectSourceGroup: {},
      associatedResourcesVisable: false,
      petPoolForm: {
        id: '',
        sysOrigin: '',
        petCode: '',
        petName: '',
        level: '',
        rewardGroupId: '',
        shelf: false,
        sync: true
      },
      petPoolFormRules: {
        sysOrigin: commonRules,
        petCode: commonRules,
        petName: commonRules,
        level: commonRules,
        stage: commonRules,
        rewardGroupId: commonRules,
        shelf: commonRules,
        sync: commonRules
      },
      isChangeSource: false,
      svgaplayerVisable: false,
      submitLoading: false
    }
  },
  computed: {
    ...mapGetters(['permissionsSysOriginPlatforms']),
    isAdd() {
      return !this.row || !this.row.petPool || !this.row.petPool.id
    }
  },
  watch: {
    row: {
      handler(newVal) {
        if (!newVal) {
          return
        }

        const newForm = deepClone(newVal)
        this.petPoolForm = newForm.petPool
        this.petStage.forEach((item, index) => {
          const stage = newForm.petStages[index]
          if (stage) {
            item.form = Object.assign({}, stage)
            item.coverFileList = getElementUiUploadFile(stage.cover)
            item.sourceUrlFileList = getElementUiUploadFile(stage.sourceUrl)
          }
        })
        this.petUnlockConditionFrom.forms = newForm.petUnlockConditions || []
        this.selectSourceGroup = newForm.rewards
      },
      immediate: true
    }
  },
  mounted() {

  },
  methods: {
    changeSysOrigin() {
      this.selectSourceGroup = {}
      this.petPoolForm.rewardGroupId = null
    },
    uploadCover(file, item) {
      const that = this
      item.uploadLoading = true
      that.$simpleUploadFlie(file, that.$application.fileBucket.svgaCover).then(res => {
        item.uploadLoading = false
        item.form.cover = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        item.uploadLoading = false
      })
    },
    handleCoverFileRemove(item) {
      item.form.cover = ''
      item.uploadLoading = false
    },
    selectSource(source) {
      this.selectSourceGroup = source
      this.associatedResourcesVisable = false
      this.petPoolForm.rewardGroupId = source.id
    },
    addPetUnlockCondition() {
      this.petUnlockConditionFrom.forms.push(getPetUnlockConditions())
    },
    removePetUnlockCondition(item, index) {
      this.petUnlockConditionFrom.forms.splice(index, 1)
    },
    sourceUpload(file, item) {
      const that = this
      item.sourceLoading = true
      that.$simpleUploadFlie(file).then(res => {
        item.sourceLoading = false
        item.form.sourceUrl = that.$getAccessImgUrl(res.name)
      }).catch(er => {
        item.sourceLoading = false
      })
    },
    handleSourceFileRemove(item) {
      item.form.sourceUrl = ''
      item.sourceLoading = false
    },

    handleClose() {
      this.$emit('close')
    },
    submitForm() {
      const that = this
      const promiseAll = []
      promiseAll.push(new Promise((resolve, reject) => {
        that.$refs.petPoolForm.validate(valid => {
          if (!valid) {
            console.error('petPoolForm error submit!!')
            reject()
            return
          }
          resolve()
        })
      }))

      promiseAll.push(new Promise((resolve, reject) => {
        that.$refs.petUnlockConditionFrom.validate(valid => {
          if (!valid) {
            console.error('petUnlockConditionFrom error submit!!')
            reject()
            return
          }
          resolve()
        })
      }))

      that.petStage.forEach(item => {
        promiseAll.push(new Promise((resolve, reject) => {
          that.$refs[`petStageForm_${item.key}`][0].validate(valid => {
            if (!valid) {
              console.error('petStage error submit!!')
              item.validNotPass = true
              reject()
              return
            }
            item.validNotPass = false
            resolve()
          })
        }))
      })

      Promise.all(promiseAll).then(() => {
        that.submitLoading = true
        const submitForm = {
          petPool: that.petPoolForm,
          petUnlockConditions: that.petUnlockConditionFrom.forms,
          petStages: that.petStage.map((item, index) => {
            item.form.level = index + 1
            item.form.stage = that.stages[index]
            if (index === that.petStage.length - 1) {
              const perv = that.petStage[that.petStage.length - 2]
              if (perv) {
                item.form.cover = perv.form.cover
                item.form.sourceUrl = perv.form.sourceUrl
              }
            }
            if (!item.form.stage) {
              throw Error('阶段信息匹配错误.')
            }
            return item.form
          })
        }
        addPet(submitForm).then(res => {
          that.submitLoading = false
          that.$emit('success', submitForm)
        }).catch(er => {
          that.submitLoading = false
          that.$emit('fail', submitForm)
          console.error('er', er)
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.pet-edit {
  .body {
    padding: 0px 10px 80px 10px;
  }
  .reward {
      overflow: auto;
      white-space:nowrap;
      .origin-source {
        padding: 0px 5px;
        text-align: center;
        width: 70px;
        height: 100px;
        img {
          width: 50px;
          height: 50px;
          cursor: pointer;
        }
      }

  }
}
</style>
