<template>
	<view 
		class="uv-button-wrapper"
		:style="[btnWrapperStyle]"
	>
    <!-- #ifndef APP-NVUE -->
		<!-- #ifdef MP -->
		<!-- 為了解決微信小程序動態設置hover-class點擊態不消失的BUG -->
		<view class="uv-button-wrapper--dis" v-if="disabled || loading"></view>
		<button
		  :hover-start-time="Number(hoverStartTime)"
		  :hover-stay-time="Number(hoverStayTime)"
		  :form-type="formType"
		  :open-type="openType"
		  :app-parameter="appParameter"
		  :hover-stop-propagation="hoverStopPropagation"
		  :send-message-title="sendMessageTitle"
		  :send-message-path="sendMessagePath"
		  :lang="lang"
		  :data-name="dataName"
		  :session-from="sessionFrom"
		  :send-message-img="sendMessageImg"
		  :show-message-card="showMessageCard"
		  @getphonenumber="onGetPhoneNumber"
		  @getuserinfo="onGetUserInfo"
		  @error="onError"
		  @opensetting="onOpenSetting"
		  @launchapp="onLaunchApp"
			@contact="onContact"
			@chooseavatar="onChooseavatar"
			@agreeprivacyauthorization="onAgreeprivacyauthorization"
			@addgroupapp="onAddgroupapp"
			@chooseaddress="onChooseaddress"
			@subscribe="onSubscribe"
			@login="onLogin"
			@im="onIm"
		  hover-class="uv-button--active"
		  class="uv-button uv-reset-button"
		  :style="[baseColor, $uv.addStyle(customStyle)]"
		  @tap="clickHandler"
		  :class="bemClass"
		>
		<!-- #endif -->
    <!-- #ifndef MP -->
    <button
      :hover-start-time="Number(hoverStartTime)"
      :hover-stay-time="Number(hoverStayTime)"
      :form-type="formType"
      :open-type="openType"
      :app-parameter="appParameter"
      :hover-stop-propagation="hoverStopPropagation"
      :send-message-title="sendMessageTitle"
      :send-message-path="sendMessagePath"
      :lang="lang"
      :data-name="dataName"
      :session-from="sessionFrom"
      :send-message-img="sendMessageImg"
      :show-message-card="showMessageCard"
      :hover-class="!disabled && !loading ? 'uv-button--active' : ''"
      class="uv-button uv-reset-button"
      :style="[baseColor, $uv.addStyle(customStyle)]"
      @tap="clickHandler"
      :class="bemClass"
    >
    <!-- #endif -->
      <template v-if="loading">
        <uv-loading-icon
          :mode="loadingMode"
          :size="loadingSize * 1.15"
          :color="loadingColor"
        ></uv-loading-icon>
          <text
            class="uv-button__loading-text"
            :style="[
							{ fontSize: textSize + 'px' },
							$uv.addStyle(customTextStyle)
						]"
          >{{ loadingText || text }}</text>
      </template>
      <template v-else>
        <uv-icon
          v-if="icon"
          :name="icon"
          :color="iconColorCom"
          :size="getIconSize"
          :customStyle="{ marginRight: '2px' }"
        ></uv-icon>
        <slot>
          <text
            class="uv-button__text"
            :style="[
							{ fontSize: textSize + 'px' },
							$uv.addStyle(customTextStyle)
						]"
            >{{ text }}</text>
        </slot>
				<slot name="suffix"></slot>
      </template>
    </button>
    <!-- #endif -->
    <!-- #ifdef APP-NVUE -->
    <view
      :hover-start-time="Number(hoverStartTime)"
      :hover-stay-time="Number(hoverStayTime)"
      class="uv-button"
      :hover-class="
        !disabled && !loading && !color && (plain || type === 'info')
          ? 'uv-button--active--plain'
          : !disabled && !loading && !plain
          ? 'uv-button--active'
          : ''
      "
      @tap="clickHandler"
      :class="bemClass"
      :style="[baseColor, $uv.addStyle(customStyle)]"
    >
      <template v-if="loading">
        <uv-loading-icon
          :mode="loadingMode"
          :size="loadingSize * 1.15"
          :color="loadingColor"
        ></uv-loading-icon>
        <text
          class="uv-button__loading-text"
          :style="[nvueTextStyle,$uv.addStyle(customTextStyle)]"
          :class="[plain && `uv-button__text--plain--${type}`]"
          >{{ loadingText || text }}</text>
      </template>
      <template v-else>
        <uv-icon
          v-if="icon"
          :name="icon"
          :color="iconColorCom"
          :size="getIconSize"
        ></uv-icon>
        <text
          class="uv-button__text"
          :style="[
            {
              marginLeft: icon ? '2px' : 0,
            },
            nvueTextStyle,
						$uv.addStyle(customTextStyle)
          ]"
          :class="[plain && `uv-button__text--plain--${type}`]"
          >{{ text }}</text>
				<slot name="suffix"></slot>
      </template>
    </view>
    <!-- #endif -->
	</view>
