<template>
  <div class="banner-form-edite">
    <el-drawer
      :title="textOptTitle"
      :visible="true"
      :before-close="handleClose"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :modal-append-to-body="true"
      :append-to-body="true"
      custom-class="drawer-auto-layout"
    >
      <div v-loading="submitLoading">
        <div class="drawer-form">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <!-- 封面 -->
            <el-form-item :label="$t('pages.bannerManager.form.cover')" prop="cover">
              <el-col :span="8">
                <el-form-item prop="cover" class="upload-small">
                  <el-upload
                    :disabled="coverUploadLoading"
                    :file-list="coverFileList"
                    :class="{ 'upload-but-hide': !isShowCoverUpload }"
                    action=""
                    list-type="picture-card"
                    :http-request="uploadCover"
                    :show-file-list="!isShowCoverUpload"
                    :on-remove="handleCoverFileRemove"
                    accept="image/*"
                  >
                    <i
                      slot="default"
                      v-loading="coverUploadLoading"
                      class="el-icon-plus"
                    />
                    <div slot="tip" class="el-upload__tip">{{
                      $t("pages.bannerManager.uploadTip.cover")
                    }}</div>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="upload-small">
                <el-form-item prop="smallCover">
                  <el-upload
                    :disabled="smallCoverUploadLoading"
                    :file-list="smallCoverFileList"
                    :class="{ 'upload-but-hide': !isShowSmallCoverUpload }"
                    action=""
                    list-type="picture-card"
                    :http-request="uploadSmallCover"
                    :show-file-list="!isShowSmallCoverUpload"
                    :on-remove="handleSmallCoverFileRemove"
                    accept="image/*"
                  >
                    <i
                      slot="default"
                      v-loading="smallCoverUploadLoading"
                      class="el-icon-plus"
                    />
                    <div slot="tip" class="el-upload__tip">{{
                      $t("pages.bannerManager.uploadTip.smallCover")
                    }}</div>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="upload-small">
                <el-form-item prop="alertCover">
                  <el-upload
                    :disabled="alertCoverUploadLoading"
                    :file-list="alertCoverFileList"
                    :class="{ 'upload-but-hide': !isShowAlertCoverUpload }"
                    action=""
                    list-type="picture-card"
                    :http-request="uploadAlertCover"
                    :show-file-list="!isShowAlertCoverUpload"
                    :on-remove="handlealertCoverFileRemove"
                    accept="image/*"
                  >
                    <i
                      slot="default"
                      v-loading="alertCoverUploadLoading"
                      class="el-icon-plus"
                    />
                    <div slot="tip" class="el-upload__tip">{{
                      $t("pages.bannerManager.uploadTip.alertCover")
                    }}</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-form-item>

            <!-- 状态 -->
            <el-form-item :label="$t('pages.bannerManager.form.status')" prop="showcase">
              <el-select
                v-model="form.showcase"
                :placeholder="$t('pages.bannerManager.placeholder.status')"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  :label="$t('pages.bannerManager.status.offShelf')"
                  :value="false"
                />
                <el-option
                  :label="$t('pages.bannerManager.status.onShelf')"
                  :value="true"
                />
              </el-select>
            </el-form-item>

            <!-- 平台 -->
            <el-form-item :label="$t('pages.bannerManager.form.platform')" prop="platform">
              <el-select
                v-model="form.platform"
                :placeholder="$t('pages.bannerManager.placeholder.platform')"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  v-for="(item, index) in appPlatforms"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 类型 -->
            <el-form-item :label="$t('pages.bannerManager.form.type')" prop="type">
              <el-select
                v-model="form.type"
                :placeholder="$t('pages.bannerManager.placeholder.type')"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 内容 -->
            <el-form-item :label="$t('pages.bannerManager.form.content')">
              <el-autocomplete
                v-model.trim="form.content"
                style="width: 100%;"
                :fetch-suggestions="querySearchContentRestaurants"
                popper-class="form-autocomplete"
                :placeholder="$t('pages.bannerManager.placeholder.content')"
              >
                <template slot-scope="{ item }">
                  <div class="name">{{ item.label }}</div>
                  <span class="label">{{ item.value }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>

            <!-- 参数 -->
            <el-form-item
              v-if="
                form.content !== 'ENTER_ROOM' &&
                  form.content !== 'ENTER_PERSONAL_CENTER'
              "
              :label="$t('pages.bannerManager.form.params')"
            >
              <el-input v-model.trim="form.params" type="text" />
            </el-form-item>

            <!-- 房间 -->
            <el-form-item
              v-if="form.content === 'ENTER_ROOM'"
              :label="$t('pages.bannerManager.form.room')"
            >
              <search-room-input
                :room-id="tmpRoomId"
                @success="searchRoomSuccess"
                @fail="searchRoomFail"
                @load="loadSearchRoom"
              />
            </el-form-item>

            <!-- 用户 -->
            <el-form-item
              v-if="form.content === 'ENTER_PERSONAL_CENTER'"
              :label="$t('pages.bannerManager.form.user')"
            >
              <account-input
                v-model="tmpUserId"
                :sys-origin="sysOrigin"
                :placeholder="$t('pages.bannerManager.placeholder.userId')"
              />
            </el-form-item>

            <!-- 展示位 -->
            <el-form-item
              :label="$t('pages.bannerManager.form.displayPosition')"
              prop="displayPosition"
            >
              <el-select
                v-model="form.displayPosition"
                :placeholder="$t('pages.bannerManager.placeholder.displayPosition')"
                clearable
                multiple=""
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  v-for="item in displayPositionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 开始时间 -->
            <el-form-item
              :label="$t('pages.bannerManager.form.startTime')"
              prop="startTime"
            >
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="timestamp"
                :placeholder="$t('pages.bannerManager.placeholder.dateTime')"
                style="width:100%;"
              />
            </el-form-item>

            <!-- 过期时间 -->
            <el-form-item
              :label="$t('pages.bannerManager.form.expiredTime')"
              prop="expiredTime"
            >
              <el-date-picker
                v-model="form.expiredTime"
                type="datetime"
                value-format="timestamp"
                :placeholder="$t('pages.bannerManager.placeholder.dateTime')"
                style="width:100%;"
              />
            </el-form-item>

            <!-- 排序 -->
            <el-form-item :label="$t('pages.bannerManager.form.sort')" prop="depict">
              <el-input
                v-model.trim="form.sort"
                v-number
                :placeholder="$t('pages.bannerManager.placeholder.sort')"
              />
            </el-form-item>

            <!-- 区域 -->
            <el-form-item :label="$t('pages.bannerManager.form.region')" prop="regionList">
              <el-select
                v-model="form.regionList"
                v-loading="loading"
                multiple
                clearable
                :placeholder="$t('pages.bannerManager.placeholder.select')"
                style="width:100%;"
                class="filter-item"
              >
                <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.bannerManager.form.country')" prop="countryCode">
              <el-select
                v-model="selectCountryCode"
                v-loading="loadingCountry"
                multiple
                clearable
                :placeholder="$t('pages.bannerManager.placeholder.select')"
                style="width:100%;"
                class="filter-item"
                @change="changeCountry"
              >
                <el-option
                  v-for="item in countryList"
                  :key="item.id"
                  :label="item.country.aliasName || item.country.enName"
                  :value="item.country.alphaTwo"
                >
                  <span style="float: left;">
                    <img :src="item.country.nationalFlag" width="30"
                  /></span>
                  <span style="float: left;margin-left:10px">{{
                    item.country.aliasName || item.country.enName
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 描述 -->
            <el-form-item :label="$t('pages.bannerManager.form.description')" prop="depict">
              <el-input
                v-model.trim="form.depict"
                resize="none"
                show-word-limit
                type="textarea"
                :rows="6"
                maxlength="200"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-footer">
          <el-button @click="handleClose()">{{
            $t("pages.bannerManager.action.cancel")
          }}</el-button>
          <el-button type="primary" @click="submitForm()">{{
            $t("pages.bannerManager.action.save")
          }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { appPlatforms } from "@/constant/origin";
import { getElementUiUploadFile } from "@/utils";

import { updateBanner, addBanner } from "@/api/banner";
import { regionConfigTable } from "@/api/sys";
import { listPayOpenCountry } from "@/api/sys-pay";
export default {
  props: {
    row: {
      type: Object,
      default: null
    },
    sysOrigin: {
      type: String,
      require: false,
      default: ""
    }
  },
  data() {
    const commonRules = [
      {
        required: true,
        message: this.$t("pages.bannerManager.validation.requiredField"),
        trigger: "blur"
      }
    ];
    return {
      appPlatforms,
      searchDisabled: false,
      alertCoverUploadLoading: false,
      alertCoverFileList: [],
      coverUploadLoading: false,
      coverFileList: [],
      smallCoverUploadLoading: false,
      smallCoverFileList: [],
      tmpRoomId: "",
      loading: false,
      tmpUserId: "",
      regions: [],
      form: {
        id: "",
        cover: "",
        smallCover: "",
        showcase: "",
        platform: "",
        type: "",
        sysOrigin: "",
        content: "",
        params: "",
        expiredTime: "",
        startTime: "",
        depict: "",
        sort: "",
        displayPosition: "",
        alertCover: "",
        regionList: [],
        countryCode: ""
      },
      submitLoading: false,
      uploadLoading: false,
      rules: {
        cover: commonRules,
        showcase: commonRules,
        type: commonRules,
        sysOrigin: commonRules,
        expiredTime: commonRules
      },
      selectCountryCode: [],
      countryList: [],
      loadingCountry: false
    };
  },
  computed: {
    textOptTitle() {
      const action = this.row && this.row.id
        ? this.$t("pages.bannerManager.dialog.edit")
        : this.$t("pages.bannerManager.dialog.create");
      return `${action}(${this.sysOrigin})`;
    },
    isShowCoverUpload() {
      return !this.form.cover;
    },
    isShowSmallCoverUpload() {
      return !this.form.smallCover;
    },
    isShowAlertCoverUpload() {
      return !this.form.alertCover;
    },
    typeOptions() {
      return [
        {
          value: "H5",
          label: this.$t("pages.bannerManager.type.H5")
        },
        {
          value: "APP",
          label: this.$t("pages.bannerManager.type.APP")
        },
        {
          value: "AD",
          label: this.$t("pages.bannerManager.type.AD")
        }
      ];
    },
    displayPositionOptions() {
      return [
        {
          value: "ROOM",
          label: this.$t("pages.bannerManager.displayPosition.ROOM")
        },
        {
          value: "EXPLORE_PAGE",
          label: this.$t("pages.bannerManager.displayPosition.EXPLORE_PAGE")
        },
        {
          value: "HOME_ALERT",
          label: this.$t("pages.bannerManager.displayPosition.HOME_ALERT")
        },
        {
          value: "WALLET",
          label: this.$t("pages.bannerManager.displayPosition.WALLET")
        },
        {
          value: "GAME",
          label: this.$t("pages.bannerManager.displayPosition.GAME")
        }
      ];
    },
    contentRestaurants() {
      return [
        {
          value: "GIFT_PACK_BUY",
          label: this.$t("pages.bannerManager.contentOption.GIFT_PACK_BUY")
        },
        {
          value: "ENTER_ROOM",
          label: this.$t("pages.bannerManager.contentOption.ENTER_ROOM")
        },
        {
          value: "ENTER_PERSONAL_CENTER",
          label: this.$t(
            "pages.bannerManager.contentOption.ENTER_PERSONAL_CENTER"
          )
        },
        {
          value: "RECHARGE_IN_APP",
          label: this.$t("pages.bannerManager.contentOption.RECHARGE_IN_APP")
        },
        {
          value: "RECHARGE_H5",
          label: this.$t("pages.bannerManager.contentOption.RECHARGE_H5")
        },
        {
          value: "PROP_STORE",
          label: this.$t("pages.bannerManager.contentOption.PROP_STORE")
        }
      ];
    },
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  watch: {
    row: {
      handler(val) {
        if (!val) {
          this.listRegion();
          this.loadOpenCountry();
          return;
        }
        const form = Object.assign({}, val);
        if (form.params !== "" && form.content === "ENTER_ROOM") {
          this.tmpRoomId = form.params;
        }
        if (form.params !== "" && form.content === "ENTER_PERSONAL_CENTER") {
          this.tmpUserId = form.params;
        }
        if (form.displayPosition) {
          form.displayPosition = form.displayPosition.split(",");
        }
        if (form.regions) {
          form.regionList = form.regions.split(",");
        }
        if (form.countryCode) {
          form.countryCode = form.countryCode;
          this.selectCountryCode = form.countryCode.split(",");
        }
        this.coverFileList = getElementUiUploadFile(form.cover);
        this.smallCoverFileList = getElementUiUploadFile(form.smallCover);
        this.alertCoverFileList = getElementUiUploadFile(form.alertCover);
        this.form = Object.assign(this.form, form);
        this.listRegion();
        this.loadOpenCountry();
      },
      immediate: true
    }
  },
  methods: {
    querySearchContentRestaurants(queryString, cb) {
      var contentRestaurants = this.contentRestaurants;
      var results = queryString
        ? contentRestaurants.filter(restaurant => {
            return (
              restaurant.value
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) === 0
            );
          })
        : contentRestaurants;
      cb(results);
    },
    uploadAlertCover(file) {
      const that = this;
      that.alertCoverUploadLoading = true;
      that
        .$simpleUploadFlie(file, that.$application.fileBucket.other)
        .then(res => {
          that.alertCoverUploadLoading = false;
          that.form.alertCover = that.$getAccessImgUrl(res.name);
        })
        .catch(er => {
          that.alertCoverUploadLoading = false;
        });
    },
    uploadSmallCover(file) {
      const that = this;
      that.smallCoverUploadLoading = true;
      that
        .$simpleUploadFlie(file, that.$application.fileBucket.other)
        .then(res => {
          that.smallCoverUploadLoading = false;
          that.form.smallCover = that.$getAccessImgUrl(res.name);
        })
        .catch(er => {
          that.smallCoverUploadLoading = false;
        });
    },
    handleSmallCoverFileRemove(file, fileList) {
      this.form.smallCover = "";
      this.smallCoverUploadLoading = false;
    },
    handlealertCoverFileRemove(file, fileList) {
      this.form.alertCover = "";
      this.alertCoverUploadLoading = false;
    },
    uploadCover(file) {
      const that = this;
      that.coverUploadLoading = true;
      that
        .$simpleUploadFlie(file, that.$application.fileBucket.other)
        .then(res => {
          that.coverUploadLoading = false;
          that.form.cover = that.$getAccessImgUrl(res.name);
        })
        .catch(er => {
          that.coverUploadLoading = false;
        });
    },
    handleCoverFileRemove(file, fileList) {
      this.form.cover = "";
      this.coverUploadLoading = false;
    },
    listRegion() {
      const that = this;
      that.loading = true;
      regionConfigTable({ sysOrigin: that.sysOrigin })
        .then(res => {
          that.regions = res.body || [];
          that.loading = false;
        })
        .catch(er => {
          that.loading = false;
        });
    },

    // 获取国家列表
    loadOpenCountry() {
      const that = this;

      that.loadingCountry = true;
      listPayOpenCountry()
        .then(res => {
          that.loadingCountry = false;
          that.countryList = res.body || [];
        })
        .catch(er => {
          that.loadingCountry = false;
          console.error(er);
        });
    },

    // 选择国家
    changeCountry(val) {
      const that = this;
      that.form.countryCode = that.selectCountryCode.join(",");
    },
    handleClose() {
      this.$emit("close");
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return;
        }
        const submitForm = Object.assign({}, that.form);
        submitForm.displayPosition = submitForm.displayPosition.join(",");
        that.submitLoading = true;

        if (!submitForm.sysOrigin) {
          submitForm.sysOrigin = that.sysOrigin;
        }

        if (!submitForm.sysOrigin) {
          that.$opsMessage.fail(
            that.$t("pages.bannerManager.message.missingSystem")
          );
          return;
        }
        if (submitForm.id) {
          updateBanner(submitForm)
            .then(res => {
              that.submitLoading = false;
              that.$emit("success", res);
            })
            .catch(er => {
              that.submitLoading = false;
              that.$emit("fial", er);
            });
          return;
        }
        addBanner(submitForm)
          .then(res => {
            that.submitLoading = false;
            that.$emit("success", res);
          })
          .catch(er => {
            that.submitLoading = false;
            console.error(er);
            that.$emit("fial", er);
          });
      });
    },
    loadSearchRoom() {
      this.searchDisabled = true;
    },
    searchRoomSuccess(res) {
      this.searchDisabled = false;
      if (!res) {
        return;
      }
      this.form.params = res.id;

      if (this.form.content === "ENTER_ROOM") {
        this.tmpRoomId = res.roomAccount;
      }
    },
    searchRoomFail() {
      this.form.params = "";
      this.searchDisabled = false;
    }
  }
};
</script>
