<template>
  <transition name="el-zoom-in-top" @after-leave="doDestroy">
    <div
      class="el-color-dropdown"
      v-show="showPopper">
      <div class="el-color-dropdown__main-wrapper">
        <hue-slider ref="hue" :color="color" vertical style="float: right;"></hue-slider>
        <sv-panel ref="sl" :color="color"></sv-panel>
      </div>
      <alpha-slider v-if="showAlpha" ref="alpha" :color="color"></alpha-slider>
      <predefine v-if="showPredefine" :color="color" :colors="predefine"></predefine>
      <template v-if="showLastUsed">
        <div class="title" style="font-size: 12px;color: #333333;margin-top: 8px;">{{ t('el.colorpicker.recentlyUsed') }}</div>
        <predefine v-if="useLocalStroage" :color="color" :colors="BiColors"></predefine>
        <predefine v-else :color="color" :colors="lastUsedColors"></predefine>
      </template>
      <div class="el-color-dropdown__btns" :style="{position: 'relative'}">
        <span class="el-color-dropdown__value">
          <el-input
            v-model="customInput"
            @keyup.native.enter="handleConfirm"
            @blur="handleConfirm"
            :validate-event="false"
            size="mini">
          </el-input>
        </span>
        <i class="el_iconfont icon-xiguan" 
          id="colorbtn"  
          :style="{position: 'absolute',left: '55%',top: '50%',marginTop:' -8px',cursor:'pointer'}" 
          @click="handleClick">
        </i>
        <input type="color" v-model="gripData" style="opacity: 0;width: 0;height: 0" ref="gripColor">
        <!-- <el-button
          size="mini"
          type="text"
          class="el-color-dropdown__link-btn"
          @click="$emit('clear')">
          {{ t('el.colorpicker.clear') }}
        </el-button> -->
        <el-button
          plain
          size="mini"
          class="el-color-dropdown__btn"
          @click="confirmValue">
          {{ t('el.colorpicker.confirm') }}
        </el-button>
      </div>
    </div>
  </transition>
</template>

<script>
  import SvPanel from './sv-panel';
  import HueSlider from './hue-slider';
  import AlphaSlider from './alpha-slider';
  import Predefine from './predefine';
  import Popper from 'element-ui/src/utils/vue-popper';
  import Locale from 'element-ui/src/mixins/locale';
  import ElInput from 'element-ui/packages/input';
  import ElButton from 'element-ui/packages/button';

  export default {
    name: 'el-color-picker-dropdown',

    mixins: [Popper, Locale],

    components: {
      SvPanel,
      HueSlider,
      AlphaSlider,
      ElInput,
      ElButton,
      Predefine
    },

    props: {
      color: {
        required: true
      },
      showAlpha: Boolean,
      showPredefine: Boolean,
      showLastUsed: Boolean,
      predefine: Array,
      lastUsedColors: Array,
      useLocalStroage: String,
      BiColors: Array
    },

    data() {
      return {
        customInput: '',
        gripData: ''
      };
    },

    computed: {
      currentColor() {
        const parent = this.$parent;
        return !parent.value && !parent.showPanelColor ? '' : parent.color.value;
      }
    },

    methods: {
      handleClick() {
        if (!window.EyeDropper) {
          this.$refs['gripColor'].click();
          console.warn('Your browser does not support the EyeDropper API');
          return;
        }

        const eyeDropper = new EyeDropper();
        const openEyeDropper = eyeDropper.open();
        openEyeDropper.then(res => {
          const rgbares = this.changeColorType(res.sRGBHex);
          this.customInput = rgbares;
          this.color.fromString(rgbares);
        });
      },
      confirmValue() {
        this.$emit('pick');
      },

      handleConfirm() {
        this.color.fromString(this.customInput);
      },
      changeColorType(colorIn) {
        // 16进制颜色值的正则
        let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        // 把颜色值变成小写
        let color = colorIn.toLowerCase();
        if (reg.test(color)) {
          // 如果只有三位的值，需变成六位，如：#fff => #ffffff
          if (color.length === 4) {
            let colorNew = '#';
            for (let i = 1; i < 4; i += 1) {
              colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
            }
            color = colorNew;
          }
          // 处理六位的颜色值，转为RGB
          let colorChange = [];
          for (let i = 1; i < 7; i += 2) {
            colorChange.push(parseInt('0x' + color.slice(i, i + 2), 16));
          }
          return 'rgba(' + colorChange.join(',') + ',1)';
        } else {
          return color;
        }
      }
    },

    mounted() {
      this.$parent.popperElm = this.popperElm = this.$el;
      this.referenceElm = this.$parent.$el;
    },

    watch: {
      showPopper(val) {
        if (val === true) {
          this.$nextTick(() => {
            const { sl, hue, alpha } = this.$refs;
            sl && sl.update();
            hue && hue.update();
            alpha && alpha.update();
          });
        }
      },

      currentColor: {
        immediate: true,
        handler(val) {
          this.customInput = val;
        }
      },

      gripData: {
        immediate: true,
        handler(val) {
          if (val) {
            this.customInput = this.changeColorType(val);
            this.color.fromString(this.customInput);
          }
        }
      }
    }
  };
</script>
