<template>
  <view v-if="status" :style="[cusBoxComp]">
    <button
      v-if="openType === 'getPhoneNumber' || openType === 'getUserInfo' || openType === 'chooseAvatar'"
      :disabled="disabled"
      :open-type="openType"
      @getphonenumber="handleClick"
      @getuserinfo="handleClick"
      @chooseavatar="handleClick"
      :style="[{
        opacity: disabled ? 0.4 : 1,
        background: getBgColor(uiType),
        fontSize: getInfo(uiSize,'fontSize','btnFontSieList'),
        height: getInfo(uiSize,'height','btnHeightList'),
        lineHeight: getInfo(uiSize,'height','btnHeightList'),
        borderRadius: getRadius(uiSize),
        color: getTextColor,
        width: width ? width : 'auto',
        boxShadow: getBoxShadow,
        border: uiType === 'default'? '2rpx solid #dcdfe6': 0,
        padding: '0 ' + btnPaddingtList[uiSize] + 'rpx'
      },cusStyleComp,plainStyle]"
      :class="getClassName"
      type="default"
      plain="true"
    ><slot>按钮</slot></button>
    <button
      v-else
      :disabled="disabled"
      @click.stop="handleClick"
      :style="[{
      opacity: disabled ? 0.4 : 1,
      background: getBgColor(uiType),
      fontSize: getInfo(uiSize,'fontSize','btnFontSieList'),
      height: getInfo(uiSize,'height','btnHeightList'),
      lineHeight: getInfo(uiSize,'height','btnHeightList'),
      borderRadius: getRadius(uiSize),
      color: getTextColor,
      width: width ? width : 'auto',
      boxShadow: getBoxShadow,
      border: uiType === 'default'? '2rpx solid #dcdfe6': 0,
      padding: '0 ' + btnPaddingtList[uiSize] + 'rpx'
    }, plainStyle, cusStyleComp]"
    :class="getClassName"
    type="default"
    plain="true"
  ><slot>按钮</slot></button>
  </view>
</template>