</template>

<script>
import throttle from '@/uni_modules/uv-ui-tools/libs/function/throttle.js';
import mpMixin from '@/uni_modules/uv-ui-tools/libs/mixin/mpMixin.js'
import mixin from '@/uni_modules/uv-ui-tools/libs/mixin/mixin.js'
import button from '@/uni_modules/uv-ui-tools/libs/mixin/button.js'
import openType from '@/uni_modules/uv-ui-tools/libs/mixin/openType.js'
import props from "./props.js";
/**
 * button 按鈕
 * @description Button 按鈕
 * @tutorial https://www.uvui.cn/components/button.html
 * @property {Boolean}			hairline				是否顯示按鈕的細邊框 (默認 true )
 * @property {String}			type					按鈕的預置樣式，info，primary，error，warning，success (默認 'info' )
 * @property {String}			size					按鈕尺寸，large，normal，mini （默認 normal）
 * @property {String}			shape					按鈕形狀，circle（兩邊為半圓），square（帶圓角） （默認 'square' ）
 * @property {Boolean}			plain					按鈕是否鏤空，背景色透明 （默認 false）
 * @property {Boolean}			disabled				是否禁用 （默認 false）
 * @property {Boolean}			loading					按鈕名稱前是否帶 loading 圖標(App-nvue 平臺，在 ios 上為雪花，Android上為圓圈) （默認 false）
 * @property {String | Number}	loadingText				加載中提示文字
 * @property {String}			loadingMode				加載狀態圖標類型 （默認 'spinner' ）
 * @property {String | Number}	loadingSize				加載圖標大小 （默認 15 ）
 * @property {String}			openType				開放能力，具體請看uniapp穩定關於button組件部分說明
 * @property {String}			formType				用於 <form> 組件，點擊分別會觸發 <form> 組件的 submit/reset 事件
 * @property {String}			appParameter			打開 APP 時，向 APP 傳遞的參數，open-type=launchApp時有效 （註：只微信小程序、QQ小程序有效）
 * @property {Boolean}			hoverStopPropagation	指定是否阻止本節點的祖先節點出現點擊態，微信小程序有效（默認 true ）
 * @property {String}			lang					指定返回用戶信息的語言，zh_CN 簡體中文，zh_TW 繁體中文，en 英文（默認 en ）
 * @property {String}			sessionFrom				會話來源，openType="contact"時有效
 * @property {String}			sendMessageTitle		會話內消息卡片標題，openType="contact"時有效
 * @property {String}			sendMessagePath			會話內消息卡片點擊跳轉小程序路徑，openType="contact"時有效
 * @property {String}			sendMessageImg			會話內消息卡片圖片，openType="contact"時有效
 * @property {Boolean}			showMessageCard			是否顯示會話內消息卡片，設置此參數為 true，用戶進入客服會話會在右下角顯示"可能要發送的小程序"提示，用戶點擊後可以快速發送小程序消息，openType="contact"時有效（默認false）
 * @property {String}			dataName				額外傳參參數，用於小程序的data-xxx屬性，通過target.dataset.name獲取
 * @property {String | Number}	throttleTime			節流，壹定時間內只能觸發壹次 （默認 0 )
 * @property {String | Number}	hoverStartTime			按住後多久出現點擊態，單位毫秒 （默認 0 )
 * @property {String | Number}	hoverStayTime			手指松開後點擊態保留時間，單位毫秒 （默認 200 )
 * @property {String | Number}	text					按鈕文字，之所以通過props傳入，是因為slot傳入的話（註：nvue中無法控制文字的樣式）
 * @property {String}			icon					按鈕圖標
 * @property {String}			iconColor				按鈕圖標顏色
 * @property {String}			color					按鈕顏色，支持傳入linear-gradient漸變色
 * @property {Object}			customStyle				定義需要用到的外部樣式
 * @event {Function}	click			非禁止並且非加載中，才能點擊
 * @event {Function}	getphonenumber	open-type="getPhoneNumber"時有效
 * @event {Function}	getuserinfo		用戶點擊該按鈕時，會返回獲取到的用戶信息，從返回參數的detail中獲取到的值同uni.getUserInfo
 * @event {Function}	error			當使用開放能力時，發生錯誤的回調
 * @event {Function}	opensetting		在打開授權設置頁並關閉後回調
 * @event {Function}	launchapp		打開 APP 成功的回調
 * @example <uv-button>月落</uv-button>
 */
