<template>
  <div class="organiza">
    <div class="organiza-body">
      <div class="but">
      <el-button type="primary" v-power="'add'" @click="insertProject"
        >新增组织架构</el-button
      >
    </div>
      <div class="tree">
        <div class="treeTile">
          <span>全国消防火调组织架构</span>
          <span style="padding-right: 100px">操作</span>
        </div>
        <div class="treeList">
          <el-tree
            style="width: 100%;"
            :props="treeProps"
            :data="treedata"
            node-key="id"
            :current-node-key="user.info.id"
            accordion
            default-expand-all
          >
            <template  #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ data.name }}</span>
                <div class="butList"  v-if="data.id != '1'">
                  <a @click="seeDetail(data, node)" v-power="'view'"> 查看 </a>
                  <a @click="insertProject(data)" v-power="'edit'"> 编辑 </a>
                  <a
                    style="color: var(--primaryColor)"
                    @click="remove(data.id)"
                    v-power="'del'"
                  >
                    删除
                  </a>
                </div>
              </span>
            </template>
          </el-tree>
        </div>
      </div>
    </div>
    <com-dialog
      v-model:show="show"
      @submit="submit"
      :title="`${detailType}组织架构`"
    >
      <el-form
        ref="form"
        :model="detail"
        label-width="84px"
        class="camera-from"
      >
        <el-form-item label="组织名称" class="mandatory">
          <el-input
            v-model="detail.name"
            maxlength="50"
            placeholder="请输入组织名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="组织类型" class="mandatory">
          <el-radio-group v-model="detail.deptType">
            <el-radio label="1">总队</el-radio>
            <el-radio label="2">支队</el-radio>
            <el-radio label="3">大队</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级组织" class="mandatory">
          <el-cascader
            v-if="detailType == '新增'"
            style="width: 100%"
            v-model="superiorValue"
            :options="treedatas"
            :props="{ checkStrictly: true, label: 'name', value: 'id' }"
            @change="handleChange"
          ></el-cascader>
          <el-input
            v-else
            v-model="detail.parentName"
            :disabled="true"
            placeholder="请输入组织名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input
            v-model="detail.leader"
            maxlength="50"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input
            v-model.trim="detail.phone"
            maxlength="50"
            placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="detail.remark"
            maxlength="500"
            type="textarea"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
    </com-dialog>

    <com-dialog
      v-model:show="seeShow"
      @submit="seeShow = false"
      :showClose="false"
      enterText="返回"
      title="查看组织架构"
    >
      <see-info :required="true" :detail="seeData" />
    </com-dialog>

    <!-- <com-dialog
      v-model:show="infoShow"
      @submit="
        () => {
          tipsShow = !tipsShow;
        }
      "
      enterText="我知道了"
      :showClose="false"
      title="温馨提示"
    >
      <div>
        当前组织下尚存在用户或绑定的相机，删除组织将一并删除，确认要删除组织吗？
      </div>
    </com-dialog> -->
  </div>
</template>

<script>
import { reactive, toRefs, onMounted } from "vue"; //computed watch ref
import comDialog from "@/components/dialog";
import user from "@/state/user";
import axios from "axios";
import { useRoute } from "vue-router";
import seeInfo from "./seeInfo.vue";
import {PHONE} from '@/constant/REG'
import { getApp } from "@/app";
import {
  getTreeselect,
  delTreeitem,
  addTreeitem,
  editTreeitem,
} from "@/request/config";

