<template>
  <div class="custom-tree-container jfgz" style="height:400px; padding:0 40px;">
    <div class="block category_list_tree">


      <el-scrollbar wrap-class="column-wrapper scrollable-items-container" :native="false" style="height: 350px;">
      <el-tree
        :data="categoryTree"
        node-key="id"
        :expand-on-click-node="false"
        :render-content="renderContent">
      </el-tree>
      </el-scrollbar>



      <el-dialog
        title="新增分类"
        width="600px"
        :visible.sync="dialogCreateCategoryVisible"
        :close-on-click-modal="false"
        @close="onDismissCreateCategoryDialog" append-to-body>
        <el-form ref="newCategoryForm" :model="newCategoryForm" :rules="rules" @submit.native.prevent
                 style="padding-right:20px;">
          <el-form-item label="分类名称" prop="name" label-width="100px">
            <el-input v-model="newCategoryForm.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCreateCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCreateCategoryForm('newCategoryForm')">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="编辑分类"
        width="600px"
        :visible.sync="dialogEditCategoryVisible"
        :close-on-click-modal="false"
        @close="onDismissEditCategoryDialog" append-to-body>
        <el-form ref="categoryForm" :model="categoryForm" :rules="rules" @submit.native.prevent style="padding-right:20px;">
          <el-form-item label="分类名称" prop="name" label-width="100px">
            <el-input v-model="categoryForm.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="从属分类" prop="pid" label-width="100px">
            <el-cascader
              v-model="categoryForm.pid"
              clearable
              :options="parentCategoryTree"
              change-on-select>
            </el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="deleteCategory()" v-show="accessEnabled.delete == 1">删除此分类</el-button>
          <el-button @click="dialogEditCategoryVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEditCategoryForm('categoryForm')">确 定</el-button>
        </div>
      </el-dialog>








    </div>
  </div>
