<!--
 * @Author: zhp
 * @Date: 2023-04-17 14:23:17
 * @LastEditTime: 2023-06-19 10:25:26
 * @LastEditors: DY
 * @Description: 标签设定
-->
<template>
  <el-card shadow="never" class="aui-card--fill">
    <!-- <div class="mod-sys__user"> -->
    <el-input v-model="name" :placeholder="$t('supplier.title')" style="width:300px" @blur="throttle(handleAdd())" @keyup.enter.native="throttle(handleAdd())">
    </el-input>
    <!-- </div> -->
    <el-card v-for="(item, index) in tableData" :key="index" class="box-card" style="width:80%; margin-top: 15px">
      <div slot="header" class="clearfix">
        <span>{{ item.name }}</span>
        <el-button  style="float: right; padding: 3px 0" type="text" icon="el-icon-edit" />
        <el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-delete" @click="deleteHandle(item.id, item.name)" />
      </div>
      <!-- <span v-for="(item, index) in tableData" :key="index" class="text item">
        {{'列表内容'}} {{ item.name}}
      </span> -->
      <el-tag
        :key="keyValue"
        v-for="(tag, keyValue) in item.list"
        closable
        :disable-transitions="false"
        @close="handleClose(tag)">
        {{ tag.name }}
        <!-- <el-input disabled v-model="tag.name"></el-input> -->
      </el-tag>
      <el-input
        class="input-new-tag"
        v-model="inputValue[index]"
        :ref="'saveTagInput'+index"
        size="small"
        @keyup.enter.native="handleInputConfirm(index)"
        @blur="handleInputConfirm(index)"
      >
      </el-input>
      <!-- <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ New Tag</el-button> -->
    </el-card>
  </el-card>
</template>

<script>
// import basicPage from "@/mixins/basic-page"
// import basicSearch from "@/mixins/basic-search"
// import supplierProductSearch from "./components/supplierProductSearch.vue"
// import evaluationTaskAdd from "./components/evaluationTask-add.vue"
// import { timeFormatter } from '@/filters'
import i18n from "@/i18n"
// import i18n from "@/i18n";
export default {
  // mixins: [basicPage],
  data() {
    return {
      urlOptions: {
        getDataListURL: "/supplier/qmsEvaluationItemListLabel/page",
        deleteURL: "/supplier/qmsEvaluationItemListLabel",
        exportURL: '/supplier/qmsEvaluationTask/export',
        getSupplierListURL: '/supplier/qmsSupplier/page',
        getTemplateListURL: '/supplier/qmsEvaluationTask/page',
        submitURL: '/supplier/qmsEvaluationItemListLabel',
        addLabelInfoURL: '/supplier/qmsEvaluationItemListLabelInfo'
      },
      name: '',
      tableData: [],
      listQuery: {
        limit: 999,
        page: 1,
        total: 0,
      },
      dynamicTags: ['标签一', '标签二', '标签三'],
      inputVisible: false,
      inputValue: [],
      searchOrEditTitle: "",
      searchOrUpdateVisible: false,
      productOrEditTitle: "",
      addOrEditTitle: '',
      addOrUpdateVisible: false
    };
  },
  components: {
  },
  activated() {
    this.getDataList()
  },
  methods: {
    //search-bar点击
    // handleSearchCancel() {
    //   this.searchOrEditTitle = "";
    //   this.searchOrUpdateVisible = false;
    // },
    handleClose(tag) {
      console.log('你好', tag)
      this.$confirm(`确定对[名称=${tag.name}]进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(()=> {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      })
    },

    // showInput(index) {
    //   this.inputVisible = true;
    //   const ref = 'saveTagInput' + index
    //   console.log('nihc ', ref)
    //   this.$nextTick(_ => {
    //     this.$refs['saveTagInput' + index].$refs.input.focus();
    //   });
    // },
    deleteHandle(id, name) {
      this.$confirm(`确定对[名称=${name}]进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(this.urlOptions.deleteURL, { data: [id] }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => { });
    },
    handleInputConfirm(index) {
      let inputValue = this.inputValue[index];
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        this.$http["post"](this.urlOptions.addLabelInfoURL, {
          'name': inputValue
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500
            // onClose: () => {
            //   this.visible = false
            //   this.$emit("successSubmit")
            // },
          })
          console.log('打印出来结果', res.data)
          this.tableData[index].list.push({
            'id': res.data,
            'name': inputValue
          })
        })
      }
      // this.inputVisible = false;
      this.inputValue = [];
    },
    throttle(fun, delay = 10000) {
      console.log('sssssssss')
      let last, now
      return function () {
        now = Date.now()
        if (last && now - last < delay) {
          last = now
        } else {
          last = now
          fun.call(this, ...arguments)
        }
      }
    },
    handleAdd() {
      const data = {
        name: this.name
      }
      this.$http["post"](this.urlOptions.submitURL, data)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit("successSubmit")
            },
          })
        })
    },
    conditionSearch() {
      this.searchOrEditTitle = "搜索";
      this.searchOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.searchOrUpdate.init();
      });
    },
    exportHandle() {
      this.$http.get(this.urlOptions.exportURL, { responseType: 'blob' }, {
        ...this.dataForm
      }).then((res) => {
        console.log(res)
        // if (res !== 0) {
        //   return this.$message.error(res.msg) 
        // }
        let fileName = ''
        const contentDisposition = res.headers['content-disposition']
        if (contentDisposition) {
          const temp = res.headers['content-disposition']
            .split(';')[1]
            .split('=')[1]
          // 对文件名乱码转义--【Node.js】使用iconv-lite解决中文乱码
          fileName = decodeURI(temp)
          console.log(temp)
        }
        const blob = new Blob([res.data])
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      }).catch(() => { })
    },
    // handleConfirm() {
    //   this.$refs.addOrUpdate.dataFormSubmitHandle();
    // },
    // conditionSearchSubmit() {},
    conditionSearchSubmit(dataForm) {
      // console.log(key);
      // console.log(key);
      this.listQuery.supplierName = dataForm.supplierName
      this.listQuery.page = 1;
      this.getDataList();
      this.searchOrUpdateVisible = false;
      // console.log(11111);
      // this.conditionSearchSubmit();
    },
    handleClick(val) {
      if (val.type === "delete") {
        this.$confirm(`确定对[名称=${val.data.customerTypeName}]进行删除操作?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$http.delete(this.urlOptions.deleteURL, { data: [val.data.id] }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.getDataList();
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          })
          .catch(() => { });
      } else if (val.type === 'edit') {
        this.addOrEditTitle = '修改'
        this.addOrUpdateVisible = true;
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(val.data.id);
        });
      }
    },
    buttonClick(val) {
      console.log(val)
      switch (val.btnName) {
        case "search":
          this.listQuery.page = 1;
          this.getDataList();
          break;
        case "add":
          this.addOrEditTitle = '新增'
          this.addOrUpdateVisible = true;
          this.addOrUpdateHandle()
          break;
        default:
      }
    },
    getDataList() {
      this.dataListLoading = true;
      this.$http
        .get(this.urlOptions.getDataListURL, {
          params: this.listQuery,
        })
        .then(({ data: res }) => {
          this.dataListLoading = false;
          if (res.code !== 0) {
            this.tableData = [];
            this.listQuery.total = 0;
            return this.$message.error(res.msg);
          }
          this.tableData = res.data.list;
          this.listQuery.total = res.data.total;
        })
        .catch(() => {
          this.dataListLoading = false;
        });
    }
  },
};
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
