<template>
  <view class="xd-select" :style="{width: width}">
    <picker
      class="xd-select__picker "
      @change="bindPickerChange"
      :range="flimTypeList"
      :mode="mode"
      :value="flimTypeIndex"
      :disabled="disabled"
      @cancel="bindPickerClick(false)"
    >
      <view
        class="xd-select__box"
        :class="{'xd-select__disabled': disabled}"
        :style="{height: uiHeight + 'rpx'}"
      >
        <view v-if="label">{{label}}</view>
        <view
          :style="{
            border: borderWidth + 'rpx solid ' + (!disabled ? uiColor : '#eee'),
            color: getColor ? '#999': textColor,
            background: disabled ? '#f4f4f4' : '#fff',
            borderRadius: radius,
            height: uiHeight + 'rpx',
            lineHeight: uiHeight + 'rpx',
            'box-sizing': 'border-box',
            padding: padding,
            fontSize: uiFontSize + 'rpx',
            justifyContent: justifyContent,
            width: width,
            opacity: disabled ? 0.8: 1
          }"
          @click="bindPickerClick(true)"
        >
          <text
            :style="{
              'max-height': uiHeight + 'rpx',
              'margin': margin,
              'color': color
            }"
          >{{getSelectName}}</text>
          <view>
            <slot :status="isUp">
              <xd-font-icon
                size="20"
                :icon="isUp ? 'iconshang_up': 'iconxia_down'"
                :color="color"
              ></xd-font-icon>
            </slot>
          </view>
        </view>
      </view>
    </picker>
  </view>
</template>

