<template>
  <div class="manualTagEdit-wrap common-wrap">
    <nav-crumb :navpath="navpath"></nav-crumb>
    <div class="right-content">
      <div class="right-box">
        <div class="manualTagEdit-wrap__form">
          <div class="manualTagEdit-wrap__title">标签基本信息</div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
            <el-form-item label="标签名称" prop="tagName" class="w-309">
              <el-input class="w-200" v-model="ruleForm.tagName" @focus="focus('tagName',10)" @keyup.native="(value) => toInput(value)">
              </el-input>
              <label class="input-label">{{inputNumObj.tagName}}/10</label>
            </el-form-item>
            <el-form-item label="所属分类" >
              <el-select v-model="ruleForm.tagCateTwo" placeholder="请选择" class="w-200">
                <el-option
                  v-for="item in optionsTwo"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select><el-select
                v-model="ruleForm.tagCateThree"
                placeholder="请选择" class="w-200 m-l-8">
                <el-option
                  v-for="item in optionsThree"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签描述" prop="tagDescription" class="w-516">
              <el-input class="w-407" type="textarea" v-model="ruleForm.tagDescription" style="height: 96px;" @focus="focus('tagDescription',200)" @keyup.native="(value) => toInput(value)">
              </el-input>
               <template><label class="input-label textarea-label">{{inputNumObj.tagDescription}}/200</label></template>
            </el-form-item>
            <el-form-item label="" class="">
              <el-button type="primary" @click.stop="confirmSave">保存</el-button>
              <el-button @click.stop="cancelSave">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- 如果新增时候,设置标签值不显示 !!currentTagId-->
        <div class="manualTagEdit-wrap__set" v-if="">
          <div class="manualTagEdit-wrap__title">标签值设置</div>
          <div class="manualTagEdit-wrap__input">
            <el-input
              v-model="addInputValue"
              placeholder="请输入"
              class="w-200 m-r-20"
              @focus="focus('addInputValue',10)"
              @keyup.native="(value) => toInput(value)">

            </el-input><label
              class="input-label textarea-label">
              {{inputNumObj.addInputValue}}/10
            </label><el-button
              class="middle"
              type="text"
              @click.stop="addInputVal">
              添加
            </el-button>
          </div>
          <div class="manualTagEdit-wrap__table m-t-20">
            <el-table :data="tagValTableData" height="275">
              <el-table-column label="标签值" width="200px">
                <template slot-scope="scope">
                   {{ !scope.row.editAble? scope.row.name: ''}}
                    <el-input v-if="scope.row.editAble" size="small" class="h5-el-input w-200" 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="操作" width="150px">
                <template slot-scope="scope"  >
                  <el-button v-if="!scope.row.editAble" type="text" size="small" class="" @click="toEditTag(scope.$index,scope.row)">编辑</el-button>
                  <el-button v-if="!scope.row.editAble" type="text" size="small" class="" @click="toDelTag(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-column  label=" ">
                <template slot-scope="scope"  >
                  <template >
                    <upload-excel-component
                      v-show="excelExistIndex != scope.$index"
                      :excelBodyData="currentExcelData"
                      :excelHeader="currentExcelHeader"
                      :currentIndex="scope.$index"
                      :failHead="scope.row.header"
                      :failData="scope.row.data"
                      @on-selected-file='selectedFile'
                      @selectIndex="setSelectIndex"
                      @clearOldData="clearOldData" >

                    </upload-excel-component>
                  </template>
                  <template v-if="excelExistIndex == scope.$index && !!currentExcelHeader.length">
                    <div class="flex excel-upload-content">
                      <i class="iconfont icon-CSV "></i>
                      <div class="flex flex-row p-l-8">
                        <div class="flex-1"><span class="p-r-8 color-303133">{{currentExcelName}}</span><span class="p-l-8 border-l-dcdfe6 color-1890ff excel-upload__del" @click.stop="clearOldData(scope.$index,scope.row)">删除</span></div>
                        <div class="flex-1 color-909399 font-12 m-t-05">已导入会员 {{ currentExcelData.length }} 人</div>
                      </div>
                    </div>

                  </template>
                </template>
              </el-table-column>
              <el-table-column  label=" ">
                <template slot-scope="scope"  >
                  <el-checkbox v-model="scope.row.check">清空已有标签会员</el-checkbox>
                </template>
              </el-table-column>
              <el-table-column  label=" " width="150px">
                <template slot-scope="scope"  >
                  <el-button type="primary" :disabled="scope.$index != excelExistIndex" @click.stop="toUploadFile(scope.$index,scope.row)">{{ !!scope.row.upStatus? '上传中':'上传' }}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <vue-gic-footer></vue-gic-footer>
    <!-- 保存 -->
    <!-- <div class="manualTagEdit-wrap__footer">
      <el-button @click.stop="cancelSave">取消</el-button>
      <el-button type="primary" @click.stop="confirmSave">保存</el-button>
    </div> -->

    <!-- 上传后弹窗 -->
   <!--  <el-dialog
      title="提示"
      :visible.sync="uploadedVisible"
      width="30%"
      :before-close="handleClose">
      <p></p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadedVisible = false">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
  import navCrumb from '@/components/nav/nav.vue';
  import uploadExcelComponent from '@/components/uploadExcel/index.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: "manualTagEdit",
      data() {
        return {
          // 面包屑参数
          navpath: [
            {
              name: '首页',
              path: ''
            },
            {
              name: '会员标签',
              path: ''
            }
          ],

          // 编辑标签的时候,获取标签的 id
          currentTagId: '',

          // 表单
          ruleForm: {
            tagName: '',
            tagCateTwo: '',
            tagCateThree: '',
            tagDescription: ''
          },
          rules: {
            tagName: [
              { required: true, message: '请输入标签名称', trigger: 'blur' },
            ],

          },

          optionsTwo: [
            {
              value: '1',
              label: '二级分类'
            }
          ],
          optionsThree: [
            {
              value: '1',
              label: '未分类'
            }
          ],

          inputNumObj: {
            tagName: 0,
            tagDescription: 0,
            addInputValue: 0,
          },

          // 输入值
          addInputValue: '',

          // 表格
          limitLength: 10,
          excelExistIndex: null, // 当前上传 excel 的表格索引
          currentExcelName: null, // 当前上传 excel 的表格名字
          currentExcelData: [], // 当前上传 excel 内容的数据
          currentExcelHeader: [], // 当前上传 excel 标题的数据
          tagValTableData: [
            {
              id: 1,
              name: '标签值1',
              inputValue: '', // 编辑输入框的值
              editAble: false, // 是否在编辑
              check: true, // 是否选择清空已有标签
              upStatus: 0, // 记录上传的状态
              // 上传失败的数据,供下载使用
              header: [],
              data: []
            },
            {
              id: 2,
              name: '标签值2',
              inputValue: '',
              editAble: false,
              check: false,
              upStatus: 0,
              header: [],
              data: []
            },
            {
              id: 3,
              name: '标签值3',
              inputValue: '',
              editAble: false,
              check: false,
              upStatus: 0,
              header: [],
              data: []
            },
            {
              id: 4,
              name: '标签值4',
              inputValue: '',
              editAble: false,
              check: false,
              upStatus: 0,
              header: [],
              data: []
            }
          ],

          // 上传后
          uploadedVisible: false,

          // 下载
          autoWidth: true,  // 下载 excel 参数
          bookType: 'xlsx', // 下载 excel 参数

        }
      },
      methods: {
        /**
         * 点击取消
         */
        cancelSave() {
          var that = this;

        },

        /**
         * 点击保存
         */
        confirmSave() {
          var that = this;

        },

        /**
         * 点击输入框
         */
        focus(name,num) {
          var that = this
          console.log(name,num);
          that.inputFlag = name;
          that.inputFlagNum = num;
        },

        /**
         * 输入
         */
        toInput: function(value) {
          var that = this;
          console.log(value);

          var temp = '';
          temp = strLength.getByteVal(value.target.value,that.inputFlagNum);
          console.log(temp)
          that.ruleForm[that.inputFlag] = temp.trim();

          that.inputNumObj[that.inputFlag] = strLength.getZhLen(that.ruleForm[that.inputFlag]);

          console.log(that.ruleForm[that.inputFlag]);
        },

         /**
         * 添加
         */
        addInputVal: function(value) {
          var that = this;
          if (!that.addInputValue.trim()) {
            that.$message.error({
              duration: 1000,
              message: "请输入标签值"
            })
            return false;
          }
          var tagsMap = null;
          if (!!that.tagValTableData.length) {
            tagsMap = that.tagValTableData.map(item=>item.name)
          }
          if (!!tagsMap&&tagsMap.indexOf(that.addInputValue) !== -1) {
            that.$message.error({
              duration: 1000,
              message: "标签值已存在"
            })

            return false;
          }

          that.tagValTableData.push({
            name: that.addInputValue.trim(),
            inputValue: '',
            editAble: false,
            check: false,
            upStatus: 0,
            header: [],
            data: []
          })

          showMsg.showmsg('添加成功','success');
        },

        /**
         * 添加三级分类
         */
        addThirdLevel() {
          const that = this
          const para = {

          }

          getRequest('/tagLevel/addHand',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
            })
          });
        },

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

        /**
         * 编辑值
         */
        toEditTag(index,item) {
          var that = this;
          console.log(index,item);
          item.editAble = true;
          item.inputValue = item.name;
        },

        /**
         * 删除值
         */
        toDelTag(index,item) {
          var that = this;
          console.log(index,item);
          that.tagValTableData.splice(index,1);
        },

        /**
         * 删除三级分类值
         */
        delThirdLevel() {
          const that = this
          const para = {

          }

          getRequest('/tagLevel/delHand',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
            })
          });
        },

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

          var newtagValTableData = JSON.parse(JSON.stringify(that.tagValTableData));
          newtagValTableData[index].name = item.inputValue;

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

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

        /**
         * 确定编辑值
         */
        editThirdLevel() {
          const that = this
          const para = {

          }

          getRequest('/tagLevel/editHand',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
            })
          });
        },

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

        /**
         * 输入编辑的值
         */
        toEditInput: function(value,index,row) {
          var that = this;
          console.log(value,index,row);

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

        },

        /**
         * 上传后子组件触发的方法-返回 excel 数据
         */
        selectedFile(data) {
          console.log(data);
          this.currentExcelData = data.results;
          this.currentExcelHeader = data.header;
          this.currentExcelName = data.name;
        },

        /**
         * 上传后子组件触发的方法-返回当前索引
         */
        setSelectIndex(index) {
          console.log(index)
          this.excelExistIndex = index;

        },

        /**
         * 上传后子组件触发的方法-返回当前索引
         */
        clearOldData(index) {
          var that = this;
          console.log("暂时无用:",index)
          that.currentExcelData = [];
          that.currentExcelHeader = [];
          that.excelExistIndex = null;
        },

        /**
         * 删除当前 excel 数据,重置索引
         */
        delCurrentExcelData(index,row){
          var that = this;
          that.currentExcelData = [];
          that.currentExcelHeader = [];
          that.excelExistIndex = null;
        },

        /**
         * 点击上传按钮
         */
        toUploadFile:_debounce(function(index,row){
          var that = this;
          console.log(index,row);
          row.upStatus = 1; // 上传中
          row.data =[
            {
              phoneNum: "13013457892"
            }
          ]
          //
          that.excelExistIndex = null
        },500),

        /**
         * 导出 excel
         */
        handleDownload() {
          const that = this

          require.ensure([], () => {
              const { export_json_to_excel } = require('@/vendor/Export2Excel')
              const tHeader = ['phoneNum']
              const filterVal = ['phoneNum']
              const list = that.currentExcelData;
              if (!list.length) {
                that.$message.error({
                  duration: 1000,
                  message: "数据为空"
                })
                return false;
              }
              const data = that.formatJson(filterVal, list)
              console.log(data)
              export_json_to_excel(tHeader, data, '导出列表');

            })
        },

        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
        },

        /**
         * 获取二级分类列表
         */
        getSecondLevel() {
          const that = this
          const para = {

          }

          getRequest('/tagLevel/handSecondLevel',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
            })
          });
        },

        /**
         * 获取三级分类列表
         */
        getThirdLevel() {
          const that = this
          const para = {

          }

          getRequest('/tagLevel/handThirdLevel',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
            })
          });
        },

      },
      mounted() {
        var that = this;
        console.log(that.$route.query);
        that.currentTagId = that.$route.query.id
      },
      components: {
        navCrumb,
        uploadExcelComponent
      }
    }
</script>
<style lang="scss" scoped>
  .manualTagEdit-wrap__title {
    width: 100%;
    height: 68px;
    line-height: 68px;
    font-size: 18px;
    color: #303133;
    font-weight: bold;
  }

  .w-407 {
    width: 407px;
  }

  .w-516 {
    width: 516px;
  }

  .manualTagEdit-wrap__form {
    border-bottom: 1px solid #DCDFE6;
  }

  .manualTagEdit-wrap__set {

    .manualTagEdit-wrap__input {
      position: relative;
      width: 250px;
    }

    .excel-upload-content {

      .icon-CSV {
        padding-top: 13px;
        font-size: 40px;
        color: #7BC788;
      }

      .flex-1 {
        font-size: 14px;
      }

      .border-l-dcdfe6 {
        border-left: 1px solid #dcdfe6;
      }

      .color-1890ff {
        color: #1890ff;
      }

      .excel-upload__del {
        cursor: pointer;
      }
    }
  }

  .manualTagEdit-wrap__footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 56px;
    line-height: 56px;
    background: #fff;
    z-index: 2;
    text-align: center;
  }

</style>
