<template>
  <div class="menu-wrap" v-loading="menuLoading">
    <transition name="fade-transform">
      <div :class="['tree-wrap', level === 2 && 'tree-wrap2']" v-show="isCollapse">
        <template v-if="level === 1">
          <div class="add-areas approve" v-if="isBuShi">
            <!-- <i class="el-icon-refresh"></i> -->
            <span class="text">待审批区域</span>
            <span class="num" @click="goToApprove">{{approveCount}}</span>
          </div>
          <div class="panel-box" :class="!isBuShi?'notBuShiClass':''">
            <div :class="['add-areas','add-areas-spec', 'add-areas-red', !isHead && 'disabled-btn']" @click="showAddAreaModal">
              <i class="el-icon-circle-plus-outline"></i>
              <span>新建区域类型</span>
            </div>
            <div :class="['add-areas', 'add-areas-spec', !isHead && 'disabled-btn']" @click="goToApprove" v-if="isBuShi">
              <i class="el-icon-coordinate"></i>
              <span>跳转审批中心</span>
            </div>
          </div>
          <div class="areas-num">共{{ areasNum }}个区域类型</div>
        </template>
        <template v-else>
          <div class="areas-back" @click="goBack">
            <i class="el-icon-arrow-left"></i>返回主页
          </div>
        </template>
        <el-tree
          :data="treeData"
          node-key="id"
          default-expand-all
          :highlight-current="true"
          :expand-on-click-node="false"
          :current-node-key="currentId"
          @node-click="handleNodeClick"
          class="tree-box"
          :class="level == 2?'my-tree-box':''"
          ref="tree"
        >
          <span
            class="custom-tree-node"
            slot-scope="{ node, data }"
            v-if="level === 1"
          >
            <span class="tree-title-box">
              <span class="tree-title" :style="{color: node.disabled? 'red' : 'black'}">{{ node.label }}</span>
              <!-- <i class="el-icon-view"></i> -->
            </span>
            <span class="tree-title-setting" v-if="currentId === data.id">
              <el-button type="text" @click.stop="reNameArea(data)" :disabled="!isHead">修改</el-button>
              <el-popconfirm
                title="确定删除吗？"
                icon="el-icon-info"
                iconColor="red"
                @confirm="removeArea(data)"
              >
                <el-button slot="reference" :disabled="!isHead" :style="{color: isHead ? '#2094ff' : '#C0C4CC', fontSize: '12px'}" type="text">删除</el-button>
              </el-popconfirm>
              <span @click.stop="lookAreas(data)">开始绘制</span>
            </span>
          </span>
          <span class="custom-tree-node" slot-scope="{ node, data }" v-else>
            <span class="tree-title-box">
              <span class="tree-title" :class="node.level == 2?'my-tree-title':'my-tree-title2'">
                <span class="title-left">{{ node.label }}</span>
                <span class="title-right" v-if="node.level === 2 && data.auditStatus == '0' && isBuShi">审批中</span>
              </span>
              <i class="el-icon-refresh look-list look-list2" v-if="data.level === 1" @click.self.stop="refreshList"></i>
              <span class="look-list" v-if="data.level === 1" @click.self.stop="gotoList">查看列表</span>
            </span>
          </span>
        </el-tree>
        <el-pagination
            @current-change="handleCurrentChange"
            layout="->,total,prev,next"
            :total="total"
            :current-page="pageNum"
            class="pagi-box-quyu"
            v-if="this.level == 2"
        ></el-pagination>
      </div>
    </transition>
    <el-dialog
      :title="modalTitle"
      :visible.sync="visible"
      width="600px"
      append-to-body
      top="30vh !important"
      custom-class="area-dialog"
    >
      <div class="select-cnt">
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="form"
          label-width="90px"
        >
          <el-form-item label="类型名称" prop="layerName">
            <el-input v-model="addForm.layerName" clearable />
          </el-form-item>
          <el-form-item label="类型颜色" prop="layerColor">
            <el-color-picker v-model="addForm.layerColor" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel('form')">取 消</el-button>
        <el-button type="primary" @click="onOk('form')">{{ this.modalType === "ADD" ? '创 建' : '修 改' }}</el-button>
      </div>
    </el-dialog>
    <menulist-modal
      :drawer="drawerShow"
      @close="close"
      @draw-polygon="data => $emit('draw-polygon', data)"
      @set-form="data => $emit('set-form', data)"
      @refreshApprove="getWaitApproveCount"
      :layerId="layerId"
      v-if="drawerShow"
    />
  </div>