<script>

  /**
   * XdSelect 全局Ui, 不支持异步数据
   * @description 自定义选择插件
   * @property textColor {String} 文字颜色 默认：
   * @property justifyContent {String} 文字对齐方式 默认：flex-start  其值：flex-start，flex-end ,space-between
   * @property fontSize {Number} 文字大小 默认：28rpx
   * @property borderWidth {Number|String}  边框大小 默认： 1rpx
   * @property padding {String} 显示内容区域填充 默认: 0 20rpx
   * @property height {Number|String}  插件高度 默认：默认: 60rpx
   * @property width {String} 插件宽度 默认：默认: auto
   * @property defaultValue {Number}  选中的默认值 默认：第一项
   * @property list {Array|Object}  选项卡数据列表  null=>使用默认数据
   * @property disabled {Boolean}  是否禁用  默认：false
   * @property contentPrefix {Boolean}  文字内容后缀  默认：-
   * @property mode {String}  模式类型  默认：selector 其值：multiSelector，selector
   * @property label {String}  选择框名称  默认：空，不显示
   * @property placeholder {String}  提示文案  默认：空，不显示
   * @property radius {String}  显示圆角  默认：25rpx
   * @property borderColor {String}  显示圆角  默认：''
   *
   * @event {Function} change    点击元宝事件
   */
  import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
  import {
    getParentsStyle, //获取页面风格单个键值值
  } from '@/utils/xd.base';

  export default {
    name: "XdSelect",
    components: {XdFontIcon},
    props: {
      textColor: {
        type: String,
        default: '#333'
      },
      width: {
        type: String,
        default: 'auto'
      },
      justifyContent: {
        type: String,
        default: 'flex-start' //
      },
      fontSize: {
        type: String | Number,
        default: 28
      },
      padding: {
        type: String,
        default: '0 20rpx'
      },
      borderWidth: {
        type: String | Number,
        default: ''
      },
      height: {
        type: String | Number,
        default: ''
      },
      defaultValue: {
        type: String | Number | null | Array,
        default: null
      },
      list: {
        type: Array | null,
        default: null
      },
      disabled: {
        type: Boolean,
        default: false
      },
      contentPrefix: {
        type: String,
        default: '-'
      },
      mode: {
        type: String,
        default: 'selector', //multiSelector selector
      },
      label: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: ''
      },
      radius: {
        type: String,
        default: '30rpx'
      },
      borderColor: {
        type: String,
        default: ''
      },
      margin: {
        type: String,
        default: ''
      },
      color: {
        type: String,
        default: '#333'
      }

    },
    data() {
      return {
        uiHeight: 60,
        isUp: false,
        flimTypeIndex: null, //选择ID
        flimTypeList: [], //选项列表
        flimTypeListSource: [], //原始数据

        //下拉菜单icon
        iconArray: [
          {up: 'iconrepository-xialaxuanxiangup', down: 'iconrepository-xialaxuanxiangdown'},
          {up: '', down: ''},
        ],

        defaultFormot: [ //测试数据
          {value: 1, label: '2D'},
          {value: 2, label: '3D'},
          {value: 3, label: '3DMAX'},
          {value: 4, label: 'AA'}
        ],

        uiColor: '',
        uiFontSize: 28,
        styleMainColor: '', //插件主题风格样式
      }
    },

    computed: {
      getSelectName() {
        if (this.flimTypeIndex === null || this.flimTypeIndex.length === 0) {
          return this.placeholder;
        }
        if (this.mode === 'selector') {
          return this.flimTypeList[this.flimTypeIndex];
        }

        if (this.mode === 'multiSelector') {
          let select = [];
          this.flimTypeIndex.map((item, index) => {
            select.push(this.flimTypeList[index][item]);
          });
          return select.join(this.contentPrefix);
        }

      },

      getColor() {
        if (this.disabled || this.flimTypeIndex === null || this.flimTypeIndex.length === 0) return true;
        if (this.mode === 'selector') return !this.flimTypeListSource[this.flimTypeIndex];
        return false;
      },
    },

    watch: {
      defaultValue() {
        if (this.mode === 'selector') this.init(this.list);
        if (this.mode === 'multiSelector') this.multiInit(this.list)
      },
      list(value) {
        if (this.mode === 'selector') this.init(value);
        if (this.mode === 'multiSelector') this.multiInit(value)
      },
    },

    async created() {
      this.styleMainColor = await getParentsStyle(this.$parent, '$mainColor');
      this.uiColor = this.styleMainColor;
      this.uiFontSize = this.fontSize;
      if (this.borderColor) this.uiColor = this.borderColor;

      //字号
      if (this.$xdUniHelper.checkVarType(this.fontSize) === 'string') {
        this.uiFontSize = Number(this.fontSize);
      }


      if (this.height) {
        this.uiHeight = this.height;
        if (this.$xdUniHelper.checkVarType(this.height) === 'string') {
          this.uiHeight = Number(this.height);
        }
      }

      //使用测试数据
      if (this.list === null) {

        if (this.mode === 'selector') this.init(this.defaultFormot);
        if (this.mode === 'multiSelector') this.multiInit([this.defaultFormot, this.defaultFormot])
      }
      //使用正式数据
      else if (this.$xdUniHelper.checkVarType(this.list) === 'array') {
        if (this.mode === 'selector') this.init(this.list);
        if (this.mode === 'multiSelector') this.multiInit(this.list)

      } else {
        throw new Error('数据格式错误')
      }
    },

    methods: {
      init(list = []) {
        let flimTypeList = [];
        let select = null;
        list.map((item, index) => {
          if (this.defaultValue !== null && (
            item.label === this.defaultValue ||
            item.value === this.defaultValue)
          ) {
            select = item;
            this.flimTypeIndex = index
          }
          flimTypeList.push(item.label);
        });
        this.flimTypeList = flimTypeList;
        this.flimTypeListSource = this.$xdUniHelper.cloneDeep(list);

        //已经有选中值
        if (select && !this.disabled) {
          this.$emit('input', select);
          this.$emit('change', {item: select, index: this.flimTypeIndex});
        }
      },

      multiInit(list) {
        let defaultValue = this.defaultValue;
        if (this.$xdUniHelper.checkVarType(this.defaultValue) !== 'array') {
          defaultValue = [];
        }
        let selectIndex = [];
        let flimTypeList = [];
        list.map((item, index) => {
          let tempitem = [];
          item.map((it, idx) => {
            let value = defaultValue[index];
            if (value) {
              if (value === it.label || value === it.value) {
                selectIndex.push(idx);
              }
            }
            tempitem.push(it.label);
          })
          flimTypeList.push(tempitem);
        });
        console.log(selectIndex);
        this.flimTypeIndex = selectIndex;
        this.flimTypeList = flimTypeList;

        this.flimTypeListSource = this.$xdUniHelper.cloneDeep(list);

        //已经有选中值
        if (!this.disabled && this.flimTypeIndex.length > 0) {
          let select = [];
          this.flimTypeIndex.map((item, index) => {
            select.push(this.flimTypeListSource[index][item]);
          });
          this.$emit('input', select);
          this.$emit('change', {item: select, index: this.flimTypeIndex})
        }
      },

      bindPickerChange(e) {

        this.isUp = false;
        if (e['detail']['value'] === this.flimTypeIndex) return;
        this.flimTypeIndex = e['detail']['value'];

        if (this.mode === 'selector') {
          if (!this.flimTypeListSource[this.flimTypeIndex]) return;
          this.$emit('input', this.flimTypeListSource[this.flimTypeIndex]);
          this.$emit('change', {item: this.flimTypeListSource[this.flimTypeIndex], index: this.flimTypeIndex})
        }

        if (this.mode === 'multiSelector') {
          let select = [];
          this.flimTypeIndex.map((item, index) => {
            select.push(this.flimTypeListSource[index][item]);
          });
          this.$emit('input', select);
          this.$emit('change', {item: select, index: this.flimTypeIndex})
        }

      },


      bindPickerClick(type) {
        if (!this.disabled) this.isUp = type;
      },

    }
  }
</script>

<style scoped lang="less">
  .xd-select {
    &__picker {
      z-index: 500;
    }

    &__box {
      font-size: @xd-font-size-base + 2;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      & > view:first-child {

      }

      & > view:last-child {
        flex: 1;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;

        & > text {
          .uni-max-cut(1, 60)
        }
      }

    }

    &__disabled {

    }
  }
</style>
