<template>
  <div>
    <div>
      <el-button type="primary" @click="addCateVisible = true" style="margin-bottom: 15px"
        >添加分类</el-button
      >
    </div>
    <el-table
      :data="cateList"
      v-loading="loading"      
      style="width: 100%"
      row-key="id" 
      border
      default-expand-all 
    >
      <el-table-column width="100" label="分类 ID" prop="id"> </el-table-column>
      <el-table-column label="分类名称" prop="title"> </el-table-column>
      <el-table-column label="排序" prop="sort"> </el-table-column>
      <el-table-column label="穴位列表" prop="contentList" width="900">
        <template slot-scope="scope">
          <div
            v-if="contentChange && 
              scope.row.pid != 0 &&
                scope.row.content &&
                scope.row.content.records.length > 0
            "
          >
            <div class="flexbox contentList">
              <div
                class="flexbox contenItem"
                v-for="(item, index) in scope.row.content.records"
                :key="index"
              >
                <span>{{ item.title }}</span>
                <div>
                  <i class="el-icon-edit" @click="editContent(item)"></i
                  ><i class="el-icon-delete" @click="deleteContent(item,index,scope.row)"></i>
                </div>
              </div>
              <div v-show="scope.row.content.current != scope.row.content.pages"
                class="contenItem"
                style="color:#409eff; border-color: #409eff; cursor: pointer;"
              >
              {{scope.row.content.current}}{{scope.row.content.pages}}
                <i class="el-icon-plus"></i
                ><el-link 
                  type="primary"
                  style="color:#409eff"
                  @click="getMoreContent(scope.row,scope.$index)"
                  >查看更多</el-link
                >
              </div>
            </div>

            <div style="text-align: center"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column width="300">
        <template slot-scope="scope">
          <div style="text-align: right">
            <el-button
              @click="addCateVisible = true"
              type="success"
              size="mini"
              v-if="scope.row.pid == 0"
              >添加子分类</el-button
            >
            <el-button
              type="success"
              size="mini"
              v-else
              @click="goAddContent(scope.row)"
              >添加穴位</el-button
            >
            <el-button
              type="warning"
              size="mini"
              @click="editCateShow(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" size="mini" @click="deleteCate(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加/修改分类 -->
    <el-dialog title="提示" :visible.sync="addCateVisible" width="30%" center @close="addCateClose">
      <div style="width:280px">
        <el-form
          ref="cateForm"
          :model="cateForm"
          label-width="80px"
          :rules="cateFormRule"
        >
          <el-form-item label="分类名称" prop="title">
            <el-input
              v-model="cateForm.title"
              placeholder="请输入分类名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-select v-model="cateForm.pid" placeholder="不选默认为顶级分类">
              <el-option
                v-for="item in treeList"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
            <!-- <el-cascader
              :options="treeList"
              :props="cateProps"
              v-model="cateForm.pid"
              @change="handleChange1"
            >
            </el-cascader> -->
          </el-form-item>
          <el-form-item label="paixu">
            <el-input
              v-model="cateForm.sort"
              type="number"
              placeholder="请输入排序,默认0"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateClose">取 消</el-button>
        <el-button type="primary" @click="addOreEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      treeList: [],
      cateList: [], // 渲染的数据列表
      loading: false,
      addCateVisible: false,
      cateForm: {
        sort: 0,
        title: "",
        pid: null,
        id: null
      },
      contentChange:true,
      cateProps: {
        value: "id",
        label: "title"
      },
      cateFormRule: {
        title: [{ required: true, message: "分类名称不能为空" }]
      }
    };
  },
  created() {
    this.getCatTreeList();
  },
  activated(){
    console.log('激活了')
  },
  methods: {
    // 点击查看更多，获取翻页内容
    getMoreContent(row, index) {
      console.log("加载更多",index, row);
      if(row.content.current + 1 <= row.content.pages){
        this.getContentList(row.id, row.content.current + 1, index)
      }else{
        this.$message.error('已全部加载完毕，没有更多了')
      }
     
    },
    // 获取二级分类下的内容
    getContentList(cateId,pageIndex,index) {
      console.log('收到的参数', cateId,pageIndex,index)      
      this.$http({
        url: this.$http.adornUrl("/book/point/getPointList"),
        method: "post",
        data: this.$http.adornData({
          limit: 10,
          page: pageIndex,
          pointCategoryId: cateId //此项为非必选
        })
      })
        .then(({ data }) => {          
          if (data.code == 0) {
            this.contentChange = false
            console.log("date二级内容", data.page);
            // 查找分类,并将新数据添加上
            this.cateList.forEach(element => {
              element.children.forEach(element1 => {
                if(element1.id == cateId){
                  element1.content.current = data.page.current
                  element1.content.records = element1.content.records.concat(data.page.records)
                  this.contentChange = true
                }
              })
            })
            console.log('追加后的数据', this.cateList)
          }
        })
        .catch(({ e }) => {
          console.log(e, "e");
        });
    },
    // 添加内容
    goAddContent(row) {
      // this.$router.push({ name:'acupointDetail' , params: {pid:row.id, title:'添加穴位'}})
      this.$router.push({
        path: "/acupointDetail",
        query: { pid: row.id, title: "添加穴位" }
      });
    },
    // 删除分类
    deleteCate(row) {
      this.$confirm("确定删除该分类？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/book/point/delPointCategory"),
            method: "post",
            data: this.$http.adornData({
              pointCategoryId: row.id
            })
          })
            .then(({ data }) => {
              if (data.code == 0) {
                this.$message.success("删除成功");
                this.getCatTreeList();
              }
            })
            .catch(({ e }) => {
              console.log(e, "e");
            });
        })
        .catch(() => {});
    },
    // 编辑分类
    editCateShow(row) {
      this.$nextTick(() => {
        this.cateForm = {
          title: row.title,
          id: row.id,
          pid: row.pid == 0 ? null : row.pid,
          sort: row.sort
        };
      });
      this.addCateVisible = true;
    },
    // handleChange1(e) {
    //   console.log("e", e);
    //   this.cateForm.pid = e[e.length - 1];
    // },
    // 添加或者编辑分类
    addOreEditCate() {
      this.$refs["cateForm"].validate(valid => {
        if (valid) {
          let url = "";
          this.cateForm.id
            ? (url = "/book/point/editPointCategory")
            : (url = "/book/point/addPointCategory");
          this.$http({
            // url: this.$http.adornUrl('/book/sysdictdata/selectByType/express_name'),
            url: this.$http.adornUrl(url),
            method: "post",
            data: this.$http.adornData({
              title: this.cateForm.title,
              pid: this.cateForm.pid ? this.cateForm.pid : 0,
              sort: this.cateForm.sort,
              id: this.cateForm.id
            })
          })
            .then(({ data }) => {
              console.log(data, "提交");
              if (data.code == 0) {
                this.$message.success("操作成功");
                this.getCatTreeList();
                this.addCateClose();
              }
            })
            .catch(({ e }) => {
              console.log(e, "e");
            });
        }
      });
    },
    addCateClose() {
      console.log("关闭了");
      this.addCateVisible = false;
      this.cateForm = {
        sort: 0,
        title: "",
        pid: null,
        id: null
      };
      this.$refs["cateForm"].resetFields();
      this.$nextTick(() => {
        this.$refs["cateForm"].clearValidate();
      });
    },
    getCatTreeList() {
      this.loading = true;
      this.$http({
        // url: this.$http.adornUrl('/book/sysdictdata/selectByType/express_name'),
        url: this.$http.adornUrl("/book/point/getPointCategoryList"),
        method: "post"
        // data: this.$http.adornData({

        // })
      })
        .then(({ data }) => {
          console.log(data, "树形结构");
          if (data.code == 0 && data.categorys.length > 0) {
            this.treeList = data.categorys;
            this.cateList = data.categorys;
            this.cateList.forEach(element => {
              if (element.children && element.children.length > 0) {
                element.children.forEach(element1 => {
                  let content = {};
                  // content = this.getContentList(element1.id)
                  this.$http({
                    url: this.$http.adornUrl("/book/point/getPointList"),
                    method: "post",
                    data: this.$http.adornData({
                      limit: 10,
                      page: 1,
                      pointCategoryId: element1.id //此项为非必选
                    })
                  })
                    .then(({ data }) => {
                      if (data.code == 0) {
                        // console.log("date二级内容", data.page);
                        element1.content = data.page;
                      } else {
                        element1.content = {};
                      }
                    })
                    .catch(({ e }) => {
                      console.log(e, "e");
                    });
                  // element1.content = content;
                });
              }
            });
            console.log("执行后的结果", this.cateList);
            //
          } else {
            this.treeList = [];
            this.cateList = [];
          }
          this.loading = false;
        })
        .catch(({ e }) => {
          this.loading = false;
          console.log(e, "e");
        });
    },
    editContent(item) {
      console.log("编辑内容");
      this.$router.push({
        path: "/acupointDetail",
        query: { cid: item.id, title: "编辑穴位" }
      });
    },
    deleteContent(item, index, row) {
      console.log("删除内容");
      this.$confirm("确定要删除该内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/book/point/delPoint"),
            method: "post",
            data: this.$http.adornData({
              pointId: item.id
            })
          })
            .then(({ data }) => {
              if (data.code == 0) {
               this.contentChange = false
                this.$message.success("删除成功");
                // 找到数据并删除
                this.cateList.forEach(element => {
                  element.children.forEach(element1 => {
                    if(element1.id == row.id){
                     element1.content.records.splice(index,1)
                     this.contentChange = true
                    }
                  })
                })
                console.log('删除后',this.cateList)
               // this.getCatTreeList()
              }
            })            
        })
        .catch(() => {});
    }
  },
};
</script>

<style lang="less" scoped>
/deep/.el-table__row--level-1{display: block !important;}
.flexbox {
  display: flex;
}
.contentList {
  flex-wrap: wrap;
}
.contenItem {
  line-height: 30px;
  padding: 4px;
  border: 1px solid #ddd;
  border-radius: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  i {
    padding: 5px;
    cursor: pointer;
  }
  .el-icon-edit {
    color: #409eff;
  }
  .el-icon-delete {
    color: #f56c6c;
  }
}
</style>