</template>
<script>
import MenulistModal from "./menulist-modal.vue";
import { mapGetters } from 'vuex'
import {
  addAreas,
  updateAreas,
  removeAreas,
  getDrawCountApi
} from "@/api/grid/draw-area";
export default {
  name: "MenuEdit",
  props: ['isCollapse'],
  data() {
    return {
      menuLoading: false,
      visible: false, // 显示新建特色区域弹窗
      addForm: {
        layerName: "",
        layerColor: "#2094ff",
      },
      currentId: null,
      modalTitle: null,
      modalType: null,
      addRules: {
        layerName: [
          {
            required: true,
            message: "请输入区域类型名称",
            trigger: "blur",
          },
          {
            max: 20,
            message: "长度在20个字符以内",
            trigger: "blur",
          },
        ],
        layerColor: [
          {
            required: true,
            message: "请选择颜色",
            trigger: "blur",
          },
        ],
      },
      shapeList: [], // 图形列表
      drawerShow: false,
      perInfo: {},
      pageNum:1,
      total:0,
      approveCount:0,
      layerId:'',
      currentLayerInfo:{},
    };
  },
  components: {
    MenulistModal
  },
  computed: {
    ...mapGetters(['roles']),
    areasNum() {
      const { layerData } = this.$store.state.featuredAreas;
      return layerData.length;
    },
    treeData() {
      const { level, layerData, shapeList } = this.$store.state.featuredAreas;
      return level === 1 ? layerData : shapeList;
    },
    level() {
      const { level } = this.$store.state.featuredAreas;
      return level;
    },
    isDrawing() {
      const { isDrawing } = this.$store.state.featuredAreas;
      return isDrawing;
    },
    isHead() {
      return this.roles.includes('admin') || this.roles.includes('headAdmin') || this.roles.includes('headOps') || this.roles.includes('headPublic') || this.roles.includes('headPrivate')
    },
    isBuShi() {
      return this.roles.includes('headOps') || this.roles.includes('headPublic') || this.roles.includes('headPrivate')
    },
  },
  mounted() {
    this.getWaitApproveCount();
    const {layerInfo} = this.$store.state.featuredAreas;
    console.log(layerInfo,'layerInfo')
    if(layerInfo?.layerId){
      this.queryMenu(layerInfo);
    }else{
      this.queryMenu();
    }
  },
  beforeDestroy() {},
  methods: {
    refreshList(){
      if(this.currentLayerInfo?.layerId){
        this.pageNum = 1;
        this.lookAreas({
          ...this.currentLayerInfo,
          pageNum:1,
          shapeId:'',
        });
      }
    },
    // 获取待审批数量
    getWaitApproveCount(){
      if(this.level == 2){
        this.refreshList();
      }
      getDrawCountApi().then(res=>{
        if(res.code == 200){
          this.approveCount = res.data;
        }
      })
    },
    // 前往审批中心
    goToApprove() {
      if (!this.isHead) return;
      this.$router.push({
        path:'/workbench/approveCenter'
      })
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.lookAreas({
        ...this.currentLayerInfo,
        pageNum:this.pageNum,
        shapeId:'',
      });
    },
    // 获取特色区域
    async queryMenu(layerInfo) {
      this.menuLoading = true;
      if(layerInfo?.layerId){
        this.$emit('getLoading',true)
      }
      this.$store.dispatch("queryMenu").then(() => {
        const {layerData} = this.$store.state.featuredAreas;
        if(layerInfo?.layerId){
          console.log('11111')
          const data = layerData.filter(item=>item.layerId == layerInfo.layerId);
          let color = data[0]?.layerColor || '#222'
          this.lookAreas({...layerInfo,color},'shapeInfo');
        }
        this.menuLoading = false;
      });
    },
    /**
     * 树节点被点击事件
     */
    handleNodeClick(data, node, self) {
      // console.log(data,'dadadadadaad')
      if (this.isDrawing) {
          this.$message({
            type: "info",
            message: "请先完成图形绘制",
          });
        return;
      }
      this.currentId = data.id;
      this.$refs.tree.setCurrentKey(data.id);
      this.addForm = {};
      // console.log(this.level)
      if (this.level === 2 && data.level !== 1) {
        this.$emit('draw-polygon', [data], true);
      }
      if (data.level === 1) {
        const { shapeList } = this.$store.state.featuredAreas;
        this.$emit('draw-polygon', shapeList[0].children);
      }
      if (this.level === 1){
        this.$emit("set-info", data);
        this.$emit('draw-polygon', []);
      }
    },
    /**
     * 显示新建特色区域弹窗
     */
    showAddAreaModal() {
      if (!this.isHead) return;
      this.modalTitle = "新建区域类型";
      this.modalType = "ADD";
      this.visible = true;
    },
    /**
     * 确定新建特色区域
     */
    onOk(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          const API = this.modalType === "ADD" ? addAreas : updateAreas;
          const res = await API(
            this.modalType === "ADD"
              ? this.addForm
              : {
                  layerId: this.currentId,
                  ...this.addForm,
                }
          );
          if (res.code === 200) {
            this.queryMenu();
            this.$message({
              type: "success",
              message: this.modalType === "ADD" ? "新增成功" : "修改成功",
            });
            this.visible = false;
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 确定新建特色区域
     */
    onCancel(form) {
      this.visible = false;
      this.modalTitle = "";
      this.modalType = null;
      this.currentId = null;
      this.$emit("set-info", {});
      this.addForm = {};
    },
    // 重命名
    async reNameArea(data) {
      const { id, label, color } = data;
      this.addForm = {
        ...this.addForm,
        layerName: label,
        layerColor: color,
      };
      this.modalTitle = "区域类型修改";
      this.modalType = "EDIT";
      this.visible = true;
      this.currentId = id;
      this.$emit("set-info", data);
    },
    // 删除
    removeArea(data) {
      const { id } = data;
      this.$confirm("提示：该区域类型下面的全部区域都会被删除", {
        title: "是否确定删除当前区域类型？",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await removeAreas({ idList: [id] });
          if (res.code === 200) {
            this.queryMenu();
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getWaitApproveCount();
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
    // 查看全部区域
    async lookAreas(data,type) {
      // console.log(data)
      this.layerId = data.layerId;
      this.currentLayerInfo = data;
      this.$emit("set-info", data);
      this.menuLoading = true;
      this.$store.dispatch("lookAreas", {...data,pageNum:this.pageNum}).then(res => {
        this.total = res.total;
        if(type == 'shapeInfo'){
          this.$emit('getLoading',false)
          const { shapeList } = this.$store.state.featuredAreas;
          const childList = shapeList[0]?.children || [];
          // console.log(shapeList,childList)
          let shapeInfo = childList.filter(item=>item.shapeId == data.shapeId);
          if(shapeInfo && shapeInfo[0]?.id){
            let item = shapeInfo[0];
            this.handleNodeClick(item,{},{});
          }else{
            this.$emit('draw-polygon', [], true);
          }
          // if(res?.data?.length){
          //   this.handleNodeClick(res.data[0],{},{});
          // }
        }else{
          this.$emit('draw-polygon', res.rows);
        }
        this.menuLoading = false;
      });
    },
    // 返回主页
    goBack() {
      if (this.isDrawing) {
          this.$message({
            type: "info",
            message: "请先完成图形绘制",
          });
        return;
      }
      this.$store.dispatch("goBack", 1);
      this.$store.commit('SET_LAYER_INFO',{})
       getDrawCountApi().then(res=>{
        if(res.code == 200){
          this.approveCount = res.data;
        }
      })
    },
    // 查看列表
    gotoList() {
      this.drawerShow = true;
    },
    // 关闭抽屉
    close() {
      this.drawerShow = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.menu-wrap {
  height: calc(100vh - 225px);
  display: flex;
  flex-direction: row;
  justify-content: center;
  ::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #d0e0ff;
  }
  .tree-box{
    overflow-y: scroll;
    overflow-x: hidden;
    height: calc(100% - 90px);
  }
  .my-tree-box{
    ::v-deep .el-tree-node__expand-icon.is-leaf{
      display: none;
    }
    ::v-deep .el-tree-node__expand-icon.expanded{
       display: none;
    }
    .my-tree-title2{
      margin-left: 5px;
      height: 40px;
    }
  }
}
.tree-wrap2{
  .tree-box{
    height: calc(100% - 30px);
  }
}
.tree-wrap {
  width: 250px;
  height: calc(100vh - 225px);
  background-color: rgba(242,244,247,1);
  padding-top: 10px;
}
.menu-wrap-min {
  width: 0;
}

.add-areas {
  margin: 0 10px 10px;
  // border: 1px dashed #adadad;
  color: #2094ff;
  height: 40px;
  line-height: 40px;
  text-align: left;
  font-size: 16px;
  background-color: #fff;
  cursor: pointer;
  span {
    // margin-left: 10px;
  }
  padding: 0 3px;
}
.approve{
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  color: #222;
  span{
    margin-left: 0;
  }
  .num{
    color: #f5441f;
    // border-bottom: 1px solid #f5441f;
    margin: 0 2px;
  }
  .el-icon-refresh{
      color: #2094ff;
  }
  .text{
    font-size: 14px;
    color:#032626;
  }
  background: rgba(221,234,248,1);
  border-radius: 4px;
}

.areas-num {
  height: 40px;
  line-height: 40px;
  background-color: rgba(242,244,247,1);
  padding: 0 10px;
  font-size: 14px;
  color:#032626;
}

.areas-back {
  color: #2094ff;
  font-size: 14px;
  line-height: 20px;
  margin-bottom: 10px;
  padding-left: 10px;
  cursor: pointer;
}

::v-deep .el-tree-node__content {
  height: auto;
}

.custom-tree-node {
  height: auto;
  line-height: 40px;
  color: #222;
  font-size: 14px;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: space-between;
  padding-right: 10px;

  .tree-title-box {
    display: flex;
    align-content: center;
    justify-content: space-between;
    position: relative;
    .el-icon-view {
      margin-top: 14px;
    }
    .look-list {
      color: #2094ff;
      cursor: pointer;
      position: absolute;
      right: 0;
      top: 0;
    }
    .look-list2{
      right: 60px;
      top: 13px;
    }
    .tree-title {
      width: 200px;
      display: inline-block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      .title-left{
        width: 150px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .title-right{
        color:#4886f8;
        font-size: 12px;
        border-radius: 5px;
        background: rgba(22, 132, 252, 0.1);
        height: 20px;
        line-height: 17px;
        padding: 2px 6px;
      }
    }
    .my-tree-title{
      display: flex;
      margin-left: 5px;
      align-items: center;
    }
  }
  .tree-title-setting {
    color: #2094ff;
    line-height: 20px;
    font-size: 12px;
    text-align: right;
    span {
      margin-left: 10px;
    }
  }
}

.area-dialog {
  margin-top: 30vh;
}
.disabled-btn {
    background: #ddd;
    color: #666;
    cursor: not-allowed;
}
.panel-box{
  display: flex;
  justify-content: space-between;
  .add-areas-spec{
    background: #2094ff;
    color: #fff;
    border-radius: 4px;
    font-size: 14px;
    padding: 0 6px;
    &:first-child{
      margin-right: 0px;
    }
    &:last-child{
      margin-left: 0px;
    }
  }

  .add-areas-red {
    background: red;
  }
}
.notBuShiClass{
  display: block;
  .add-areas{
    text-align: center;
  }
}
.pagi-box-quyu{
  background: #fff;
  position: relative;
  top: -166px;
  right: 40px;
  ::v-deep .el-pagination .btn-prev, .el-pagination .btn-next{
    color: #303133 !important;
  }
}
</style>
