<template>
  <div class="send-props">
    <el-alert
      :title="$t('pages.propsSendTool.title.ticket')"
      style="margin-bottom: 10px;"
      :closable="false"
    />
    <el-form
      ref="form"
      :model="propsGiveForm"
      :rules="formRules"
      label-width="85px"
    >
      <el-form-item :label="$t('pages.propsSendTool.form.receiver')" prop="receiverAccounts">
        <el-input
          v-model="propsGiveForm.receiverAccounts"
          :placeholder="$t('pages.propsSendTool.placeholder.receiverAccounts')"
        />
      </el-form-item>
      <el-form-item :label="$t('pages.propsSendTool.form.system')" prop="sysOrigin">
        <el-form-item>
          <el-select
            v-model="propsGiveForm.sysOrigin"
            :placeholder="$t('pages.propsSendTool.placeholder.system')"
            style="width:100%;"
            class="filter-item"
            @change="changeSysOrigin"
          >
            <el-option
              v-for="item in permissionsSysOriginPlatforms"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item :label="$t('pages.propsSendTool.form.type')" prop="secondaryType">
        <el-select
          v-model="propsGiveForm.secondaryType"
          :placeholder="$t('pages.propsSendTool.placeholder.type')"
          style="width:100%;"
          class="filter-item"
          @change="changePropsType"
        >
          <el-option
            v-for="item in propsTicket"
            :key="item.value"
            :label="getPropsTypeName(item)"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('pages.propsSendTool.form.resource')" prop="propId">
        <div v-if="selectProps.cover" class="payer-source">
          <div class="paler-icon">
            <svgaplayer type="popover" :url="selectProps.sourceUrl || ''" />
          </div>
          <img :src="selectProps.cover" alt="cover" />
        </div>
        <props-source-select-popover
          v-loading="
            propsTypeMap[propsGiveForm.secondaryType]
              ? propsTypeMap[propsGiveForm.secondaryType].loading
              : false
          "
          :data="
            propsTypeMap[propsGiveForm.secondaryType]
              ? propsTypeMap[propsGiveForm.secondaryType].list
              : []
          "
          :property="selectPopoverProperty"
          :visible="visiblePopover"
          :show-filter="true"
          @select="selectPropsSourcePopover"
        />
      </el-form-item>
      <el-form-item
        v-if="propsGiveForm.secondaryType == 'NOBLE_VIP'"
        :label="$t('pages.propsSendTool.form.vipOrigin')"
        prop="vipOrigin"
      >
        <el-select
          v-model="propsGiveForm.vipOrigin"
          :placeholder="$t('pages.propsSendTool.placeholder.vipOrigin')"
          style="width:100%;"
          class="filter-item"
        >
          <el-option :label="$t('pages.propsSendTool.vipOrigin.SYSTEM_GIVE')" value="SYSTEM_GIVE" />
          <el-option :label="$t('pages.propsSendTool.vipOrigin.BUY_OR_GIVE')" value="BUY_OR_GIVE" />
          <el-option :label="$t('pages.propsSendTool.vipOrigin.ACTIVITY_AWARD')" value="ACTIVITY_AWARD" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('pages.propsSendTool.form.validDays')" prop="propDays">
        <el-input
          v-model="propsGiveForm.propDays"
          type="number"
          :placeholder="$t('pages.propsSendTool.placeholder.validDays')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="submitLoading" @click="onGiveSubmit"
          >{{ $t('pages.propsSendTool.action.send') }}</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  listNotFamilyBySysOriginType,
  sendPropsTicketGiveUser
} from "@/api/props";
import { propsTicket } from "@/constant/type";
import PropsSourceSelectPopover from "@/components/data/PropsSourceSelectPopover";
import { mapGetters } from "vuex";

