<template>
  <el-select
    class="k-select"
    v-model="value"
    :placeholder="placeholder"
    :multiple="multiple"
    :multiple-limit="multiplelimit"
    :clearable="clearable"
    :disabled="disabled"
    @change="onChange"
    :collapse-tags="collapseTags"
    filterable
  >
    <el-option
      v-for="item in items"
      :key="item[valueName]"
      :label="item[labelName]"
      :value="item[valueName]"
    >
      <slot :item="item"></slot>
    </el-option>
  </el-select>
</template>

<script>
import sync from "../utils/computed.sync";
import { groupBy } from "lodash";
import { dictionListUser } from "@/api/system/user";

export default {
  data() {
    return {
      isOpen: false,
      items: [],
    };
  },
  computed: {
    // pv: sync("value"),
    groupData() {
      return groupBy(this.items, this.group);
    },
  },
  watch: {
    url(nv) {
      console.log("url refresh",nv)
      this.refresh();
    },
    params(n, o) {
      if (JSON.stringify(n) == JSON.stringify(o)) return;
      console.log("params refresh",n,o)
      this.refresh();
    },
    // 当数值变化后, 但是不在数据源里面, 刷新数据源
    pv() {
      if(!this.pv || this.pv.length==0) return;

      // 判断在不在源里面的方法有问题，当清空值的时候不应该刷新
      if (!this.contain(this.items, this.pv)) {
        console.log("pv refresh",this.pv)
        this.refresh();
      }
    },
    // 当数据源变换后, 如果已选的数据不在数据源中, 则重置
    items(items) {
      if (!this.contain(items, this.pv)) {
        console.log("items refresh",this.pv,items)
        if(!this.pv || this.pv.length==0) return;
        this.pv = this.multiple ? [] : null;
        this.onChange(this.pv);
      }      
    },
  },
  props: {
    value: {},
    placeholder: {},
    url: {},
    multiple: { type: Boolean, default: false },
    params: {},
    labelName: {
      default: "name",
    },
    valueName: {
      default: "id",
    },
    group: {},
    engineeringDefault: {
      type: Boolean,
      default: false,
    },
    multiplelimit:{
      type:Number,
      default:0
    },
    clearable:{
      type:Boolean,
      default:true
    },
    collapseTags:{
      type:Boolean,
      default:false,
    },
    disabled:{
      type:Boolean,
      default:false,
    },
    isMountedRefresh:{
      type:Boolean,
      default:true,
    }
  },
  methods: {
    //
    contain(items, value) {
      if (this.multiple) {        
        const tv = [];
        items.forEach((item) => {         
          if (value && ~value.indexOf(item[this.valueName])) {
            tv.push(item[this.valueName]);
          }
        });
        return tv.length != 0;
      }
      // 单选
      return (
        this.items.filter((item) => item[this.valueName] == this.pv).length != 0
      );
    },
    async refresh() {
      dictionListUser(this.params).then(items=>{
        // debugger
        if(items.data && Array.isArray(items.data)){
        items=items.data;
      }
      if (Array.isArray(items)) {
        this.items = items.map((v) => {
          if (typeof v == "string") {
            v = {
              [this.labelName]: v,
              [this.valueName]: v,
            };
          }
          return v;
        });
      } else {
        this.items = [];
      }

      // if (this.engineeringDefault) {
      //   this.items.forEach((value) => {          
      //     if ((value.code == "GCFWS" || value.code == "GCSYG") && !this.pv.includes(value.id)) {
      //       this.pv.push(value.id);
      //     }
      //   });
      //   console.log(this.pv);
      // }
      this.$emit("data", this.items);
      return this.items;
      })

      // let items = await this.$api[this.params ? "post" : "get"](
      //   this.url,
      //   this.params || {}
      // );
     
    },

    //
    onChange(val, index, item) {
      this.$forceUpdate()
      // this.$set(this.value, 0, val);
      console.log("onChange",val,this.value,item)
      this.$emit("input", val);
      // this.$emit("select", val);
      this.$emit(
        "select",
        this.multiple? this.items.filter((v) =>val.indexOf(v[this.valueName])>-1): this.items.filter((v) => v[this.valueName] == val)[0]
      );
    },
  },
  mounted() {
    if(this.isMountedRefresh)
    {
      this.refresh();
    }    
  },
};
</script>

<style lang="scss">
.k-select {
  .el-icon-refresh {
    position: absolute;
    top: 10px;
    right: 30px;
    cursor: pointer;
    color: #ccc;
  }
}
</style>