export default {
		name: "uv-button",
		// #ifdef MP
		mixins: [mpMixin, mixin, button, openType, props],
		// #endif
		// #ifndef MP
		mixins: [mpMixin, mixin, props],
		// #endif
		emits: ['click'],
		data() {
			return {};
		},
		computed: {
			// 生成bem風格的類名
			bemClass() {
				// this.bem為壹個computed變量，在mixin中
				if (!this.color) {
					return this.bem("button",
						["type", "shape", "size"],
						["disabled", "plain", "hairline"]);
				} else {
					// 由於nvue的原因，在有color參數時，不需要傳入type，否則會生成type相關的類型，影響最終的樣式
					return this.bem("button",
						["shape", "size"],
						["disabled", "plain", "hairline"]);
				}
			},
			loadingColor() {
				if (this.plain) {
					// 如果有設置color值，則用color值，否則使用type主題顏色
					return this.color ? this.color : '#3c9cff';
				}
				if (this.type === "info") {
					return "#c9c9c9";
				}
				return "rgb(200, 200, 200)";
			},
			iconColorCom() {
				// 如果是鏤空狀態，設置了color就用color值，否則使用主題顏色，
				// uv-icon的color能接受壹個主題顏色的值
				if (this.iconColor) return this.iconColor;
				if (this.plain) {
					return this.color ? this.color : this.type;
				} else {
					return this.type === "info" ? "#000000" : "#ffffff";
				}
			},
			baseColor() {
				let style = {};
				if (this.color) {
					// 針對自定義了color顏色的情況，鏤空狀態下，就是用自定義的顏色
					style.color = this.plain ? this.color : "white";
					if (!this.plain) {
						// 非鏤空，背景色使用自定義的顏色
						style["background-color"] = this.color;
					}
					if (this.color.indexOf("gradient") !== -1) {
						// 如果自定義的顏色為漸變色，不顯示邊框，以及通過backgroundImage設置漸變色
						// weex文檔說明可以寫borderWidth的形式，為什麼這裏需要分開寫？
						// 因為weex是阿裏巴巴為了部門業績考核而做的妳懂的東西，所以需要這麼寫才有效
						style.borderTopWidth = 0;
						style.borderRightWidth = 0;
						style.borderBottomWidth = 0;
						style.borderLeftWidth = 0;
						if (!this.plain) {
							style.backgroundImage = this.color;
						}
					} else {
						// 非漸變色，則設置邊框相關的屬性
						style.borderColor = this.color;
						style.borderWidth = "1px";
						style.borderStyle = "solid";
					}
				}
				return style;
			},
			// nvue版本按鈕的字體不會繼承父組件的顏色，需要對每壹個text組件進行單獨的設置
			nvueTextStyle() {
				let style = {};
				// 針對自定義了color顏色的情況，鏤空狀態下，就是用自定義的顏色
				if (this.type === "info") {
					style.color = "#323233";
				}
				if (this.color) {
					style.color = this.plain ? this.color : "white";
				}
				style.fontSize = this.textSize + "px";
				return style;
			},
			// 字體大小
			textSize() {
				let fontSize = 14,
					{ size } = this;
				if (size === "large") fontSize = 16;
				if (size === "normal") fontSize = 14;
				if (size === "small") fontSize = 12;
				if (size === "mini") fontSize = 10;
				return fontSize;
			},
			// 設置圖標大小
			getIconSize() {
				const size = this.iconSize ? this.iconSize : this.textSize * 1.35;
				return this.$uv.addUnit(size);
			},
			// 設置外層盒子的寬度，其他樣式不需要
			btnWrapperStyle() {
				const style = {};
				const customStyle = this.$uv.addStyle(this.customStyle);
				if(customStyle.width) style.width = customStyle.width;
				return style;
			}
		},
		methods: {
			clickHandler() {
				// 非禁止並且非加載中，才能點擊
				if (!this.disabled && !this.loading) {
					// 進行節流控制，每this.throttle毫秒內，只在開始處執行
					throttle(() => {
						this.$emit("click");
					}, this.throttleTime);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
$show-reset-button: 1;
@import '@/uni_modules/uv-ui-tools/libs/css/variable.scss';
@import '@/uni_modules/uv-ui-tools/libs/css/components.scss';
@import '@/uni_modules/uv-ui-tools/libs/css/color.scss';

/* #ifndef APP-NVUE */
@import "./vue.scss";
/* #endif */

/* #ifdef APP-NVUE */
@import "./nvue.scss";
/* #endif */

$uv-button-uv-button-height: 40px !default;
$uv-button-text-font-size: 15px !default;
$uv-button-loading-text-font-size: 15px !default;
$uv-button-loading-text-margin-left: 4px !default;
$uv-button-large-width: 100% !default;
$uv-button-large-height: 50px !default;
$uv-button-normal-padding: 0 12px !default;
$uv-button-large-padding: 0 15px !default;
$uv-button-normal-font-size: 14px !default;
$uv-button-small-min-width: 60px !default;
$uv-button-small-height: 30px !default;
$uv-button-small-padding: 0px 8px !default;
$uv-button-mini-padding: 0px 8px !default;
$uv-button-small-font-size: 12px !default;
$uv-button-mini-height: 22px !default;
$uv-button-mini-font-size: 10px !default;
$uv-button-mini-min-width: 50px !default;
$uv-button-disabled-opacity: 0.5 !default;
$uv-button-info-color: #323233 !default;
$uv-button-info-background-color: #fff !default;
$uv-button-info-border-color: #ebedf0 !default;
$uv-button-info-border-width: 1px !default;
$uv-button-info-border-style: solid !default;
$uv-button-success-color: #fff !default;
$uv-button-success-background-color: $uv-success !default;
$uv-button-success-border-color: $uv-button-success-background-color !default;
$uv-button-success-border-width: 1px !default;
$uv-button-success-border-style: solid !default;
$uv-button-primary-color: #fff !default;
$uv-button-primary-background-color: $uv-primary !default;
$uv-button-primary-border-color: $uv-button-primary-background-color !default;
$uv-button-primary-border-width: 1px !default;
$uv-button-primary-border-style: solid !default;
$uv-button-error-color: #fff !default;
$uv-button-error-background-color: $uv-error !default;
$uv-button-error-border-color: $uv-button-error-background-color !default;
$uv-button-error-border-width: 1px !default;
$uv-button-error-border-style: solid !default;
$uv-button-warning-color: #fff !default;
$uv-button-warning-background-color: $uv-warning !default;
$uv-button-warning-border-color: $uv-button-warning-background-color !default;
$uv-button-warning-border-width: 1px !default;
$uv-button-warning-border-style: solid !default;
$uv-button-block-width: 100% !default;
$uv-button-circle-border-top-right-radius: 100px !default;
$uv-button-circle-border-top-left-radius: 100px !default;
$uv-button-circle-border-bottom-left-radius: 100px !default;
$uv-button-circle-border-bottom-right-radius: 100px !default;
$uv-button-square-border-top-right-radius: 3px !default;
$uv-button-square-border-top-left-radius: 3px !default;
$uv-button-square-border-bottom-left-radius: 3px !default;
$uv-button-square-border-bottom-right-radius: 3px !default;
$uv-button-icon-min-width: 1em !default;
$uv-button-plain-background-color: #fff !default;
$uv-button-hairline-border-width: 0.5px !default;

.uv-button {
    height: $uv-button-uv-button-height;
    position: relative;
    align-items: center;
    justify-content: center;
    @include flex;
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    /* #endif */
    flex-direction: row;

    &__text {
        font-size: $uv-button-text-font-size;
    }

    &__loading-text {
        font-size: $uv-button-loading-text-font-size;
        margin-left: $uv-button-loading-text-margin-left;
    }

    &--large {
        /* #ifndef APP-NVUE */
        width: $uv-button-large-width;
        /* #endif */
        height: $uv-button-large-height;
        padding: $uv-button-large-padding;
    }

    &--normal {
        padding: $uv-button-normal-padding;
        font-size: $uv-button-normal-font-size;
    }

    &--small {
        /* #ifndef APP-NVUE */
        min-width: $uv-button-small-min-width;
        /* #endif */
        height: $uv-button-small-height;
        padding: $uv-button-small-padding;
        font-size: $uv-button-small-font-size;
    }

    &--mini {
        height: $uv-button-mini-height;
        font-size: $uv-button-mini-font-size;
        /* #ifndef APP-NVUE */
        min-width: $uv-button-mini-min-width;
        /* #endif */
        padding: $uv-button-mini-padding;
    }

    &--disabled {
        opacity: $uv-button-disabled-opacity;
    }

    &--info {
        color: $uv-button-info-color;
        background-color: $uv-button-info-background-color;
        border-color: $uv-button-info-border-color;
        border-width: $uv-button-info-border-width;
        border-style: $uv-button-info-border-style;
    }

    &--success {
        color: $uv-button-success-color;
        background-color: $uv-button-success-background-color;
        border-color: $uv-button-success-border-color;
        border-width: $uv-button-success-border-width;
        border-style: $uv-button-success-border-style;
    }

    &--primary {
        color: $uv-button-primary-color;
        background-color: $uv-button-primary-background-color;
        border-color: $uv-button-primary-border-color;
        border-width: $uv-button-primary-border-width;
        border-style: $uv-button-primary-border-style;
    }

    &--error {
        color: $uv-button-error-color;
        background-color: $uv-button-error-background-color;
        border-color: $uv-button-error-border-color;
        border-width: $uv-button-error-border-width;
        border-style: $uv-button-error-border-style;
    }

    &--warning {
        color: $uv-button-warning-color;
        background-color: $uv-button-warning-background-color;
        border-color: $uv-button-warning-border-color;
        border-width: $uv-button-warning-border-width;
        border-style: $uv-button-warning-border-style;
    }

    &--block {
        @include flex;
        width: $uv-button-block-width;
    }

    &--circle {
        border-top-right-radius: $uv-button-circle-border-top-right-radius;
        border-top-left-radius: $uv-button-circle-border-top-left-radius;
        border-bottom-left-radius: $uv-button-circle-border-bottom-left-radius;
        border-bottom-right-radius: $uv-button-circle-border-bottom-right-radius;
    }

    &--square {
        border-bottom-left-radius: $uv-button-square-border-top-right-radius;
        border-bottom-right-radius: $uv-button-square-border-top-left-radius;
        border-top-left-radius: $uv-button-square-border-bottom-left-radius;
        border-top-right-radius: $uv-button-square-border-bottom-right-radius;
    }

    &__icon {
        /* #ifndef APP-NVUE */
        min-width: $uv-button-icon-min-width;
        line-height: inherit !important;
        vertical-align: top;
        /* #endif */
    }

    &--plain {
        background-color: $uv-button-plain-background-color;
    }

    &--hairline {
        border-width: $uv-button-hairline-border-width !important;
    }
}
</style>