</template>
<script>
  let id = 1000;


  export default {

    data() {
        let validateName = (rule, value, callback) => {
          var validValue = value ? value.replace(/\s/g, "").replace(/&nbsp;/ig, "") : value;
          if (!validValue) {
            return callback(new Error('请填写积分分类名称'));
          } else {
            callback();
          }
        };
      return {
        profile: this.$store.getters.user_info,
        categoryTree: [],
        dialogCreateCategoryVisible:false,
        dialogEditCategoryVisible:false,
        categoryForm: {
          id: '',
          name: '',
          pid: []
        },
        filter: {
          keywords: '',
          category_id: []
        },
        parentCategoryTree: [],
        rules: {
          name: [
            { validator: validateName, trigger: 'blur' }
          ]
        },
        accessEnabled: {
          add: 0,
          delete: 0,
          excel_import: 0,
          edit: 0,
        },
        newCategoryForm: {
          name: '',
          pid:[]
        },
        rules: {

        },
      }
    },




    methods: {

      edit(row){
        this.dialogEditCategoryVisible= true
        this.loadCurrentCategoryInfo(row.value)
      },


      loadCurrentCategoryInfo(categoryId) {

        var self = this;
        this.$http('get','/integral.php/ajax_request_common/get_category_info',{
            id: categoryId
          }).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data;
            try {
              self.parentCategoryTree = jsonData.tree;
              self.categoryForm.id = jsonData.category_info.id;
              self.categoryForm.name = jsonData.category_info.name;
              if (jsonData.path) {
                let pathStrArray = jsonData.path.split(",");
                let pathArray = pathStrArray.map((data) => {
                  return +data;
                });
                self.categoryForm.pid = pathArray;
              } else {
                self.categoryForm.pid = [];
              }
              self.dialogEditCategoryVisible = true;
            } catch (err) {
              console.log(err);
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      },

      submitEditCategoryForm: function(formName) {
        var form = this.$refs[formName];

        console.log(form);
        var self = this;
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.submitEditCategoryForm2(form);
            }
          } else {
            //console.log('验证未通过');
            return false;
          }
        });
      },


      submitEditCategoryForm2: function() {
        let dataObj = this.categoryForm;
        let formData = {};
        for(let item in dataObj) {
          if (item == 'pid') {
            let length = dataObj[item].length;
            formData[item] = length == 0 ? 0 : dataObj[item][length - 1];
          } else {
            if (!dataObj[item]) {
              continue;
            }
            formData[item] = dataObj[item];
          }
        }
        var self = this;
        this.$http('post','/integral.php/ajax_request_common/update_integral_category',formData,'','',
          {transformRequest: [(data) => {
            let paramArray = new Array();
            for (let it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]));
            }
            return paramArray.join("&");
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function (response) {
          let message = "";
          let status = 0;
          if (response.status == 200) {
            let data = response.data;
            status = isNaN(data.status) ? 0 : parseInt(data.status);
            switch (status) {
              case 1:
                message = "修改分类成功";
                break;
              case -1:
                message = "表单参数错误";
                break;
              case -2:
                message = "该分类名称已经存在，请改用其他名称";
                break;
              case -3:
                message = "分类结构冲突，不能将子分类设置为从属分类";
                break;
              default:
                message = "修改分类失败";
            }
          } else {
            message = "服务器出现问题";
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          });
          if (status == 1) {
            self.loadCategoryTree()
            self.$parent.$parent.loadRuleList()
            self.dialogEditCategoryVisible = false;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },


      onDismissEditCategoryDialog: function() {
        var form = this.$refs['categoryForm'];
        form.clearValidate();
        this.categoryForm = {
          id: '',
          name: '',
          pid: []
        };
      },


      addto: function(row){


      this.newCategoryForm.pid.push(row.value)
        this.dialogCreateCategoryVisible= true


        //this.dialogCreateCategoryVisible=true
      },

      onDismissCreateCategoryDialog: function () {
        var form = this.$refs['newCategoryForm'];
        form.clearValidate();
        this.newCategoryForm = {
          name: '',
          pid: []
        };
      },

      submitCreateCategoryForm: function (formName) {
        var form = this.$refs[formName];
        var self = this;
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.sendCreateCategoryRequest();
            }
          } else {
            //console.log('验证未通过');
            return false;
          }
        });
      },
      sendCreateCategoryRequest: function () {
        let dataObj = this.newCategoryForm;
        let formData = {};
        for (let item in dataObj) {
          if (item == 'pid') {
            let length = dataObj[item].length;
            formData[item] = length == 0 ? 0 : dataObj[item][length - 1];
          } else {
            if (!dataObj[item]) {
              continue;
            }
            formData[item] = dataObj[item];
          }
        }
        formData['site_id'] = this.profile.site_id;
        var self = this;
        this.$http('post','/integral.php/ajax_request_common/add_integral_category',formData,'','',
          {transformRequest: [(data) => {
            let paramArray = new Array();
            for (let it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]));
            }
            return paramArray.join("&");
          }]},
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function (response) {
          let message = "";
          let status = 0;
          if (response.status == 200) {
            let data = response.data;
            status = isNaN(data.status) ? 0 : parseInt(data.status);
            switch (status) {
              case 1:
                message = "新建分类成功";
                break;
              case -1:
                message = "表单参数错误";
                break;
              case -2:
                message = "该分类名称已经存在，请改用其他名称";
                break;
              default:
                message = "新建分类失败";
            }
          } else {
            message = "服务器出现问题";
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          });
          if (status == 1) {
            self.loadCategoryTree();
            self.dialogCreateCategoryVisible = false;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      loadCategoryTree: function () {
        var self = this;
        this.$http('get','/integral.php/ajax_request_common/get_integral_category_list_cascaded',{
            site_id: this.profile.site_id
          }).then(function (response) {
          if (response.status == 200) {
            let jsonData = response.data;
            try {
              self.categoryTree = jsonData;
            } catch (err) {
              console.log(err);
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      },









      delete(row) {
        const _row=row
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          let params = {
            id: _row.value
          };
          var self = this;
          this.$http('get','/integral.php/ajax_request_common/delete_integral_category',params).then(function (response) {
            var message = "";
            var status = 0;
            if (response.status == 200) {
              var data = response.data;
              status = isNaN(data.status) ? 0 : parseInt(data.status);
              switch (status) {
                case 1:
                  message = "删除积分分类成功";
                  break;
                case -1:
                  message = "表单参数错误";
                  break;
                default:
                  message = data.info ? data.info : "删除积分分类失败";
              }
            } else {
              message = "服务器出现问题";
            }
            self.$message({
              message: message,
              type: status == 1 ? 'success' : 'error'
            });
            if (status == 1) {
              self.loadCategoryTree();
              self.dialogEditCategoryVisible = false;
            }
          }).catch(function (error) {
            console.log(error);
          });
        }).catch(() => {

        });
      },







      append(data) {
        const newChild = {id: id++, label: 'testtest', children: []};
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      renderContent(h, {node, data, store}) {
        return (
          <span class= "custom-tree-node" ><span> {node.label}</span>
        <span>
        <el-button on-click={()=>this.addto(data)}type = "text" > 添加子分类 < /el-button>
          <el-button on-click={()=>this.edit(data)}
        type = "text" > 修改分类 </el-button>
          <el-button on-click = {()=>this.delete(data)}
        type = "text" > 删除分类 </el-button>
          </span>
          </span>);
      }
    },
    created() {
      this.loadCategoryTree()
    }
  }
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .jfgz .el-tree-node__content{ height:40px;}
  .category_list_tree .el-tree-node{
    border-bottom:1px solid #eee;
  }
</style>
