<template>
  <div class="gift-edit">
    <el-dialog
      :title="eventName"
      :visible="true"
      :before-close="handleClose"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      top="50px"
      width="80%"
    >
      <div v-loading="submitLoading">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="110px"
          style="margin-right:50px;"
        >
          <el-form-item label-width="0">
            <!-- 平台 选择 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item label="平台" prop="sysOrigin">
                <el-select
                  v-model="form.sysOrigin"
                  :disabled="isUpdate"
                  placeholder="归属平台"
                  style="width: 100%"
                  class="filter-item"
                  @change="loadTmpData()"
                >
                  <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-col>

            <!-- 区域 选择 -->
            <el-col :md="12" :sm="24">
              <el-form-item prop="regionList" label="区域">
                <el-button
                  type="text"
                  style="margin-left: 10px; color: #FF9326;"
                  @click="handleSelectAllRegions"
                >
                  {{ isAllRegionsSelected ? "取消全选" : "全选" }}
                </el-button>
                <el-select
                  v-model="form.regionList"
                  v-loading="loading"
                  multiple
                  placeholder="请选择"
                  style="width:calc(100% - 80px);"
                >
                  <el-option
                    v-for="(item, index) in regions"
                    :key="index"
                    :label="item.regionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label-width="0px">
            <!-- 名称 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item label="名称" prop="giftName">
                <el-input
                  v-model.trim="form.giftName"
                  type="text"
                  placeholder="礼物名称"
                />
              </el-form-item>
            </el-col>

            <!-- 编码 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="Code" prop="giftCode">
                <el-input
                  v-model.trim="form.giftCode"
                  type="text"
                  placeholder="礼物编码"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item v-if="!isTypeFree" label-width="0px">
            <!-- 金币 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item prop="giftCandy" label="金币">
                <el-input
                  v-model="form.giftCandy"
                  v-number
                  type="text"
                  placeholder="礼物金币"
                />
              </el-form-item>
            </el-col>

            <!-- 积分 -->
            <el-col :md="12" :sm="24">
              <el-form-item prop="giftCandy" label="积分">
                <el-input
                  v-model="form.giftIntegral"
                  v-number
                  type="text"
                  placeholder="礼物积分"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item prop="giftTab" label-width="0">
            <!-- 礼物类型 选择 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item label="礼物类型">
                <el-select
                  v-model="form.giftTab"
                  placeholder="礼物类型"
                  style="width:100%;"
                  class="filter-item"
                >
                  <el-option
                    v-for="item in giftConfigTabs"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 收费类型 选择 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="收费类型">
                <el-select
                  v-model="form.type"
                  placeholder="收费类型"
                  style="width:100%;"
                  class="filter-item"
                  @change="selectChanged"
                >
                  <el-option label="金币" :value="'GOLD'" />
                  <el-option label="免费" :value="'FREE'" disabled />
                  <el-option label="钻石" :value="'DIAMOND'" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label-width="0">
            <!-- 特效 选择 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="特效" prop="specialList" class="col-margin">
                <el-select
                  v-model="form.specialList"
                  multiple
                  placeholder="请选择"
                  style="width:100%;"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 排序 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="排序" prop="sort">
                <el-input
                  v-model="form.sort"
                  v-number
                  type="text"
                  placeholder="请输入排序权重"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label-width="0">
            <!-- 封面 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item label="封面" prop="giftPhoto">
                <el-upload
                  :file-list="giftPhotoFileList"
                  :class="{ 'upload-but-hide': giftCoverUploadVisible }"
                  action=""
                  list-type="picture-card"
                  :http-request="httpRequestGiftCover"
                  :limit="1"
                  :show-file-list="true"
                  :on-remove="removeGiftCover"
                  accept="image/*"
                >
                  <i slot="default" class="el-icon-plus" />
                </el-upload>
              </el-form-item>
            </el-col>

            <!-- 资源 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="资源" prop="giftSourceUrl">
                <el-upload
                  :class="{ 'upload-but-hide': form.giftSourceUrl }"
                  action=""
                  :http-request="httpRequestUploadSourceUrl"
                  :on-remove="handleRemoveSourceUrl"
                  :file-list="sourceUrlFileList"
                  :limit="1"
                  accept=".svga,.pag,.mp4"
                >
                  <div class="upload-but">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                      只能上传svga/pag/mp4文件
                    </div>
                  </div>
                </el-upload>
                <div class="flex-l">
                  <div class="preview-svga">
                    <svgaplayer
                      type="popover"
                      :url="payerSvgaUrl || form.giftSourceUrl"
                    />
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item label-width="0">
            <!-- 有效期 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="有效期" prop="expiredTime">
                <el-date-picker
                  v-model="form.expiredTime"
                  :picker-options="pickerOptions"
                  value-format="timestamp"
                  type="date"
                  placeholder="下架日期"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <el-form-item v-if="form.giftTab === 'EXCLUSIVE'" label-width="0">
            <!-- 归属人账号 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="归属人账号" prop="account">
                <el-input
                  v-model="form.account"
                  type="text"
                  placeholder="归属人账号"
                />
              </el-form-item>
            </el-col>
          </el-form-item>

          <!-- 幸运礼物||魔法礼物 -->
          <el-form-item
            v-if="form.giftTab === 'LUCKY_GIFT' || form.giftTab === 'MAGIC'"
            label-width="0"
          >
            <!-- 幸运规格 选择 -->
            <el-col :md="12" :sm="24" class="col-margin">
              <el-form-item prop="standardId" label="幸运规格">
                <el-select
                  v-model="form.standardId"
                  v-loading="loading"
                  placeholder="请选择"
                  style="width:100%;"
                >
                  <el-option
                    v-for="(item, index) in mapStandard"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>

          <!-- CP -->
          <el-form-item v-if="form.giftTab === 'CP'" label-width="0">
            <!-- 是否告白礼物 -->
            <el-col :md="12" :sm="24">
              <el-form-item label="是否告白礼物" prop="explanationGift">
                <el-select
                  v-model="form.explanationGift"
                  placeholder="告白礼物"
                  clearable
                  style="width:100%;"
                  class="filter-item"
                >
                  <el-option label="是" :value="true" />
                  <el-option label="否" :value="false" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div slot="footer" style="text-align: center;">
          <el-button @click="handleClose()">取消</el-button>
          <el-button type="primary" @click="submitForm()">保存</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapLuckyGiftStandard } from "@/api/game-lucky-gift-config";
