<template>
  <div class="manualTagList-wrap common-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <!-- 子类 -->
        <div class="common-wrap__cateTags">
          <!-- <div class="common-wrap__currentTag inline-block">
            <a href="#/platformTagList?v=122" class="common-wrap__currentTag__name">全部</a>
            <i class="el-icon-arrow-right m-l-8 m-r-8"></i>
            <template v-for="(item,index) in currentTagDatas">
              <a href="" class="common-wrap__currentTag__name">{{item.name}}</a>
              <i class="el-icon-arrow-right m-l-8 m-r-8" v-if="currentTagDatas.length-1 != index"></i>
            </template>
          </div>
          <div class="common-wrap__childTag inline-block">
            <template v-for="(item,index) in childTagDatas">
              <a href="" class="common-wrap__childTag__name">{{item.name}}</a>
            </template>
          </div> -->
          <tag-category :tagLibName="tagLibName" :tagCateId="currentGroupId"></tag-category>
        </div>
        <div class="common-wrap__opt">
          <el-input
            class="w-184"
            placeholder="请输入标签"
            prefix-icon="el-icon-search"
            v-model="tagSearch"
            @keyup.enter.native="searchEnterFun">
          </el-input>
          <el-button type="primary" @click="toAddMyTagLib('mult')" class="fr m-l-8">添加至我的标签库</el-button>
          <el-button type="primary" @click="toManualTagEdit" class="fr">新增标签</el-button>
          <el-button type="primary" @click="showCateDialog" class="fr">分类设置</el-button>
        </div>
        <div class="common-wrap__table m-t-20">
          <el-table
            ref="multipleTable"
            :data="tagTableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectChange">
            <el-table-column
              type="selection"
              >
            </el-table-column>
            <el-table-column
              prop="name"
              label="标签名称"
              >
              <!-- <template slot-scope="scope">{{ scope.row.name }}</template> -->
            </el-table-column>
            <el-table-column
              prop="tagDescribe"
              label="标签描述"
              >
            </el-table-column>
            <el-table-column
              label="是否实时"
              >
              <template slot-scope="scope">
                {{scope.row.isRealTime == 1? '实时':'非实时'}}
              </template>
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <router-link :to="{path:'/myTagDetail',query:{name:scope.row.id}}" class="edit-btn el-button--text">详情</router-link>
                <router-link :to="{path:'/manualTagEdit',query:{name:scope.row.id}}" class="edit-btn el-button--text p-l-20">编辑</router-link>
                <el-button type="text" size="small" class="p-l-20" @click="toAddMyTagLib('single',scope.row.id)">添加至我的标签库</el-button>
                <el-popover
                  placement="top"
                  width="160"
                  v-model="scope.row.popVisible">
                  <p style="line-height: 1.5; padding: 10px 10px 20px;">确认删除吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="cancelDelTag(scope.$index,scope.row)">取消</el-button>
                    <el-button type="primary" size="mini" @click="toDelTag(scope.$index,scope.row)">确定</el-button>
                  </div>
                  <el-button slot="reference" class="p-l-20" type="text">
                    删除
                  </el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block common-wrap__page text-right" v-if="tagTableData.length!=0">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
    <!-- 分类设置 -->
    <el-dialog
      title="分类设置"
      :visible.sync="cateTableVisible"
      width="543px"
      class="cate-dialog"
      :before-close="closeCateDialog">
      <el-form :model="cateForm" :rules="rules" ref="cateForm">

        <el-form-item label="二级分类" prop="cateTwo">
          <el-select v-model="cateForm.cateTwo" placeholder="请选择">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="三级分类" prop="cateThree">
          <el-input v-model="cateForm.cateThree" auto-complete="off" placeholder="请选择分类名称" @keyup.native="(value) => toInput(value)"></el-input>
          <label class="input-label">{{inputNum}}/{{limitLength}}</label>
          <el-button type="text" size="small" class="" @click="toAddCate('cateForm')">添加</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="cateTableData" height="275">
        <el-table-column label="分类名称">
          <template slot-scope="scope">
             {{ !scope.row.editAble? scope.row.name: ''}}
              <el-input v-if="scope.row.editAble" size="small" class="h5-el-input" v-model="scope.row.inputValue" type="text" placeholder="请输入分类名称" @keyup.native="(value) => toEditInput(value,scope.$index,scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template slot-scope="scope"  >
            <el-button v-if="!scope.row.editAble" type="text" size="small" class="" @click="toEditCate(scope.$index,scope.row)">编辑</el-button>
            <el-button v-if="!scope.row.editAble" type="text" size="small" class="" @click="toDelCate(scope.$index,scope.row)">删除</el-button>

            <el-button v-if="scope.row.editAble" type="text" @click.stop="confirmEdit(scope.$index,scope.row)">确认</el-button>
            <el-button v-if="scope.row.editAble" type="text" @click.stop="cancleEdit(scope.$index,scope.row)">取消</el-button>
          </template>

        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="confirmDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import navCrumb from '@/components/nav/nav.vue';
  import tagCategory from '@/components/tagCategory.vue';
  import strLength from '@/common/js/strlen';
  import showMsg from '@/common/js/showmsg';
  import errMsg  from '@/common/js/error';
  import { _debounce } from "@/common/js/public";
  import { getRequest, postRequest, postJson, postForm } from '@/api/api';
  export default {
      name: "manualTagList",
      data() {
        return {
          // 面包屑参数
          navpath: [
            {
              name: '首页',
              path: ''
            },
            {
              name: '会员标签',
              path: ''
            }
          ],

          tagLibName: 'manualTag',// 面包屑分类需要的参数

          tagSearch: '', // 搜索值绑定的参数

          // 标签列表数据
          tagTableData:[
            {
              id: 1,
              name: "123",
              tagDescribe: '描述描述，最多200字，一行显示50字，默认显示一行',
              isRealTime: 1,
              popVisible: false,
            }
          ],
          selTagTableData: [], // 已选择

          // 分页参数
          currentPage: 1,
          pageSize: 20,
          total: 0,

          // 子分类数据
          currentGroupId: '', //当前分类 id
          currentTagDatas: [
            {
              id: 1,
              name: '基本信息',
            },
            {
              id: 2,
              name: '地理信息',
            },
          ],
          childTagDatas: [
            {
              id: 1,
              name: '其他一',
              num: 12
            },
            {
              id: 2,
              name: '其他二',
              num: 12
            },
          ],

          // 分类设置
          cateTableVisible: false,
          inputNum: 0,
          limitLength: 10,
          cateForm: {
            two: '',
            three: ''
          },
          rules: {
            cateTwo: [
              { required: true, message: '请选择分类', trigger: 'blur' }
            ],
            cateThree: [
              { required: true, message: '请输入分类名称', trigger: 'blur' },
            ]
          },
          cateTableData: [
            {
              id: 1,
              name: '分类1',
              inputValue: '',
              editAble: false,
            },
            {
              id: 1,
              name: '分类2',
              inputValue: '',
              editAble: false,
            },
            {
              id: 1,
              name: '分类3',
              inputValue: '',
              editAble: false,
            },
            {
              id: 1,
              name: '分类4',
              inputValue: '',
              editAble: false,
            }
          ]
        }
      },
      methods: {
        /**
         * 路由跳转
         */
        changeRoute(route) {
          this.$router.push(route);
        },

        /**
         * 添加到我的标签库
         */
        toAddMyTagLib(flag,id) {
          const that = this
          console.log(id)
          const para = {

          }
          if (flag === 'mult' ) {
            if (!that.selTagTableData.length) {
              that.$message.error({ message: '请选择标签' })
              return false;
            }
            para.tagId = [];
            that.selTagTableData.forEach(function(ele,index){
              para.tagId.push(ele.id)
            })
            console.log(para)
            para.tagId = para.tagId.join(',')
            that.addByTagId('addByTagIds',para)
          }else {
            para.tagId = id
            that.addByTagId('addByTagId',para)
          }

        },

        /**
         * 添加单个ID至我的标签库
         */
        addByTagId(name,para) {
          const that = this

          getRequest(`/enterpriseMemberTag/${name}`,para)
          .then((res) => {
            // console.log(res,res.data,res.data.errorCode)
            var resData = res.data
            if (resData.errorCode == 1) {
              showMsg.showmsg('添加成功','success')
              return;
            }

            errMsg.errorMsg(resData)

          })
          .catch(function (error) {
            console.log(error);

            that.$message.error({
              duration: 1000,
              message: error.message
            })
          });
        },

        /**
         * 搜索标签
         */
        searchEnterFun(e) {
          const that = this
          console.log(e)
          that.currentPage = 1;
          that.getTagList()
        },

        /**
         * 表格---多选
         */
        handleSelectChange(val) {
          const that = this
          console.log(val);
          that.selTagTableData = val;
        },

        /**
         * 分页---页码变化
         */
        handleSizeChange(val) {
          const that = this
          console.log(`每页 ${val} 条`);
          that.pageSize = val;
          that.getTagList();
        },

        /**
         * 分页---当前页变化
         */
        handleCurrentChange(val) {
          const that = this
          console.log(`当前页: ${val}`);
          that.currentPage = val;
          that.getTagList();
        },

        /**
         * 获取当前分类下下的标签
         */
        getTagList(val) {
          const that = this
          const para = {
            tagName: that.tagSearch, // 搜索字段
            tagLevelGroupId: that.currentGroupId, // 当前分类的id
            pageNum: that.currentPage, // 当前页
            pageSize: that.pageSize, // 一页显示个数
          }

          getRequest('/memberTag/handTagPageList',para)
          .then((res) => {
            // console.log(res,res.data,res.data.errorCode)
            var resData = res.data
            if (resData.errorCode == 1) {
              // showMsg.showmsg('保存成功','success')
              return;
            }

            errMsg.errorMsg(resData)

          })
          .catch(function (error) {
            console.log(error);

            that.$message.error({
              duration: 1000,
              message: error.message
            })
          });
        },

        /**
         * 删除当前标签 -- 取消
         */
        cancelDelTag(index,row) {
          const that = this
          row.popVisible = false
        },

        /**
         * 删除当前标签 -- 取消
         */
        toDelTag(index,row) {
          const that = this
          that.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.tagTableData.splice(index,1)
          }).catch(() => {

          });

        },

        /**
         * 点击新增标签
         */
        toManualTagEdit() {
          const that = this
          that.changeRoute('/manualTagEdit')
        },

        /**
         * 判断添加重复字段
         */
        isRepeat(arr) {
          const hash = {};
          for(const i in arr) {
            if(hash[arr[i]]){
               return true;
             }
             hash[arr[i]] = true;
          }
          return false;
        },

        /**
         * 点击分类设置-显示弹窗
         */
        showCateDialog() {
          const that = this
          that.cateTableVisible = true
        },

        /**
         * 添加分类
         */
        toAddCate(formName) {
          const that = this;
          that.$refs[formName].validate((valid) => {
            if (valid) {
              that.cateForm.name = that.cateForm.cateThree
              that.cateForm.editAble = false;
              that.cateForm.inputValue = '';
              that.cateTableData.push(JSON.parse(JSON.stringify(that.cateForm)))
              const arrKeys = that.cateTableData.map(item=>item.name) // 返回对象中键值集合的数组

              if (that.isRepeat(arrKeys)) {
                that.cateTableData.splice(that.cateTableData.length-1,1)
                that.$message.error({
                  duration: 1000,
                  message: "名称不能重复"
                })
                return;
              }
              showMsg.showmsg('添加成功','success')
            } else {
              console.log('error submit!!');
              return false;
            }
          });


        },

        /**
         * 编辑分类
         */
        toEditCate(index,item) {
          const that = this;
          console.log(index,item)
          item.editAble = true;
          item.inputValue = item.name
        },

        /**
         * 删除分类
         */
        toDelCate(index,item) {
          const that = this;
          console.log(index,item)
          that.cateTableData.splice(index,1)
        },

        /**
         * 确认编辑分类
         */
        confirmEdit(index,item) {
          const that = this;
          console.log(index,item)
          if (!item.inputValue.trim()) {
            that.$message.error({
              duration: 1000,
              message: "请输入分类名称"
            })
            return false;
          }

          const newCateTableData = JSON.parse(JSON.stringify(that.cateTableData))
          newCateTableData[index].name = item.inputValue

          const arrKeys = newCateTableData.map(item=>item.name) // 返回对象中键值集合的数组
          if (that.isRepeat(arrKeys)) {
            that.$message.error({
              duration: 1000,
              message: "名称不能重复"
            })
            return;
          }

          item.name = item.inputValue
          item.editAble = false
        },

        /**
         * 取消编辑分类
         */
        cancleEdit(index,item) {
          const that = this;
          console.log(index,item),
          item.editAble = false
        },

        /**
         * 输入三级分类名
         */
        toInput: function(value) {
          const that = this;
          console.log(value)

          let temp = '';
          temp = strLength.getByteVal(value.target.value,that.limitLength)
          console.log(temp)
          that.cateForm.cateThree = temp.trim()

          that.inputNum = strLength.getZhLen(temp.trim());
        },

        /**
         * 输入三级分类名
         */
        toEditInput: function(value,index,row) {
          const that = this;
          console.log(value,index,row)

          let editTemp = '';
          editTemp = strLength.getByteVal(value.target.value,that.limitLength)
          console.log(editTemp)
          row.inputValue = editTemp.trim()

        },

        /**
         * 关闭弹框
         */
        closeCateDialog() {

          this.cateTableVisible = false
        },

        /**
         * 取消-->关闭弹框
         */
        cancelDialog(){
          const that = this
          that.closeCateDialog()
        },

        /**
         * 确定-->关闭弹框
         */
        confirmDialog(){
          const that = this
          that.closeCateDialog()
        }

      },
      watch: {
        $route: {
          handler: function(val, oldVal){
            console.log("获取当前路由:",val);
            const that = this
            // 获取标签库中传递的搜索字段
            that.tagSearch = !!that.$route.query.searchName? that.$route.query.searchName : '';

            // 获取标签库传递过来的分类 id
            that.currentGroupId = !!that.$route.query.tagLevelGroupId? that.$route.query.tagLevelGroupId : '';
            that.getTagList()
          },
          // 深度观察监听
          deep: true
        },
      },
      mounted() {
        const that = this
        console.log(that.$route.query);
        // 获取标签库中传递的搜索字段
        that.tagSearch = !!that.$route.query.searchName? that.$route.query.searchName : '';

        // 获取标签库传递过来的分类 id
        that.currentGroupId = !!that.$route.query.tagLevelGroupId? that.$route.query.tagLevelGroupId : '';
        that.getTagList()
      },
      components: {
        navCrumb,
        tagCategory
      }
    }
</script>
<style lang="scss" scoped>


.cate-dialog {


  .el-form {
    .el-button--text {
      margin-left: 10px;
      vertical-align: middle;
    }
  }

  .el-select {
    width: 226px;
  }

  .el-input {
    width: 226px;
  }


}

.input-label {
    position: absolute;
    right: 210px;
    top: 2px;
    color: #606266;
    font-size: 14px;
  }
</style>