export default {
  name: "SendTicket",
  components: { PropsSourceSelectPopover },
  data() {
    const propsTypeMap = {};
    propsTicket.forEach(item => {
      propsTypeMap[item.value] = {
        list: [],
        loading: false,
        loadData: false
      };
    });
    return {
      propsTicket,
      visiblePopover: false,
      propsTypeMap,
      selectPopoverProperty: {
        label: "name",
        cover: "cover",
        svgaUrl: "sourceUrl",
        value: "id"
      },
      selectProps: {},
      submitLoading: false,
      propsGiveForm: {
        sysOrigin: "",
        receiverAccounts: "",
        userIds: [],
        type: "PROPS",
        propId: "",
        propDays: "",
        secondaryType: "",
        vipOrigin: null
      },
      userInfo: {}
    };
  },

  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"]),
    formRules() {
      const commonRules = [
        {
          required: true,
          message: this.$t("pages.propsSendTool.validation.requiredField"),
          trigger: "blur"
        }
      ];
      return {
        receiverAccounts: commonRules,
        propDays: [
          {
            required: true,
            message: this.$t("pages.propsSendTool.validation.propDaysRequired"),
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (value === "" || isNaN(value)) {
                callback(new Error(this.$t("pages.propsSendTool.validation.validNumber")));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        propId: commonRules,
        secondaryType: commonRules,
        sysOrigin: commonRules
      };
    }
  },
  created() {
    this.propsTicket = this.propsTicket.filter(
      item => !(item.value === "CUSTOMIZE" || item.value === "FRAGMENTS")
    );
  },
  methods: {
    getLocalizedOption(group, value, fallback) {
      const key = `pages.propsSendTool.${group}.${value}`;
      const text = this.$t(key);
      return text === key ? fallback : text;
    },
    getPropsTypeName(item) {
      return this.getLocalizedOption("propsTypes", item.value, item.name);
    },
    changeSysOrigin(val) {
      const that = this;
      that.propsGiveForm.secondaryType = "";
      that.selectProps = {};
    },
    changePropsType(val) {
      const that = this;
      that.propsGiveForm.vipOrigin = null;
      if (!that.propsGiveForm.sysOrigin) {
        return;
      }
      that.selectProps = {};
      that.propsGiveForm.propId = "";
      const propsTypeItem = that.propsTypeMap[val];
      propsTypeItem.list = [];
      // 区分系统,如果要做缓存需要改造支持多系统资源
      // if (propsTypeItem && propsTypeItem.loadData === true) {
      //   return
      // }
      propsTypeItem.loading = true;
      listNotFamilyBySysOriginType(that.propsGiveForm.sysOrigin, val)
        .then(res => {
          propsTypeItem.loading = false;
          propsTypeItem.loadData = true;
          propsTypeItem.list = res.body || [];
        })
        .catch(er => {
          propsTypeItem.loading = false;
          console.error(er);
        });
    },
    selectPropsSourcePopover(item) {
      this.selectProps = item;
      this.propsGiveForm.propId = item.id;
    },
    onGiveSubmit() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error("error submit!!");
          return;
        }

        // 将 receiverAccounts 转换为数组并赋值给 userIds
        const formToSend = { ...that.propsGiveForm };
        if (formToSend.receiverAccounts) {
          formToSend.userIds = formToSend.receiverAccounts
            .split(",")
            .map(id => id.trim())
            .filter(id => id);
        } else {
          formToSend.userIds = [];
        }

        that.submitLoading = true;
        sendPropsTicketGiveUser(formToSend)
          .then(res => {
            if (res.errorCode === 0) {
              if (res.body) {
                that.$opsMessage.fail(
                  that.$t("pages.propsSendTool.message.invalidShortAccounts", {
                    accounts: res.body
                  })
                );
                that.submitLoading = false;
                return;
              }
              that.$opsMessage.success();
              that.selectProps = {};
              that.propsGiveForm.propId = "";
              that.submitLoading = false;
              return;
            }
            that.$opsMessage.fail(res.errorMsg);
            that.submitLoading = false;
          })
          .catch(er => {
            that.submitLoading = false;
            console.error(er);
          });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.payer-source {
  position: relative;
  .paler-icon {
    position: absolute;
    left: 0px;
    top: -10px;
  }
  img {
    width: 100px;
    height: 100px;
  }
}
</style>