export default {
  name: "camera",
  setup() {
    const rout = useRoute();
    console.log("rout", rout);
    const data = reactive({
      show: false,
      tipsShow: false,
      seeShow: false,
      infoShow: false,
      detailType: "新增",
      seeData: {
        name: "test",
        deptType: "1",
        superior: "sheq",
        leader: "负责人",
        phone: "",
        remark: "test",
      },
      detail: {
        name: "",
        deptType: "",
      },
      treeProps: { children: "children", label: "name" },
      superiorValue: [],
      treedata: [],
      treedatas:[]
    });
    const seeDetail = (val) => {
      // console.log('seeDetail',getApp().$refs)
      // getApp().$refs.treeBox.setCurrentKey(user.info.id)
      console.log("getApp().$ref", getApp().$refs);
      data.seeData = {
        superior: val.order,
        ...val,
      };
      data.seeShow = true;
    };
    const handleNodeClick = (data) => {
      console.log(data);
    };
    const submit = async () => {
      
      const { name, deptType, parentId,phone } = data.detail;
      const { detailType } = data;
      if (!name) {
        return getApp().$message.error("组织名称不能为空！", "提示");
      } else if (!deptType) {
        return getApp().$message.error("组织类型不能为空！", "提示");
      } else if (!parentId) {
        return getApp().$message.error("上级组织不能为空！", "提示");
      } else if( phone && !PHONE.REG.test(phone)){
        return getApp().$message.error('联系电话格式不正确', "提示");
      }
      //校验成功后温馨提示
      let apidata = {
        superior: "sheq",
        ...data.detail,
      };
      let requestApi = addTreeitem;
      if (detailType == "编辑") {
        requestApi = editTreeitem;
      }
      let res = await axios.post(requestApi, apidata);
      getTreedata();
      console.log("async", res, data);
      if (detailType == "编辑") {
        getApp().$message({ message: "操作成功", type: "success" });
      } else {
        getApp().$confirm("组织创建成功，快去创建用户吧", "温馨提示", {
          confirmButtonText: "去创建",
          showClose:true,
          cancelButtonText: "我知道了",  
        }).then(() => {
            setTimeout(()=>{  
                getApp().$router.push({name: 'user'})
              },500)
          })
      }
      data.detail = {};
      data.show = false;
      data.superiorValue = [];
    };
    const insertProject = (val) => {
      console.log("insertProject", val.id);
      if (val.id) {
        data.detailType = "编辑";
        data.detail = {
          ...val,
        };
      } else {
        data.detailType = "新增";
        data.detail = {};
      }
      data.show = true;
    };
    const handleChange = (val) => {
      data.detail.parentId = val && val[val.length - 1];
      console.log("点击handleChange", val.length, data);
    };
    const loadNode = (node, resolve) => {
      if (node.level === 0) {
        return resolve([{ label: "region" }]);
      }
      if (node.level > 1) return resolve([]);

      setTimeout(() => {
        const data = [
          {
            name: "leaf",
            leaf: true,
          },
          {
            name: "zone",
          },
        ];

        resolve(data);
      }, 500);
    };
    const remove = async (val) => {
      let isOk = await getApp().$confirm(
        "确认要删除组织吗？",
        "删除"
      );
      if (isOk) {
        let res = await axios.post(delTreeitem + val);
        console.log("isOk", isOk, val, res);
        getApp().$message({ message: "删除成功", type: "success" });
        getTreedata();
      }
    };
    const getTreedata = async () => {
      let ress = await axios.get(getTreeselect, {});
      let res = await axios.get(getTreeselect, {params:{type:'1'}});
      data.treedata = res.data;
      data.treedatas = ress.data;
      // getApp().$ref.treeBox.setCurrentKey(user.info.id)
    };
    onMounted(async () => {
      getTreedata();
    });
    return {
      // treedata,
      ...toRefs(data),
      // ...toRefs(state),
      user,
      handleNodeClick,
      loadNode,
      insertProject,
      submit,
      handleChange,
      seeDetail,
      remove,
    };
  },
  data() {
    return {
      searchLoading: false,
      searchOptions: [],
    };
  },
  methods: {},

  components: {
    "com-dialog": comDialog,
    "see-info": seeInfo,
  },
};
</script>

<style lang="scss" scoped>
.organiza {
  .but {
    padding: 0 16px 16px 16px;
    background-color: #fff;
    text-align: right;
  }
  .title {
    height: 56px;
    padding: 0 24px;
    color: #303133;
    font-size: 16px;
    line-height: 56px;
    height: 56px;
    font-weight: 500;
    background-color: #fff;
    border-bottom: 1px solid #e4e7ed;
  }
  .organiza-body {
    margin-top: 15px;
    background-color: #fff;
    padding: 15px;
    .tree {
      border: 1px solid #ebeef5;
      // margin-top: 24px;
      .treeTile {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
        background-color: #fafafa;
        padding: 12px 20px;
      }
      .treeList {
        max-height: 500px;
        overflow-y: auto;
        display: flex;
        justify-content: space-between;
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          .butList {
            width: 140px;
            a {
              margin: 0 8px;
            }
          }
        }
      }
    }
  }
}
.table-ctrl-right {
  .search-scene {
    margin: 0 20px 0 26px;
  }
  i {
    margin-left: 20px;
    font-size: 1.7rem;
    vertical-align: middle;
    cursor: pointer;

    &.active {
      color: var(--primaryColor);
    }
  }
}

.camera-from {
  margin: 0 50px;
}
.share-from {
  width: 500px;
  margin: 0 auto;
}
.maker {
  font-weight: 400;
  color: #969799;
  line-height: 20px;
}
.oper-user {
  height: 40px;
  overflow: hidden; //超出的文本隐藏
  text-overflow: ellipsis; //溢出用省略号显示
  white-space: nowrap; //溢出不换行
  cursor: pointer;
}
</style>

<style>
.organiza .el-tree-node__content {
  padding: 12px 10px;
  border-bottom: 1px solid #ebeef5;
}
.camera-from .el-select,
.dispatch-file-from .el-select {
  width: 100%;
}

.el-textarea__inner {
  font-family: "Microsoft YaHei";
}
.dispatch-detial .el-form-item__content {
  color: #323233;
}
.dispatch-detial .el-form-item__label {
  color: #646566;
}

</style>