<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="封面" 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">banner封面</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">banner小图</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">首页弹出banner</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-form-item>

            <!-- 状态 -->
            <el-form-item label="状态" prop="showcase">
              <el-select
                v-model="form.showcase"
                placeholder="状态"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option label="下架" :value="false" />
                <el-option label="上架" :value="true" />
              </el-select>
            </el-form-item>

            <!-- 平台 -->
            <el-form-item label="平台" prop="platform">
              <el-select
                v-model="form.platform"
                placeholder="状态"
                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="类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="类型"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option label="H5" :value="'H5'" />
                <el-option label="APP" :value="'APP'" />
                <el-option label="AD" :value="'AD'" />
              </el-select>
            </el-form-item>

            <!-- 内容 -->
            <el-form-item label="内容">
              <el-autocomplete
                v-model.trim="form.content"
                style="width: 100%;"
                :fetch-suggestions="querySearchContentRestaurants"
                popper-class="form-autocomplete"
                placeholder="请输入内容"
              >
                <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="参数"
            >
              <el-input v-model.trim="form.params" type="text" />
            </el-form-item>

            <!-- 房间 -->
            <el-form-item v-if="form.content === 'ENTER_ROOM'" label="房间">
              <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="用户"
            >
              <account-input
                v-model="tmpUserId"
                :sys-origin="sysOrigin"
                placeholder="用户ID"
              />
            </el-form-item>

            <!-- 展示位 -->
            <el-form-item label="展示位" prop="displayPosition">
              <el-select
                v-model="form.displayPosition"
                placeholder="类型"
                clearable
                multiple=""
                style="width:100%;"
                class="filter-item"
              >
                <el-option
                  v-for="(item, index) in displayPosition"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <!-- 开始时间 -->
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                value-format="timestamp"
                placeholder="选择日期时间"
                style="width:100%;"
              />
            </el-form-item>

            <!-- 过期时间 -->
            <el-form-item label="过期时间" prop="expiredTime">
              <el-date-picker
                v-model="form.expiredTime"
                type="datetime"
                value-format="timestamp"
                placeholder="选择日期时间"
                style="width:100%;"
              />
            </el-form-item>

            <!-- 排序 -->
            <el-form-item label="排序" prop="depict">
              <el-input
                v-model.trim="form.sort"
                v-number
                placeholder="降序排列(数字越大越靠前)"
              />
            </el-form-item>

            <!-- 区域 -->
            <el-form-item label="区域" prop="regionList">
              <el-select
                v-model="form.regionList"
                v-loading="loading"
                multiple
                clearable
                placeholder="请选择"
                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="国家" prop="countryCode">
              <el-select
                v-model="selectCountryCode"
                v-loading="loadingCountry"
                multiple
                clearable
                placeholder="请选择"
                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="描述" 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()">取消</el-button>
          <el-button type="primary" @click="submitForm()">保存</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: "必填字段", trigger: "blur" }
    ];
    return {
      displayPosition: [
        { name: "房间内", value: "ROOM" },
        { name: "发现页", value: "EXPLORE_PAGE" },
        { name: "首页弹出层", value: "HOME_ALERT" },
        { name: "钱包", value: "WALLET" },
        { name: "游戏", value: "GAME" }
      ],
      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
      },
      contentRestaurants: [
        { value: "GIFT_PACK_BUY", label: "礼物背包" },
        { value: "ENTER_ROOM", label: "进入房间" },
        { value: "ENTER_PERSONAL_CENTER", label: "个人中心" },
        { value: "RECHARGE_IN_APP", label: "充值-站内" },
        { value: "RECHARGE_H5", label: "充值-H5(站外)" },
        { value: "PROP_STORE", label: "道具商店" }
      ],

      selectCountryCode: [],
      countryList: [],
      loadingCountry: false
    };
  },
  computed: {
    textOptTitle() {
      return `${this.row && this.row.id ? "修改" : "新增"}(${this.sysOrigin})`;
    },
    isShowCoverUpload() {
      return !this.form.cover;
    },
    isShowSmallCoverUpload() {
      return !this.form.smallCover;
    },
    isShowAlertCoverUpload() {
      return !this.form.alertCover;
    },
    ...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("系统错误, 没有平台信息!");
          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>
