<!-- 民族 -->
<template>
  <cs-field
    ref="csField"
    class="cs-ethnicity"
    v-model="currentValue"
    :label="label"
    :rules="rules"
    :rules-key="rulesKey"
    :disabled="disabled"
    :colon="colon"
    :required="required"
    :error-message-align="errorMessageAlign"
    :label-class="labelClass"
    :label-width="labelWidth"
    :label-align="labelAlign"
    :input-align="inputAlign"
    :popupCloseable="true"
    right-icon="arrow"
    @click="showPicker"
  >
    <div :class="disabled ? 'disabled' : ''">
      <span v-if="currentValue">{{ currentValue }}</span>
      <span class="placeholder" v-else>{{ currentPlaceholder }}</span>
    </div>

    <template #popup>
      <!-- 标题 -->
      <div class="title">{{ title }}</div>
      <div class="search">
        <van-search v-model="keyword" placeholder="请输入关键字" />
      </div>

      <div class="bar-list">
        <!-- 用户搜索列表 -->
        <div class="item">
          <van-cell v-for="(item, index) in showList" :key="index" @click="selected(item)">
            <template #title>
              <div :class="item.Selected ? 'selected' : ''">
                <div class="user-item">{{ item.Label }}</div>
              </div>
            </template>
            <template #right-icon>
              <van-icon class="selected" name="passed" size="20" v-if="item.Selected" />
            </template>
          </van-cell>
        </div>
      </div>

      <!-- 选中按钮 -->
      <div class="bottom-tool">
        <van-tag type="primary" round size="large" @click="submit"> 确认 </van-tag>
      </div>
    </template>
  </cs-field>
</template>
<script>
import CsField from '../Base'
import mixin from '../mixin'
import Data from '../../../../lib/data/dthnicity.json'
import { i18n } from '../../../..//lib/locale/lang/index'

export default {
  name: 'CsFieldEthnicity',
  components: { CsField },
  mixins: [mixin],
  props: {
    // 当前输入的值
    value: {
      default: null
    },
    // 标题
    title: {
      type: String,
      default: '选择民族'
    }
  },
  data() {
    return {
      i18nLang: new Vue({ i18n }),
      currentValue: this.value,

      keyword: '', // 搜索关键字
      list: [], // 所有数据
      showList: [] // 当前显示数据
    }
  },
  //监听属性 类似于data概念
  computed: {
    currentPlaceholder() {
      if (this.placeholder) {
        return this.placeholder
      } else {
        return this.i18nLang.$t('common.placeholderEthnicity')
      }
    }
  },
  //监控data中的数据变化
  watch: {
    value: {
      handler(val, oldVal) {
        this.setData()
      },
      immediate: true, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    },
    keyword: {
      handler(val, oldVal) {
        this.filterItemFunc()
      },
      immediate: false, // 首次绑定是否执行
      deep: true // 对象内部的属性监听，也叫深度监听
    }
  },
  //方法集合
  methods: {
    change() {
      this.$forceUpdate()
    },

    /** 关键字筛选 */
    filterItemFunc() {
      this.showList.splice(0, this.showList.length)
      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i]

        if (this.keyword && !this.$util.containsObjProperty(item, this.keyword, ['Value'])) {
          continue
        }
        this.showList.push(item)
      }
    },

    /** 弹出选择框 */
    showPicker() {
      if (this.disabled) {
        return
      }
      let loading = vant.Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })

      this.keyword = ''
      this.$refs.csField.showPopup = true
      loading.clear()
    },

    /** 选中用户 */
    selected(item) {
      if (item.Selected) {
        this.currentValue = ''
        item.Selected = false
      } else {
        this.currentValue = item.Label
        item.Selected = true
      }
      this.list.forEach(itemData => {
        if (itemData.Value != item.Value) {
          itemData.Selected = false
        }
      })
      this.change()
    },

    /** 确认提交 */
    submit() {
      this.$emit('input', this.currentValue)
      this.$refs.csField.showPopup = false
    },

    /** 绑定数据 */
    setData() {
      this.list = []
      this.showList = []
      Object.keys(Data).forEach(key => {
        var value = Data[key]
        let selected = false
        if (this.value == value) {
          selected = true
        }
        let item = {
          Label: value,
          Value: value,
          Selected: selected
        }
        this.list.push(item)
        this.showList.push(item)
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang="scss" scoped>
.cs-ethnicity {
  // 标题
  .title {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    text-align: center;
  }

  // 搜索
  .search {
    position: fixed;
    top: 50px;
    left: 0;
    z-index: 999;
    width: 100%;
    height: 54px;
    line-height: 54px;
  }

  // 索引栏列表
  .bar-list {
    height: calc(100vh - 154px);
    margin: 104px 0 50px 0;
    overflow-y: auto;

    // 用户列表
    .item {
      padding-right: 25px;

      // 单个用户
      .user-item {
        display: flex;
        align-items: center;

        .name {
          margin-left: 8px;
        }
      }

      .notes {
        margin-left: 40px;
        font-size: 14px;
      }

      i {
        top: 5px;
      }

      // 选中
      .selected {
        color: #1989fa;
      }
    }
  }

  // 底部操作栏
  .bottom-tool {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 999;
    background-color: white;
    width: calc(100% - 20px);
    height: 50px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid #d2d2d2;

    .van-tag {
      padding: 5px 12px;
    }
  }
}
</style>
<style lang="scss">
.cs-ethnicity {
  .van-popup__close-icon {
    z-index: 1000;
  }
}
</style>