<script>
  import helper from "@/utils/helper";
  import {
    getParentsStyle, //获取页面风格单个键值值
    getParentsStyles //获取页面风格列表
  } from '@/utils/xd.base';

  /**
   * XdButton 按钮UI
   * @description 按钮组件
   * @tutorial
   * @property {Boolean} disabled                   是否禁用 默认值：false
   * @property {String} bgColor                     按钮背景颜色 （可选）默认：空
   * @property {String} color                       按钮文字颜色 （可选） 默认：#fff
   * @property {String} width                       按钮宽度 （可选）默认：空
   * @property {String}  type                       按钮颜色类型（primary,default,subPrimary,danger,info,warning,success）
   * @property {String|Number} fontSize             按钮文字大小 （可选）默认：空
   * @property {String}  radius                     按钮圆角 （可选）默认：空
   * @property {String}  size                       按钮大小  default（默认）, large（最大）, medium（中）, small（小）, 'mini'
   * @property {String|null} boxShadow              启动文字阴影功能，其值与css原生属性保存一直，例如：0,0,10px rgba(0,0,0,0.5) null:关闭阴影效果
   * @property {String} gradualColor                启动ICON线性渐变 其值与css原生属性保存一直, 例如：rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%
   * @property {Boolean} isGradual                  是否启用线性渐变 默认值：false
   * @property {String} gradualType                 线性渐变类型  默认值：to right （to right 左右），（to right 左右），（135deg  左上到右下），（45deg 左下到右上（角度））
   * @event {Function} click                        按钮点击事件e
   */

  export default {
    name: "XdButton",
    props:{
      bgColor: {
        type: String,
        default: ''
      },
      openType:{
        type: String,
        default: ''
      },

      systemStyle: {
        type: Object|null,
        default: null
      },

      //标准的样式格式
      cusStyle: {
        type: Object|Array,
        default(){
          return {}
        }
      },

      color: {
        type: String,
        default: '#fff'
      },

      disabled:{
        type: Boolean,
        default: false
      },

      width: {
        type: String,
        default: ''  //rpx
      },

      type: {
        type: String,
        default: 'default', //primary,default,subPrimary,danger,info,warning,success
      },

      fontSize: {
        type: String|Number,
        default: '' , //rpx
      },

      radius: {
        type: String,
        default: ''//rpx
      },

      size: {
        type: String,
        default: 'medium' //'default', 'large', 'medium', 'small', 'mini'
      },

      /**仅支持线性渐变******/
      boxShadow: {
        type: String|null,
        default: ''
      },

      //rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%
      gradualColor: {
        type: String,
        default: 'rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%',
      },

      isGradual: {
        type: Boolean,
        default: false,
      },

      gradualType: {
        type: String,
        //to right 左右
        //to bottom 上下
        //135deg  左上到右下（角度）
        //45deg 左下到右上（角度）
        default: 'to bottom',
      },
      /**仅支持线性渐变******/

      isBoxShadow:{
        type: Boolean,
        default: false,
      },
      plain: {
        type: Boolean,
        default: false
      },
      wrapStyle: {
        type: Object|Array,
        default() {
          return {}
        }
      },
      isAuto:{
        type: Boolean,
        default: true
      }
    },
    data(){
      return {
        uiType: 'primary',
        uiSize: 'default',
        btnTypeList: ['primary','default', 'subPrimary', 'danger', 'info', 'warning', 'success', 'text'],
        btnSizeList: ['default', 'large' ,'medium', 'normal','small', 'mini'],
        status: false,
        btnHeightList: {
          default: 100,
          large: 110,
          medium: 80,
          normal:72,
          small: 60,
          mini: 50,
        },
        btnPaddingtList: {
          default: 75,
          large: 82.5,
          medium: 60,
          normal:60,
          small: 45,
          mini: 30,
        },
        btnFontSieList: {
          default: 36,
          large: 40,
          medium: 36,
          normal:28,
          small: 26,
          mini: 24,
        },
        btnShadowList: {
          default: 10,
          large: 10,
          medium: 8,
          normal:8,
          small: 6,
          mini: 4,
        },
        btnOpacityList: {
          default: .45,
          large: .40,
          medium: .25,
          normal:.25,
          small: .25,
          mini: .45,
        },
        btnBtnColor: {
          subPrimary:'',
          primary: '#EC4D71',
          default: '#fff',
          danger: '#ec5c5c',
          info:'#B8B7BE',
          warning: '#E6A23C',
          success:'#67C23A',
          text: '#F5F5F5'
        }
      }
    },
    computed: {
      cusStyleComp(){
        if(this.$xdUniHelper.checkVarType(this.cusStyle) === 'object') {
          return this.cusStyle;
        }else if(this.$xdUniHelper.checkVarType(this.cusStyle) === 'array') {
          let temp = {};
          this.cusStyle.map(item=>{
            temp = {...temp, ...item}
          })
          return temp;
        }
        return {}
      },
      getClassName() {
        let btn = `xd-button xd-button__${this.uiType} xd-button-size__${this.size}`;
        if(this.disabled) {
          btn = `${btn} xd-button__disabled`;
        }
        return btn
      },

      getTextColor(){
        if(this.uiType === 'default') return '#333';
        if(this.uiType === 'text') return  '#B8B7BE';
        return this.color || '#fff';
      },

      getBoxShadow(){
        if(!this.isBoxShadow) return `0 0 0 rgba(0,0,0,0)`
        if(this.uiType === 'default' || this.uiType === 'text'|| this.boxShadow === null) return `0 0 0 rgba(0,0,0,0)`
        let color = this.$color(this.getColor(this.uiType)).alpha(0.4).toString();
        if(this.boxShadow) return this.boxShadow;
        return `0 ${this.btnShadowList[this.uiSize]}rpx ${this.btnShadowList[this.uiSize] - 2}rpx  ${color}`;
      },
      plainStyle(){
        let color = this.getBgColor(this.uiType);
        if(this.plain){
          return {
            background: 'transparent',
            borderColor: color,
            color: color,
            borderWidth: '1rpx',
            borderStyle: 'solid'
          }
        }
        return {}
      },
      cusBoxComp(){
        let item = this.wrapStyle;
        if(this.isAuto) {
          if(this.$xdUniHelper.checkVarType(item) === 'object')  item = {...item, margin: '0 auto'}
          if(this.$xdUniHelper.checkVarType(item) === 'array')  item = [{margin: '0 auto'}].concat(item);
        }
        return item;
      },
    },
    async created(){
      let pageStyle = this.systemStyle || {};
      let style = await getParentsStyles(this.$parent);
      style = Object.assign({}, JSON.parse(JSON.stringify(style)) , pageStyle);
      this.btnBtnColor = {
        subPrimary: style.$subMainColor,
        primary: style.$mainColor,
        default: style.$defaultColor,
        danger: style.$dangerColor,
        info: style.$infoColor,
        warning: style.$warningColor,
        success: style.$successColor,
        mainGradient: style.$mainGradient,
        subGradient: style.$subGradient,
        text: '#333'
      };
      this.uiType  = this.existKey(this.type);
      this.uiSize = this.existKey(this.size, 'btnSizeList');
      this.$set(this.btnBtnColor, 'primary', style.$mainColor);
      this.$set(this.btnBtnColor, 'subPrimary', this.$color(this.btnBtnColor.primary).alpha(0.4).lighten(0.35).hex());
      this.status = true;
    },
    methods:{

      handleClick(e){
        this.$emit('click',e);
        this.$emit('tap', e);
      },

      getInfo(type, dataKey, list='btnHeightList'){
        if (this[dataKey]) {
          let temp = this[dataKey];
          if (helper.checkVarType(this[dataKey]) === 'string') {
            temp = Number(this[dataKey]);
          }
          return temp + 'rpx';
        }
        return this[list][type] + 'rpx'
      },

      getRadius(type){
        if(this.radius) return this.radius;
        if(this.uiSize === 'large') return  '20rpx';
        return Math.floor(this.btnHeightList[type] / 2) + 'rpx';
      },

      getColor(){
        let bgc = '';
        if (this.isGradual && this.gradualColor && this.gradualType) {
          let reg = /(rgba\((.*?)\))/g;
          let arr = this.gradualColor.match(reg);
          if(arr === null){
            let strArr = this.gradualColor.split(',');
            strArr = strArr[strArr.length - 1];
            return  strArr.split(' ').filter(item=>{
              return !!item;
            })[0];
          }
          else {
            return arr[arr.length - 1];
          }

        }
        return  this.bgColor || bgc || this.btnBtnColor[this.uiType];
      },

      getBgColor(){
        if(this.uiType === 'primary') {
          return this.getColor() || this.btnBtnColor.mainGradient;
        }
        if (this.uiType === 'subPrimary') {
          return this.getColor() || this.btnBtnColor.subGradient
        }

        let bgc = this.getColor();
        if (this.isGradual && this.gradualColor && this.gradualType) {
          bgc =`linear-gradient(${this.gradualType}, ${this.gradualColor})`;
        }
        return bgc;
      },

      existKey(key, type='btnTypeList'){
        if(this[type].includes(key)) return key;
        else return this[type][0];
      },
    }
  }
</script>

<style lang="less" scoped>
  .xd-button {
    z-index: 0;
    padding: 0 unit(50, rpx);
    border: 0;
    opacity: 1;
    transition: opacity .1s;
    box-sizing: border-box;

    &:hover {
      opacity: 0.7;
    }
  }


</style>
