<template>
  <view class="wk-field wk-field-tag">
    <view v-if="_label" class="wk-field__label">
      <view v-if="field.isNull === 1" class="line" />
      {{ _label }}
    </view>

    <view class="wk-field__body" @click.stop="handleToChoose">
      <view class="wk-field__body-core">
        <template v-if="formValue.length > 0">
          <view
            v-for="(item, index) in formValue"
            :key="index"
            :style="{ backgroundColor: item.color }"
            class="tag-item">
            {{ item.name }}
          </view>
        </template>
      </view>
      <text class="wk wk-arrow-right icon-right" />
    </view>
  </view>
</template>

<script>
  import mixins from './mixins'
	
  export default {
    name: 'WkFieldTag',
    mixins: [mixins],
    data() {
      return {
        guid: null,
        valueStr: '',
        formValue: []
      }
    },
    watch: {
      value: {
        handler() {
          if (this.value && this.value === 'string') {
            let val = []
            try {
              val = JSON.parse(this.value)
            } catch (e) {
              val = []
            }
            this.formValue = []
          } else {
            this.formValue = this.value || []
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      this.guid = this.$guid()
    },
    methods: {
      handleToChoose() {
        if (this.field.disabled) {
          if (this.config && this.config.disabledMsg) {
            this.$toast(this.config.disabledMsg)
          }
          return
        }
				
        const bridge = getApp().globalData.selectedValBridge
        bridge.tag = {
          guid: this.guid,
          maxlength: 1 / 0,
          title: '选择' + this.field.name,
          defaultVal: this.formValue || [],
          list: this.field.setting || []
        }
        uni.$on('selected-tag', this.selectedTag)
        this.$Router.navigateTo('/pages_common/selectList/tag')
      },
			
      selectedTag(data) {
        if (this.guid === data.guid) {
          this.formValue = data.data
          this.emitChangeEvt(this.formValue)
        }
        uni.$off('selected-tag')
      }
    }
  }
</script>

<style scoped lang="scss">
	@import './wkField.scss';
	.wk-field  {
		.wk-field__body {
			.wk-field__body-core {
				padding-right: 32rpx;
				display: flex;
				align-items: center;
				justify-content: flex-start;
				flex-wrap: wrap;
			
				.tag-item {
					font-size: $wk-font-sm;
					color: white;
					border-radius: 6rpx;
					padding: 5rpx 15rpx;
					margin: 5rpx;
				}
			}
		}
	}
</style>
