
<template>
  <div class="page">
    <el-dialog
      :title="topicDialog.title"
      :visible.sync="topicDialog.visible"
      width="50%"
    >
      <el-form
        :model="topicform"
        :label-width="formLabelWidth"
        :rules="topicRules"
        ref="topicform"
      >
        <el-row>
          <el-form-item label="主题名称">
            <el-input v-model="topicform.topicalName"></el-input>
          </el-form-item>
        </el-row>

         <el-row>
          <el-form-item label="描述信息">
            <el-input v-model="topicform.remark"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="topicDialog.visible = false">取 消</el-button>

        <el-button type="primary" @click="submitTopicForm">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 新增主题包 -->
    <el-dialog
      :title="topicPacksDialog.title"
      :visible.sync="topicPacksDialog.visible"
      width="95%"
    >
      <el-row>
        <el-row>
          <el-form
            :model="topicPacksform"
            :label-width="formLabelWidth"
            :rules="topicPacksRules"
            ref="topicPacksform"
          >

              <el-col :span="12">
                <el-form-item prop="classifyName" label="主题事项名称">
                  <el-input v-model="classifyform.classifyName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="sortRemarks" label="主题事项说明">
                  <el-input v-model="classifyform.sortRemarks"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item prop="deliveryPeriod" label="到现场次数">
                  <el-input v-model="topicPacksform.presenceNum"></el-input>
                </el-form-item>
              </el-col>

              <Field label="办理机构" prop="jointInfoShow" v-model="topicPacksform.jointInfoShow" placeholder="请输入办理机构"/>
              <Field label="法定时限" prop="legalTimeLimitShow" v-model="topicPacksform.legalTimeLimitShow" placeholder="请输入法定时限"/>
              <Field label="承诺时限" prop="promiseTimeLimitShow" v-model="topicPacksform.promiseTimeLimitShow" placeholder="请输入承诺时限"/>
              <Field label="收费标准" prop="isChargesShow" v-model="topicPacksform.isChargesShow" placeholder="请输入收费标准"/>
              <Field label="收费金额" prop="charges" v-model="topicPacksform.charges" placeholder="请输入收费金额"/>
              <Field label="办理时间" prop="handleTimeShow" v-model="topicPacksform.handleTimeShow" placeholder="请输入办理时间"/>
              <Field label="办理地点" prop="handlePlaceShow" v-model="topicPacksform.handlePlaceShow" placeholder="请输入办理地点"/>
              <Field label="咨询方式" prop="cousultingTelephoneShow" v-model="topicPacksform.cousultingTelephoneShow" placeholder="请输入咨询方式"/>
              <Field label="结果信息" prop="resultInfo" v-model="topicPacksform.resultInfo" placeholder="请输入结果信息"/>
              <Field label="投诉电话" prop="supervisoryTelephoneShow" v-model="topicPacksform.supervisoryTelephoneShow" placeholder="请输入投诉电话"/>

          </el-form>
        </el-row>
        <el-divider></el-divider>

        <el-row>
          <!--搜索-->
          <div>
            <el-form :inline="true" size="mini">
              <el-form-item>
                <el-button plain @click="matterBatchAdd">批量添加</el-button>
              </el-form-item>

              <el-form-item style="float: right">
                <el-button plain @click="matterSearchConfirm">查询</el-button>
              </el-form-item>

              <el-form-item label="事项名称" style="float: right">
                <el-input
                  v-model="searchform.matterName"
                  placeholder="事项名称"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <!--事项列表-->
          <el-table
            size="mini"
            ref="multipleTable"
            :data="matterPageInfoData"
            tooltip-effect="dark"
            border
            v-loading="loading"
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
            <el-table-column prop="matterName" label="事项名称"  :show-overflow-tooltip="true" />
            <el-table-column width="400" prop="datumn" label="关联材料">
              <template slot-scope="scope">
                <el-row
                  v-for="(item, index) in scope.row.datumList"
                  :key="index"
                >
                  <el-tag
                    style="
                      font-size: 12px;
                      white-space: pre-wrap;
                      margin-bottom: 5px;
                    "
                  >
                    {{ item.materialName | ellipsis2 }}
                  </el-tag>
                </el-row>
              </template>
            </el-table-column>

            <el-table-column width="100" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleAdd(scope.$index, scope.row)"
                  >加入</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页器 -->
          <el-row type="flex" justify="end">
            <el-pagination
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              :current-page="matterPageInfo.currPage"
              :page-size="matterPageInfo.prePageResult"
              :page-sizes="[10, 20, 50, 100, 200]"
              layout="sizes, total, prev, pager, next, jumper"
              :total="matterPageInfo.totalResult"
            >
            </el-pagination>
          </el-row>

          <el-row
            style="margin-bottom: 10px"
            v-for="item in matterTags"
            :key="item.id"
          >
            <el-tag closable @close="handleClose(item.id)">
              {{ item.matterName | ellipsis }}
            </el-tag>
          </el-row>

          <el-row type="flex" justify="end">
            <el-button @click="topicPacksDialog.visible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="selectMatterConfirm"
              >确 定</el-button
            >
          </el-row>
        </el-row>
      </el-row>
    </el-dialog>

    <!-- 添加问题 -->
    <el-dialog
      :title="questionDialog.title"
      :visible.sync="questionDialog.visible"
      width="50%"
    >
      <el-form
        :model="classifyform"
        :label-width="formLabelWidth"
        :rules="classifyRules"
        ref="classifyform"
      >
        <el-row v-if="parentClassifyName != null">
          <el-form-item
            prop="parentClassifyName"
            :label="questionDialog.parentLabel"
          >
            <el-input v-model.trim="parentClassifyName" disabled></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item prop="classifyName" :label="questionDialog.label">
            <el-input v-model.trim="classifyform.classifyName"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="name" label="温馨提示">
            <el-input v-model.trim="classifyform.sortRemarks"></el-input>
          </el-form-item>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="questionDialog.visible = false">取 消</el-button>

        <el-button type="primary" @click="submitClassifyForm">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 关联事项 -->
    <el-dialog
      :title="matterDialog.title"
      :visible.sync="matterDialog.visible"
      width="80%"
    >
      <mu-list>
        <mu-list-item
          v-for="(item, index) in mattersList"
          :key="index"
          button
          :ripple="false"
          @click="selectList(item.id)"
        >
          <mu-list-item-action>
            <mu-checkbox v-model="selects" :value="item.id + ''"></mu-checkbox>
          </mu-list-item-action>
          <mu-list-item-title> {{ item.matterName }} </mu-list-item-title>
        </mu-list-item>
      </mu-list>

      <!-- <mu-select label="关联事项选择" multiple  v-model="selects" full-width>
        <mu-option v-for="item,index in mattersList" :key="index" :label="item.matterName|ellipsis2" :value="item.id"></mu-option>
      </mu-select> -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="matterDialog.visible = false">取 消</el-button>

        <el-button type="primary" @click="submitMatterForm">保 存</el-button>
      </span>
    </el-dialog>

    <el-row gutter="20">
      <el-col :span="6" class="el-row-filter">
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="个人服务" name="1">
            <el-row :span="24" style="height: 40px">
              <el-button @click="addTopic(1)" icon="el-icon-plus" size="mini"
                >添加主题</el-button
              >
            </el-row>
            <div id="dataPage" style="height: 100%" class="mytree">
              <el-tree
                size="mini"
                v-loading="loading"
                ref="categoryTree"
                id="el-tree"
                :data="data"
                node-key="id"
                indent="0"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
                :props="treeProps"
                :load="loadNode"
                :render-content="renderContent"
                highlight-current
              >
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="企业服务" name="2">
            <el-row :span="24" style="height: 40px">
              <el-button @click="addTopic(2)" icon="el-icon-plus" size="mini"
                >添加主题</el-button
              >
            </el-row>

            <div id="dataPage1" style="height: 100%" class="mytree">
              <el-tree
                size="mini"
                v-loading="loading"
                ref="categoryTree"
                id="el-tree"
                :data="data"
                node-key="id"
                indent="0"
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
                :props="treeProps"
                :load="loadNode"
                :render-content="renderContent"
                highlight-current
              >
              </el-tree>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <!--添加问题 -->
      <el-col :span="18">
        <el-row style="margin-bottom: 5px">
          <el-button
            v-if="tempClassifyId != null"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddQuestion"
          >
            添加问题</el-button
          >
          <!--todo -->
          <!-- <el-button
            v-if="tempClassifyId != null"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddQuestion"
          >
            申请条件</el-button
          >

          <el-button
            v-if="tempClassifyId != null"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddQuestion"
          >
            办理流程</el-button
          >

          <el-button
            v-if="tempClassifyId != null"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddQuestion"
          >
            基本信息</el-button
          > -->
        </el-row>

        <div>
          <el-table
            ref="table"
            size="mini"
            v-loading="loading"
            row-key="id"
            :data="questionTableData"
            @row-click="clickTableRow"
            border
            highlight-current-row
            lazy
            :load="tableLoadData"
            :tree-props="treeTableProps"
          >
            <el-table-column prop="classifyName" label="问题/答案">
              <template slot-scope="scope">
                <span v-if="scope.row.isAns == 0">问：</span>
                <span v-else>答：</span>
                <span>{{ scope.row.classifyName }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="matterNames" label="事项名称">
              <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  <el-row
                    style="margin-bottom: 5px"
                    :key="index"
                    v-for="(item, index) in scope.row.matterNameList"
                  >
                    <el-tooltip effect="light" :content="item" placement="top">
                      <el-tag size="medium">{{ item | ellipsis2 }}</el-tag>
                    </el-tooltip>
                  </el-row>
                </div>
              </template>
            </el-table-column>

            <el-table-column width="240" fixed="right" label="操作">
              <template slot-scope="scope">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-button
                      size="mini"
                      type="text"
                      @click="handleSubQuestion(scope.$index, scope.row)"
                      >添加子集</el-button
                    >
                  </el-col>
                  <el-col :span="6">
                    <el-button
                      type="text"
                      size="mini"
                      :disabled="scope.row.isLeaf === 0||scope.row.isAns===0"
                      @click="handleMater(scope.$index, scope.row)"
                      >关联事项</el-button
                    >
                  </el-col>
                  <el-col :span="6">
                    <el-button
                      type="text"
                      size="mini"
                      @click="handleEditQuestion(scope.$index, scope.row)"
                      >编辑</el-button
                    >
                  </el-col>

                  <el-col :span="6">
                    <el-button
                      type="text"
                      size="mini"
                      @click="handleQuestionDel(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-row>
          <!-- 分页器 -->
          <div class="table-foot" v-if="questionTableData.length > 0">
            <Pagination
              :total="tableData.pageInfo.totalResult"
              :prePageResult="tableData.pageInfo.prePageResult"
            />
          </div>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>



<script>
import Pagination from "@/components/Pagination.vue";
import table from "@/assets/mixins/table";
//import Form from "../../../components/Form.vue";

//import topicClassify from "./topicClassify.vue";

export default {
  components: {
    Pagination,
   // topicClassify
  },
  name: "topic",
  mixins: [table],

  created() {
    //
    this.getTopicList(1);

    //初始化事项列表
    let query = {};
    this.getMatterList(query);
  },
  methods: {
    selectList(val) {
      //如果有 就删除，否则添加\
      let index = this.selects.indexOf(val + "");

      if (index != -1) {
        //存在 删除
        this.selects.splice(index, 1);
      } else {
        this.selects.push(val + "");
      }
    },

    handleTabClick(tab, event) {
      this.getTopicList(tab.name);
      //console.log(tab, event);
    },
    //弹窗事项列表搜索事件-查询
    matterSearchConfirm() {
      this.getMatterList({});
    },
    //弹窗事项列表搜索事件-清空
    matterSearchClear() {
      this.searchform = {};
    },

    handleSelectionChange(val) {
      //判断是否选中
      console.log("selected", val);

      //获取当前列表未选中行，与tags比较 如果有 则删除tags中的行

      // this.multipleSelection = val;
    },

    handleSizeChange(currSize) {
      console.log("currSize=" + currSize);
      this.matterPageInfo.prePageResult = currSize;
      this.getMatterList(this.searchform);
    },
    handleCurrentChange(currPage) {
      console.log("currPage=" + currPage);
      this.matterPageInfo.currPage = currPage;
      this.getMatterList(this.searchform);
    },

    handleSubQuestion(index, row) {
      console.log("添加子集", row);
      //判断当前节点是否有关联事项，如果有，添加成功后会清除关联的事项
      if (row.matterIds && row.matterIds.length > 0) {
        //提示框
        this.$confirm("当前节点包含关联事项，添加子集后将取消关联", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          //todo 更新父节点事项关联信息

          this.initForm();
          this.classifyform.parentId = row.id;
          this.classifyform.classifyLevel = row.classifyLevel + 1;
          this.parentClassifyName = row.classifyName;
          this.questionDialog.visible = true;
          this.questionDialog.title = "添加子集问题";
        });
      } else {
        this.initForm();
        this.classifyform.parentId = row.id;
        this.parentClassifyName = row.classifyName;
        this.classifyform.classifyLevel = row.classifyLevel + 1;
        this.questionDialog.visible = true;
        this.questionDialog.title = "添加子集问题";
      }

      if (row.isAns == 0) {
        this.questionDialog.label = "答案选项";

        this.questionDialog.parentLabel = "问题";
      } else {
        this.questionDialog.label = "问题";

        this.questionDialog.parentLabel = "答案选项";
      }
    },

    handleMater(index, row) {
      console.log("关联事项", row);
      if (row.isLeaf == 0) {
        this.$message.warn("当前问题非终节点，不能关联事项！");
        return;
      }
      this.editRow = row;
      this.initForm();
      this.selects = row.matterIds.split(",").filter((i) => i && i.trim());
      this.classifyform = Object.assign({}, this.classifyform, row);
      this.loading = true;
      this.$post("/one/classify/topical/list", {
        "query.classifyId": this.rootClassifyId,
        "pageInfo.prePageResult": "-1",
      }).then(({ data }) => {
        if (data.result.length > 0) {
          let matterIds = data.result[0].matterId;
          this.$post("/matter/list", {
            "query.idList": matterIds.split(","),
            "pageInfo.prePageResult": "-1",
          }).then(({ data }) => {
            this.mattersList = data.result;
            this.matterDialog.visible = true;
            this.matterDialog.title = "关联事项";
            this.loading = false;
            console.log("selects", this.selects);
          });
        }
      });

      //查询当前问题可选事项
    },

    handleEditQuestion(index, row) {
      console.log("编辑问题", row);
      this.editRow = row;
      this.classifyform = Object.assign({}, this.classifyform, row);
      this.$post("/one/classify/view", {
        id: [row.parentId],
      }).then(({ data }) => {
        this.parentClassifyName = data.entity.classifyName;
        this.questionDialog.visible = true;
        this.questionDialog.title = "编辑问题";
      });
    },

    handleQuestionDel(index, row) {
      console.log("删除问题");
      //级联删除，
      console.log("handleQuestionDel", row);
      let title = "此操作将删除问答及其子问题, 是否继续?";
      let url = "/one/classify/logicDelete";

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          this.$post(url, {
            entity: { id: row.id },
          })
            .then((res) => {
              if (res && res.code && res.code == 1) {
                //this.getClassifyList();
                this.deleteLazyTableItem(row);
                this.loading = false;
                this.$message.success("问题删除成功！");
              }
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除!",
          });
        });
    },

    deleteLazyTableItem(item) {
      const store = this.$refs.table.store;
      console.log("store", store);
      if (item.parentId != null) {
        let parentRow = store.states.data.find(
          (child) => child.id == item.parentId
        );
        if (!parentRow) {
          const keys = Object.keys(store.states.lazyTreeNodeMap);
          for (let i = 0; i < keys.length; i++) {
            parentRow = store.states.lazyTreeNodeMap[keys[i]].find(
              (child) => child.id == item.parentId
            );
            if (parentRow) {
              break;
            }
          }
        }

        console.log("parentRow", parentRow);

        if (!parentRow) {
          const parent = store.states.data;
          console.log("未找到指定父节点行,data,id",parent,item.id);
          const index = parent.findIndex((child) => child.id == item.id);
          parent.splice(index, 1);
        } else {
          const parent = store.states.lazyTreeNodeMap[item.parentId];
          const index = parent.findIndex((child) => child.id == item.id);
          parent.splice(index, 1);
        }
      } else {
        const parent = store.states.data;
        const index = parent.findIndex((child) => child.id == item.id);
        parent.splice(index, 1);
      }
    },
    //新增主题
    addTopic(val) {
      console.log("addTopic");
      this.initForm();
      if (val == 2) {
        this.topicform.topicalType = 2;
        this.topicDialog.title = "新增企业主题";
      }
      this.topicDialog.visible = true;
    },
    tableLoadData(tree, treeNode, resolve) {
      console.log("treeNode", treeNode);
      this.$post("/one/classify/list", {
        "query.parentId": tree.id,
        "pageInfo.prePageResult": "-1",
      }).then(({ data }) => {
        resolve(data.result);
      });
    },
    getTopicList(type) {
      this.$post("/one/topical/getTopicList", {
        "query.topicalType": type,
      }).then(({ data }) => {
        this.data = data;
      });
    },

    getMatterList(query) {
      query["pageInfo.currPage"] = this.matterPageInfo.currPage;
      query["pageInfo.prePageResult"] = this.matterPageInfo.prePageResult;

      //弹窗材料列表搜索条件name
      if (this.searchform.matterName) {
        query["query.matterName"] = "%" + this.searchform.matterName + "%";
      }

      this.loading = true;

      this.$post("/matter/list", query).then((res) => {
        if (res && res.code && res.code == 1) {
          this.loading = false;
          this.matterPageInfoData = res.data.result;
          this.matterPageInfo.currPage = res.data.pageInfo.currPage;
          this.matterPageInfo.prePageResult = res.data.pageInfo.prePageResult;
          this.matterPageInfo.totalResult = res.data.pageInfo.totalResult;
        }
      });
    },

    matterBatchAdd() {
      console.log("matterBatchAdd", this.$refs.multipleTable);

      this.$refs.multipleTable.data.map((item) => this.matterTags.push(item));
      this.matterTags = this.unique(this.matterTags, "id");
    },

    handleAdd(index, row) {
      this.matterTags.push(row);
      this.matterTags = this.unique(this.matterTags, "id");
    },

    handleClose(tag) {
      let tmpArrs = [];
      for (let item of this.matterTags) {
        if (item.id === tag) {
          continue;
        }
        tmpArrs.push(item);
      }
      this.matterTags = tmpArrs;
    },

    unique(arr, attr) {
      const res = new Map();
      return arr.filter((item) => {
        var attrItem = item[attr];
        return !res.has(attrItem) && res.set(attrItem, 1);
      });
    },

    handleNodeClick(data) {
      console.log("handleNodeClick", data);
      if (data.type == 1) {
        this.tempClassifyId = data.classifyId;
        this.tempTopicPackName = data.name;
        console.log(this.tempClassifyId);
        this.getClassifyList(data.classifyId);
      }
    },

    getClassifyList(id) {
      this.loading = true;
      this.$post("/one/classify/list", {
        "query.parentId": id,
      })
        .then((res) => {
          this.tableData.pageInfo = res.data.pageInfo;
          this.questionTableData = res.data.result;
          this.classifyform.parentId = id;
          this.loading = false;

          this.rootClassifyId = id;
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },

    handleAddQuestion() {
      this.initForm();
      this.parentClassifyName = null;
      this.classifyform.parentId = this.tempClassifyId;
      this.classifyform.classifyLevel = 2;
      this.questionDialog.title = "添加问题";
      this.questionDialog.label = "问题";

      this.questionDialog.parentLabel = "主题包名称";

      this.parentClassifyName = this.tempTopicPackName;
      this.questionDialog.visible = true;
    },

    renderContent: function (h, { node, data, store }) {
      let addTopicPack = (
        <el-link
          style="margin-right:5px;margin-left:5px"
          icon="el-icon-plus"
          onClick={() => {
            this.handleAddTopicPacks(data);
          }}
        ></el-link>
      );

      if (data.type == 1) {
        addTopicPack = "";
      }

      return (
        <span class="custom-tree-node">
          <span style="padding-left: 2px;font-size:14px">
            {" "}
            <i style="font-size:16px;color:#409EFF" class={data.icon}></i>{" "}
            {node.label}
          </span>
          <span style="flex">
            {addTopicPack}

            <el-link
              style="margin-right:5px;margin-left:5px"
              icon="el-icon-edit"
              onClick={() => {
                this.handleEditTopic(data);
              }}
            ></el-link>
            <el-link
              style="margin-right:5px;margin-left:5px"
              icon="el-icon-delete"
              onClick={() => {
                this.handleDeleteTopic(data);
              }}
            ></el-link>

            <el-link
              style="margin-right:5px;margin-left:5px"
              icon="el-icon-sort-up"
              onClick={() => {
                this.handleUpTopic(data);
              }}
            ></el-link>

            <el-link
              style="margin-right:5px;margin-left:5px"
              icon="el-icon-sort-down"
              onClick={() => {
                this.handleDownTopic(data);
              }}
            ></el-link>
          </span>
        </span>
      );
    },

    handleAddTopicPacks(data) {
      console.log("handleAddTopicPacks", data);
      this.initForm();

      //初始化
      this.matterPageInfoData = [];
      this.matterTags = [];

      this.matterSearchClear();
      this.initMatterPage();

      this.getMatterList({});

      this.topicPacksform.topicalId = data.id;
      this.topicPacksDialog.visible = true;
    },

    handleEditTopic(data) {
      console.log("handleEditTopic", data);

      if (data.type == 1) {
        this.initForm();
        this.loading = true;
        this.$post("/one/classify/topical/edit", {
          id: [data.id],
        })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              //获取实现关联包
              this.$post("/matter/list", {
                "query.idList": res.data.entity.matterId.split(","),
                "pageInfo.prePageResult": "-1",
              })
                .then((res) => {
                  if (res && res.code && res.code == 1) {
                    //初始化关联事项
                    this.matterTags = [];
                    res.data.result.map((item) => this.matterTags.push(item));
                    //获取主题包名次
                    this.loading = false;
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });
              //获取主题包名称
              this.$post("/one/classify/edit", {
                id: [data.classifyId],
              })
                .then((res) => {
                  if (res && res.code && res.code == 1) {
                    //获取主题包名次
                    this.loading = false;

                    Object.assign(this.classifyform, res.data.entity);
                    this.topicPacksDialog.title = "编辑主题包";
                    this.topicPacksDialog.visible = true;
                  }
                })
                .catch((error) => {
                  this.$message.error(error.message);
                });

              this.loading = false;
              console.log(res);
              Object.assign(this.topicPacksform, res.data.entity);
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      } else if (data.type == 0) {
        this.initForm();
        this.loading = true;
        this.$post("/one/topical/edit", {
          id: [data.id],
        })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              this.loading = false;
              Object.assign(this.topicform, res.data.entity);
              this.topicDialog.title = "编辑主题";
              this.topicDialog.visible = true;
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      }
    },

    handleDeleteTopic(data) {
      console.log("handleDeleteTopic", data);
      let title = "此操作将删除主题及其相关主题包与问答, 是否继续?";
      let url = "/one/topical/logicDelete";
      if (data.type == 1) {
        title = "此操作将删除该主题包关联问答, 是否继续?";
        url = "/one/classify/topical/logicDelete";
      }

      this.$confirm(title, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.$post(url, {
          entity: { id: data.id },
        })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              this.getTopicList(this.activeName);
              this.loading = false;
              this.questionTableData = [];
              this.$message.success("主题删除成功！");
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      });
    },

    handleUpTopic(data) {
      let type = 0;
      let url = "/one/topical/upOrDownTopicList";
      if (data.type == 1) {
        url = "/one/classify/topical/upOrDownTopicList";
      }
      this.switchSort(url, data.id, type);
    },

    handleDownTopic(data) {
      let type = 1;
      let url = "/one/topical/upOrDownTopicList";
      if (data.type == 1) {
        url = "/one/classify/topical/upOrDownTopicList";
      }
      this.switchSort(url, data.id, type);
    },

    switchSort(url, id, type) {
      this.loading = true;
      this.$post(url, {
        id: id,
        type: type,
      })
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.getTopicList(this.activeName);
            this.loading = false;

            this.$message.success("更新排序成功！");
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.message);
        });
    },

    async selectMatterConfirm() {
      //清空物料选择弹窗搜索条件
      this.searchform = {};
      this.topicPacksDialog.visible = false;
      this.matterCurTableData = this.matterTags;
      let ids = this.matterTags.map((i) => i.id);
      this.topicPacksform.matterId = ids.join(",");
      this.loading = true;
      this.$post("/one/classify/save", {
        entity: this.classifyform,
      })
        .then((res) => {
          this.loading = false;
          if (res && res.code && res.code == 1) {
            this.topicPacksform.classifyId = res.data.id;
            this.submitTopicPackForm();
            this.matterTags = [];
            this.matterCurTableData = [];
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.message);
        });
    },
    //提交关联数据数据
    submitMatterForm() {
      this.classifyform.matterIds = this.selects.join(",");
      this.submitClassifyForm();

      this.matterDialog.visible = false;
    },

    // 提交表单
    submitTopicForm(ref) {
      this.loading = true;
      const el = this.$refs.topicform;
      el.validate((valid) => {
        if (!valid) return;
        this.$post("/one/topical/save", {
          entity: this.topicform,
        })
          .then((res) => {
            this.loading = false;
            if (res && res.code && res.code == 1) {
              this.initForm();
              this.topicDialog.visible = false;
              this.getTopicList(this.activeName);
            }
          })
          .catch((error) => {
            this.loading = false;
            this.$message.error(error.message);
          });
      });
    },

    // 提交主题包表单
    submitTopicPackForm(ref) {
      this.loading = true;
      const el = this.$refs.topicPacksform;
      el.validate((valid) => {
        if (!valid) return;
        this.$post("/one/classify/topical/save", {
          entity: this.topicPacksform,
        })
          .then((res) => {
            this.loading = false;
            if (res && res.code && res.code == 1) {
              this.initForm();
              this.topicPacksDialog.visible = false;
              this.getTopicList(this.activeName);
            }
          })
          .catch((error) => {
            this.loading = false;
            this.$message.error(error.message);
          });
      });
    },

    // 提交问题表单
    submitClassifyForm(ref) {
      this.loading = true;
      this.$post("/one/classify/save", {
        entity: this.classifyform,
      })
        .then((res) => {
          this.loading = false;
          if (res && res.code && res.code == 1) {
            if (res.data["__mortals_form_state__"] == "EDIT") {
              console.log("编辑");
              //编辑
              this.handleEditOnSave(res.data.entity);
            } else {
              //判断编辑或者新增
              this.handleAddOnSave(res.data.entity);
            }

            this.initForm();
            this.classifyform.parentId = this.tempClassifyId;
            // this.getClassifyList(this.tempClassifyId);
            this.questionDialog.visible = false;
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error(error.message);
        });
    },

    handleEditOnSave(model) {
      console.log(model);

      const newItemData = Object.assign({}, model);

      //更新当前行数据
      // 未编辑父级节点，更新当前数据
      // Object.assign(this.editRow, newItemData, {
      //   hasChildren: false,
      // });

      //删除当前节点。再添加当前节点

      this.deleteLazyTableItem(this.editRow);

      this.findNewParent(model.parentId, newItemData);

      // const store = this.$refs.table.store;
      // // 首先在最外层里面找
      // let curRow = store.states.data.find((item) =>item.id === model.id);
      // if (curRow) {
      //   Object.assign(curRow, model);
      // } else {
      //   const keys = Object.keys(store.states.lazyTreeNodeMap);
      //   for (let i = 0; i < keys.length; i++) {
      //     curRow = store.states.lazyTreeNodeMap[keys[i]].find(
      //       (item) => item.id == model.id
      //     );
      //     if (curRow) {
      //       break;
      //     }
      //   }
      //   if (curRow) {
      //     Object.assign(curRow, newItemData);
      //     console.log("curRow", curRow);

      //   }
      // }
    },

    //model 为行数据
    handleAddOnSave(model) {
      const newItemData = Object.assign({}, model);
      const parentId = model.parentId;

      if (parentId == this.tempClassifyId) {
        // 添加最外层
        this.addOuterTableItem(newItemData);
      } else {
        this.findNewParent(parentId, newItemData);
      }
    },

    findNewParent(parentId, newItemData) {
      const store = this.$refs.table.store;
      // 首先在最外层里面找
      let parentRow = store.states.data.find((item) => item.id === parentId);
      if (parentRow) {
        parentRow.hasChildren = true;
      }
      // 不在最外层
      else {
        const keys = Object.keys(store.states.lazyTreeNodeMap);
        for (let i = 0; i < keys.length; i++) {
          parentRow = store.states.lazyTreeNodeMap[keys[i]].find(
            (item) => item.id == parentId
          );
          if (parentRow) {
            break;
          }
        }
        if (parentRow) {
          console.log("parentRow", parentRow);
          parentRow.hasChildren = true;
          parentRow.isLeaf = 0;
        }
      }
      const parentTreeNode = store.states.treeData[parentId];
      console.log("parentTreeNode", parentTreeNode);
      this.addLazyTableItemToParent(parentTreeNode, parentId, newItemData);
    },

    // 添加数据放到最外层的数据中去
    addOuterTableItem(newItemData) {
      const store = this.$refs.table.store;
      store.states.data.push(newItemData);
    },

    // 把数据加到父级节点上去
    addLazyTableItemToParent(parentTreeNode, parentId, newItemData) {
      const store = this.$refs.table.store;
      // 如果在已加载过的节点的子节点中
      if (parentTreeNode) {
        // 如果该节点已加载
        if (parentTreeNode.loaded) {
          store.states.lazyTreeNodeMap[parentId].push(newItemData);
        }
      } else {
        console.log("new");
        store.states.treeData[parentId] = {
          display: true,
          loading: false,
          loaded: false,
          expanded: false,
          children: [],
          lazy: true,
          level: newItemData.classifyLevel,
        };
      }
    },

    async loadNode(node, resolve) {
      console.log("node:", node);

      if (node.level === 0) {
        //初始化数据
        resolve(this.data);
        return;
      }
    },
    // table的左键点击当前行事件
    clickTableRow(row, column, event) {
      console.log("clickTableRow row", row);
      this.tableRowData = row;
    },

    initForm() {
      this.topicform = {
        id: null,
        topicalName: "",
        topicalRank: 1,
        deleted: 0,
        siteId: 0,
        topicalType: 1,
      };

      this.topicPacksform = {
        id: null,
        topicalId: null,
        classifyId: null,
        moveIcon: "",
        classifyRank: 0,
        overWay: "1",
        overTime: "1天",
        siteId: 0,
        matterId: "",
        presenceNum: 0,
        deleted: 0,
      };
      this.classifyform = {
        id: null,
        classifyName: "",
        tName: "",
        classifyLevel: 1,
        businessId: "",
        matterIds: "",
        sortRemarks: "",
        siteId: 0,
        isLeaf: 1,
        isAns: 0,
        deleted: 0,
      };
    },

    initMatterPage() {
      this.matterPageInfo = {
        totalResult: 0,
        prePageResult: 10,
        currPage: 1,
      };
    },
  },
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 50) {
        return value.slice(0, 50) + "...";
      }
      return value;
    },
    ellipsis2(value) {
      if (!value) return "";
      if (value.length > 30) {
        return value.slice(0, 30) + "...";
      }
      return value;
    },
  },

  data() {
    return {
      tempTopicPackName: "",
      editRow: {},
      selects: [],
      rootClassifyId: null,
      tempClassifyId: null,
      parentClassifyName: null,
      activeName: "1",
      loading: false,
      topicDialog: {
        visible: false,
        title: "新增主题",
      },
      topicPacksDialog: {
        visible: false,
        title: "新增主题包",
      },
      questionDialog: {
        visible: false,
        title: "新增问题项",
      },

      matterDialog: {
        visible: false,
        title: "关联事项",
      },

      topicform: {
        topicalName: "",
      },

      topicPacksform: {},
      matterTags: [],
      matterCurTableData: [],
      mattersList: [],
      matterPageInfoData: [],
      searchform: { tname: "" },
      matterPageInfo: {
        totalResult: 0,
        prePageResult: 10,
        currPage: 1,
      },
      questionform: {},
      formLabelWidth: "120px",
      formInputWidth: "20",
      radio: null,
      questionTableData: [],
      currentRowIndex: 0, // 获取当前右键点击的table行下标
      data: [],
      fileList3: [],
      classifyform: {},
      treeProps: {
        children: "children",
        label: "name",
        isLeaf: "isLeaf",
        type: "type",
        icon: "icon",
        id: "id",
        classifyId: "classifyId",
      },
      treeTableProps: { children: "children", hasChildren: "hasChildren" },
      submitButtonDisabled: false,
      isChildDir: false, //刷新标志
      isShowDrop: false, //右键菜单的是否显示
      contextMenuTarget: null, //右键菜单的DOM对象
      thisformdata: {}, //右键菜单的点击的节点对象
      targetElement: {}, //右键点击的目标对象
      isShowSearch: false,
      tableRowData: {},
      topicRules: {
        topicalName: [
          {
            required: true,
            message: "请输入类目名称",
            trigger: "blur",
          },
        ],
      },

      attRules: {
        attachType: [
          {
            required: true,
            message: "请选择附件类型",
            trigger: "blur",
          },
        ],
        attachUrl: [
          {
            required: true,
            message: "请上传附件",
            trigger: "blur",
          },
        ],
      },

      supplyRules: {
        supplierId: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "blur",
          },
        ],
        deliveryPeriod: [
          {
            required: true,
            message: "请输入交货期",
            trigger: "blur",
          },
        ],
        deliveryPeriodUnit: [
          {
            required: true,
            message: "请交货期单位",
            trigger: "blur",
          },
        ],

        unitOfMeasure: [
          {
            required: true,
            message: "请选择计量单位",
            trigger: "blur",
          },
        ],

        costPlan: [
          {
            required: true,
            message: "请输入供货成本",
            trigger: "blur",
          },
        ],
      },
    };
  },
};
</script>
<style>
.winClass {
  width: 500px;
  height: 200px;
  overflow-y: auto;
}
/* el-divider 修改高度&虚线效果 */
.el-divider--horizontal {
  margin: 5px 0;
  background: 0 0;
  border-top: 1px solid #e8eaec;
}
.el-row-filter {
  max-height: 768px;
  height: 600px;
  overflow: auto;
}
.table-foot {
  width: 100%;
  overflow: auto;
}

#dataPage {
  margin: 0 0;
  font-family: "Microsoft Yahei", "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  height: 100%;
}

.el-scrollbar .el-scrollbar__wrap .el-scrollbar__view {
  overflow-y: hidden;
  overflow-x: hidden;
}
.el-radio__label {
  display: none !important;
}
</style>


<style lang="scss" scoped>
.el-row {
  margin-bottom: 5px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-select {
  width: 130px;
}

.mytree ::v-deep {
  .el-tree--highlight-current
    ::v-deep
    .el-tree-node.is-checked
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }
  .el-tree--highlight-current
    ::v-deep
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: rgb(255, 255, 255);
    color: rgb(64, 158, 255);
  }
  .el-tree > .el-tree-node:after {
    border-top: none;
  }
  .el-tree-node {
    position: relative;
    padding-left: 16px;
  }
  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  // .el-tree-node__expand-icon.is-leaf {
  //   display: none;
  // }
  .el-tree-node__children {
    padding-left: 16px;
  }

  .el-tree-node :last-child:before {
    height: 38px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #4386c6;
    bottom: 0px;
    height: 100%;
    top: -26px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #4386c6;
    height: 20px;
    top: 12px;
    width: 24px;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding-right: 8px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