import { updateGift, addGift } from "@/api/gift";
import { giftConfigTabs } from "@/constant/type";
import { mapGetters } from "vuex";
import { regionConfigTable } from "@/api/sys";

export default {
  name: "GiftEdit",
  props: {
    // ADD or UPDATE
    event: {
      type: String,
      required: true,
      default: "ADD"
    },
    selectParam: {
      type: Object,
      default: null
    }
  },
  data() {
    function commonFormRules() {
      return [{ required: true, message: "必填字段", trigger: "blur" }];
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date().getTime();
        }
      },
      giftCoverUploadVisible: false,
      submitLoading: false,
      giftConfigTabs,
      regions: [],
      options: [
        {
          value: "ANIMATION",
          label: "动画",
          disabled: false
        },
        {
          value: "MUSIC",
          label: "音乐",
          disabled: false
        },
        {
          value: "NOTICE",
          label: "全局通报",
          disabled: false
        },
        // {
        //   value: 'LUCKY_GIFT',
        //   label: '幸运礼物',
        //   disabled: false
        // },
        {
          value: "SVIP_GIFT",
          label: "SVIP礼物",
          disabled: false
        },
        {
          value: "STAR",
          label: "周星礼物",
          disabled: false
        },
        {
          value: "GLOBAL_GIFT",
          label: "全局广播礼物",
          disabled: false
        }
      ],
      giftPhotoFileList: [],
      sourceUrlFileList: [],
      mapStandard: [],
      standardIdTmp: "",
      form: {
        id: "",
        giftPhoto: "",
        giftSourceUrl: "",
        giftName: "",
        giftCode: "",
        giftCandy: "",
        account: "",
        giftIntegral: "",
        type: "GOLD",
        specialList: [],
        giftTab: "ORDINARY",
        sort: "",
        expiredTime: "",
        explanationGift: "",
        sysOrigin: "HALAR",
        regionList: []
      },
      rules: {
        giftPhoto: commonFormRules(),
        giftName: commonFormRules(),
        giftCode: commonFormRules(),
        giftCandy: commonFormRules(),
        giftIntegral: commonFormRules(),
        type: commonFormRules(),
        giftTab: commonFormRules(),
        sort: commonFormRules(),
        sysOrigin: commonFormRules(),
        regionList: commonFormRules()
      },
      payerSvgaUrl: ""
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"]),
    eventName() {
      return this.event === "ADD"
        ? "添加"
        : this.event === "UPDATE"
        ? "修改"
        : "ERROR";
    },
    isUpdate() {
      return this.event === "UPDATE";
    },
    isTypeFree() {
      return this.form.type === "FREE";
    },
    isAllRegionsSelected() {
      if (!this.regions || this.regions.length === 0) return false;
      return this.form.regionList.length === this.regions.length;
    }
  },
  watch: {
    selectParam: {
      handler(newVal) {
        if (!newVal) {
          this.loadTmpData();
          return;
        }
        this.standardIdTmp = newVal.standardId;
        if (newVal.special) {
          newVal.specialList = newVal.special.split(",");
        }
        if (newVal.regions) {
          newVal.regionList = newVal.regions.split(",");
        }
        if (newVal.giftPhoto) {
          this.giftCoverUploadVisible = true;
          this.giftPhotoFileList.push({ url: newVal.giftPhoto });
        }
        if (newVal.giftSourceUrl) {
          this.sourceUrlFileList.push({
            name: newVal.giftSourceUrl.substring(
              newVal.giftSourceUrl.lastIndexOf("/")
            ),
            url: newVal.giftSourceUrl
          });
        }

        this.form = Object.assign({}, newVal);
        this.loadTmpData();
      },
      immediate: true
    }
  },
  methods: {
    loadTmpData() {
      const that = this;
      // 加载区域
      that.listRegion();
      // 加载幸运礼物规格
      that.loadMapLuckyGiftStandard();
    },
    handleClose() {
      this.$emit("close");
    },
    httpRequestUploadSourceUrl(file) {
      const that = this;
      that
        .$simpleUploadFlie(file, "gifts")
        .then(res => {
          that.$message.success("上传成功");
          that.form.giftSourceUrl = res.name;
          that.payerSvgaUrl = that.$getAccessImgUrl(res.name);
        })
        .catch(er => {
          console.error(er);
          that.$message.error("上传失败，请尝试重新上传!");
        });
    },
    handleRemoveSourceUrl(file, fileList) {
      this.form.giftSourceUrl = "";
    },
    httpRequestGiftCover(file) {
      const that = this;
      that.giftCoverUploadVisible = true;
      this.$simpleUploadFlie(file, "gifts")
        .then(res => {
          that.form.giftPhoto = res.name;
        })
        .catch(er => {
          console.error(er);
          that.giftCoverUploadVisible = false;
          that.$message.error("上传失败，请尝试重新上传!");
        });
    },
    listRegion() {
      const that = this;
      that.loading = true;
      regionConfigTable({ sysOrigin: that.form.sysOrigin })
        .then(res => {
          that.regions = res.body || [];
          that.loading = false;
        })
        .catch(er => {
          that.loading = false;
        });
    },
    loadMapLuckyGiftStandard() {
      const that = this;
      that.loading = true;
      mapLuckyGiftStandard(that.form.sysOrigin)
        .then(res => {
          that.mapStandard = res.body || [];
          that.loading = false;
        })
        .catch(er => {
          that.loading = false;
        });
    },
    selectChanged(value) {
      if (value === "FREE") {
        this.form.giftCandy = "";
        this.form.giftIntegral = "";
        return;
      }
    },
    removeGiftCover() {
      this.form.giftPhoto = "";
      this.giftCoverUploadVisible = false;
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true;

          if (that.form.giftTab === "LUCKY_GIFT") {
            if (!that.form.standardId) {
              that.$message.error("幸运礼物必须选择规格");
              that.submitLoading = false;
              return;
            }

            if (
              that.standardIdTmp &&
              that.standardIdTmp !== that.form.standardId
            ) {
              const that = this;
              that
                .$confirm(
                  "修改规格会立刻切换新规格新抽奖数据,是否确定切换?",
                  "提示",
                  {
                    type: "warning"
                  }
                )
                .then(() => {
                  that.submitData();
                })
                .catch(() => {
                  that.submitLoading = false;
                });
              return;
            }
            that.submitData();
            return;
          }

          that.submitData();
        } else {
          console.error("error submit!!");
          return false;
        }
      });
    },
    submitData() {
      const that = this;
      if (that.form.id) {
        updateGift(that.form)
          .then(res => {
            that.submitLoading = false;
            that.$emit("success", { result: res, event: that.event });
          })
          .catch(er => {
            that.submitLoading = false;
            that.$emit("fial", { error: er, event: that.event });
          });
        return;
      }
      addGift(that.form)
        .then(res => {
          that.submitLoading = false;
          that.$emit("success", { result: res, event: that.event });
        })
        .catch(er => {
          that.submitLoading = false;
          console.error(er);
          that.$emit("fial", { error: er, event: that.event });
        });
    },
    handleSelectAllRegions() {
      if (this.isAllRegionsSelected) {
        this.form.regionList = [];
      } else {
        this.form.regionList = this.regions.map(item => item.id);
      }
    }
  }
};
</script>
<style scoped>
.col-margin {
  margin-bottom: 20px;
}
</style>
