<template>
  <div>
    <el-tag
      class="skill-select-tag"
      :key="tag.id"
      v-for="tag in selectedSkills"
      :disable-transitions="true"
      size="medium"
      >{{ tag.name }}</el-tag
    >
    <el-button
      v-if="canSelect"
      class="button-new-tag"
      size="small"
      @click="showSelect"
      :disabled="!this.id"
      >+ 选择技能</el-button
    >
    <el-dialog
      title="技能标签"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="24">
          <div>
            <el-tag
              class="skill-select-tag"
              :key="tag.id"
              v-for="(tag, index) in tobeSelectedSkills"
              closable
              type="primary"
              :disable-transitions="true"
              @close="removeSkill(index)"
              size="medium"
              >{{ tag.name }}</el-tag
            >
          </div>
        </el-col>
      </el-row>

      <div>请选择或者添加您所需的技能标签（最多5个）</div>
      <el-row>
        <el-col :span="24">
          <div class="autocompleteBox">
            <el-autocomplete
            popper-class="my-autocomplete"
            v-model.trim="search"
            :fetch-suggestions="querySearch"
            placeholder="请选择行业类型"
            @select="handleSelect"
            maxlength="15"
            show-word-limit
            >
            <el-button 
            type="primary"
            :disabled = "addBtnState"
            slot="suffix"
            @click="handleIconClick"
            size="mini"
            >+添加</el-button>
            <!-- <i class="el-icon-arrow-down" slot="suffix" @click="handleIconClickArrowDown"></i> -->
            <template slot-scope="{ item }">
              <div class="name">{{item.value}}</div>
            </template>
          </el-autocomplete> 

          </div>
          
          <!-- <el-autocomplete
            v-model="search"
            :fetch-suggestions="querySearch"
            :trigger-on-focus="false"
            placeholder="搜索您想要的标签"
            @select="editSkill"
            style="width: 100%"
            :validate-event="false"
          >
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete> -->
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div>
            <a
              class="skill-select-tag"
              href="javascript:void(0)"
              v-for="tag in allSkill"
              :key="tag.id"
              @click="editSkill(tag)"
            >
              <el-tag
                type="info"
                :disable-transitions="true"
                size="medium"
                effect="plain"
                >{{ tag.name }}</el-tag
              >
            </a>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button
          icon="el-icon-circle-plus-outline"
          type="primary"
          @click="submit"
          >保 存</el-button
        >
        <el-button icon="el-icon-circle-close" @click="dialogVisible = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSkillList } from "@/api/tenant/common";
import {skillListAdd} from "@/api/tenant/mission";
import _ from "lodash";

export default {
  name: "skillSelect",
  props: {
    selectedSkills: Array,
    canSelect: Boolean,
    id: String,
  },
  data() {
    return {
      search: "",
      loading: false,
      dialogVisible: false,
      tobeSelectedSkills: [],
      allSkill: [],
      flags:true,
      addBtnState:true,
      nameAttr:[]
    };
  },
  created() {
  },
  computed: {},
  watch: {
    id: function (val, oldVal) {
      if (val !== oldVal && oldVal) {
        this.$emit("add-skill", []);
      }
    },
    search:function(n,o){
      if((n || o!='') && this.tobeSelectedSkills.length != 0){
        this.$emit('clear-validator');
      }
    }
  },
  methods: {
    //获取技能列表
    getData() {
      if (this.id) {
        this.loading = true;
        getSkillList(this.id).then((res) => {
          this.allSkill = res.data.data.records;
          this.nameAttr =  this.allSkill.map((ele)=>{
            return ele.name
          })
          this.loading = false;
        });
      }
    },
    handleSelect(item) {
        this.addBtnState = true;
        // console(item);
        this.editSkill(item);
      },
    querySearch(queryString, cb) {
      let results = [];
      let nameState = this.nameAttr.indexOf(queryString);
      if(nameState == -1){
        this.addBtnState = false;
      }else{
        this.addBtnState = true;
      }
        for(let i of this.allSkill){
            i.value = i.name;
        }
        results = queryString ? this.allSkill.filter(this.createStateFilter(queryString)) : this.allSkill;
        cb(results); 
    },
    createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleIconClick() {
        let nameState = this.nameAttr.indexOf(this.search)
        if(this.search == ""){
          this.$message.closeAll()
          this.$message({
            type: "error",
            message: "请输入要添加的技能！",
          })
        }else if(nameState != -1){
            this.$message({
              type: "error",
              message: "此技能已存在，请在列表中选择！",
          })
        }else{
          skillListAdd(this.id,this.search).then((res) =>{
            if(res.data.code == 200){
              //this.search = res.data.data;
              this.$message({
                type: "success",
                message: res.data.msg,
              })
              this.addBtnState = true;
              this.getData();
            }else{
              this.$message({
                type: "error",
                message: res.data.msg,
              })
            }
        });
        }
      },
    /*技能*/
    editSkill(tag) {
      if (this.tobeSelectedSkills.length < 5) {
        if (
          this.tobeSelectedSkills.find((item) => {
            return item.id === tag.id;
          })
        ) {
          if(!this.flags){
            this.$message({
            message: "您已添加该技能标签",
            type: "warning",
          }); 
          this.flags=true;
          }
                   
        } else {          
            this.tobeSelectedSkills.push(tag); 
            this.$emit('clear-validator');
            this.flags=false;                  
        }
      } else {
        this.$message({
          message: "最多添加5个技能标签",
          type: "warning",
        });
      }
    },
    removeSkill(index) {
      this.tobeSelectedSkills.splice(index, 1);
    },
    submit() {
      if (this.tobeSelectedSkills.length) {
        this.dialogVisible = false;
        this.$emit("add-skill", this.tobeSelectedSkills);
      } else {
        this.$message.closeAll();
        this.$message({
          message: "请至少选择一个技能标签",
          type: "warning",
        });
      }
    },
    showSelect() {
      this.tobeSelectedSkills = _.cloneDeep(this.selectedSkills || []);
      this.getData();
      this.dialogVisible = true;
    },
  },
};
</script>
<style scoped>
.skill-select-tag {
  margin: 0px 5px;
}
.autocompleteBox .el-autocomplete{
  width:100%;
}
</style>
