<template>
  <el-container>
    <el-header v-if="isSearch">
      <el-form style="margin: 10px 0" :inline="true">
        <el-form-item label="队伍名称：">
          <el-input v-model="contingentName" placeholder="请输入队伍名称" />
        </el-form-item>
        <el-form-item>
          <el-button
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            搜索
          </el-button>
          <el-button class="commonBtn" icon="el-icon-refresh" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <div class="headerTop">
        <div>
          <el-button type="primary" class="el-icon-plus" @click="add">
            新增</el-button
          >
        </div>
        <div>
          <right-toolbar :showSearch.sync="isSearch" @queryTable="getList" ></right-toolbar>
        </div>
      </div>
      <el-table
        height="calc(100% - 200px)"
        :data="list"
        :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px' }"
        :cell-style="{ 'text-align': 'center', padding: '2px' }"
        style="width: 100%"
      >
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            <span> {{ (pageNum - 1) * pageSize + (scope.$index + 1) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="队伍名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.contingentName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="队伍状态" align="center">
          <template slot-scope="scope">
            <span>{{
              scope.row.contingentStatus === 1 ? "已启用" : "未启用"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.updateDate || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="300">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="edit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="mini" @click="del(scope.row.id)">
              删除
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="organization(scope.row.id)"
            >
              组织结构
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        @pagination="getList"
      />
    </el-main>
    <el-dialog
      :visible.sync="addAlert"
      width="30%"
      :title="title"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        label-position="right"
        label-width="130px"
        inline
        :rules="rules1"
        style="overflow: auto"
      >
        <el-form-item label="队伍名称：" prop="contingentName">
          <el-input
            v-model="addForm.contingentName"
            placeholder="请输入队伍名称"
          />
        </el-form-item>
        <el-form-item label="队伍状态：" prop="contingentStatus">
          <el-radio v-model="addForm.contingentStatus" :label="1"
            >启用</el-radio
          >
          <el-radio v-model="addForm.contingentStatus" :label="2"
            >关闭</el-radio
          >
        </el-form-item>
      </el-form>
      <el-row
        style="
          text-align: right;
          margin-top: 50px;
          padding-top: 10px;
          border-top: 1px solid rgb(33, 67, 91);
        "
      >
        <el-button type="primary" @click="addSubmit('addForm')">
          提交
        </el-button>
        <el-button class="abrogateBtn" @click="addCancel"> 取消 </el-button>
      </el-row>
    </el-dialog>
    <el-dialog
      :visible.sync="organizationAlert"
      :fullscreen="true"
      title="组织架构图"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-dialog
        width="30%"
        :title="title"
        :visible.sync="innerVisible"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
      >
        <el-form
          ref="addTeam"
          :model="addTeam"
          label-position="right"
          label-width="130px"
          inline
          :rules="rules2"
          style="overflow: auto"
        >
          <el-form-item label="岗位名称：" prop="drillPost">
            <el-input
              style="width: 220px"
              v-model="addTeam.drillPost"
              placeholder="请输入岗位名称"
            />
          </el-form-item>
          <el-form-item label="人员名称：" prop="personList">
            <el-cascader
              v-model="addTeam.personList"
              style="width: 220px"
              :options="options"
              :show-all-levels="false"
              :props="props"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <el-row
          style="
            text-align: right;
            margin-top: 50px;
            padding-top: 10px;
            border-top: 1px solid rgb(33, 67, 91);
          "
        >
          <el-button type="primary" @click="teamSubmit('addTeam')">
            提交
          </el-button>
          <el-button class="abrogateBtn" @click="teamCancel"> 取消 </el-button>
        </el-row>
      </el-dialog>
      <div class="org-boxs">
        <vue2-org-tree
          name="test"
          :data="datas"
          :horizontal="horizontal"
          :label-class-name="labelClassName"
          :render-content="renderContent"
          collapsable
          @on-expand="onExpand"
          @on-node-click="onNodeClick"
        />
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import {
  getTeamList,
  addTeam,
  removeTeam,
  editTeam,
  getTree,
  getDeptUserTree,
  addOrganizational,
  editOrganizational,
  removeOrganizational,
} from "@/api/emergencies";
export default {
  name: "RuoyiAllocation",

  data() {
    return {
      //组织架构当前项数据
      itemData: {},
      props: { multiple: true, emitPath: false },
      innerVisible: false,
      organizationAlert: false,
      addAlert: false,
      isSearch: true,
      pageNum: 1,
      pageSize: 10,
      total: 1,
      list: [],
      addForm: {
        contingentName: "",
        contingentStatus: 1,
      },
      options: [],
      addTeam: {
        drillPost: "",
        personList: [],
      },
      title: "添加演习队伍",
      rules1: {
        contingentName: [
          { required: true, message: "请输入队伍名称", trigger: "blur" },
        ],
        contingentStatus: [
          { required: true, message: "请选择队伍状态", trigger: "change" },
        ],
      },
      rules2: {
        drillPost: [
          { required: true, message: "请输入岗位名称", trigger: "blur" },
        ],
        personList: [
          { required: true, message: "请选择人员", trigger: "change" },
        ],
      },
      contingentName: "",
      horizontal: false,
      collapsable: false,
      expandAll: true,
      labelClassName: "bg-none",
      //组织架构图数据
      datas: {},
      //组织架构当前操作id
      contingentId: "",
      manUrl: require("@/assets/images/jianshi.png"),
      title: "",
    };
  },

  mounted() {
    this.getList();
    this.initOrg();
    // 获取部门用户列表
    getDeptUserTree().then((res) => {
      if (res.code === 200) {
        this.options = this.getUser(res.data);
        console.log(this.options);
      }
    });
  },

  methods: {
    getUsers(data) {
      return data.map((item) => {
        return { label: item.nickName, value: item.userId };
      });
    },
    getUser(data) {
      return data.map((item) => {
        if (item.children && item.children.length && !item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: this.getUser(item.children),
          };
        }
        if (item.children && item.children.length && item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: [
              ...this.getUser(item.children),
              ...this.getUsers(item.sysUsers),
            ],
          };
        }
        if (!(item.children && item.children.length) && item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: this.getUsers(item.sysUsers),
          };
        }
        if (!(item.children && item.children.length) && !item.sysUsers) {
          return {
            label: item.label,
            value: item.id + "d",
            children: [],
          };
        }
        return { label: item.label, value: item.id + "d" };
      });
    },
    toggleExpand(data, val) {
      var _this = this;
      if (Array.isArray(data)) {
        data.forEach(function (item) {
          _this.$set(item, "expand", val);
          if (item.children) {
            _this.toggleExpand(item.children, val);
          }
        });
      } else {
        this.$set(data, "expand", val);
        if (data.children) {
          _this.toggleExpand(data.children, val);
        }
      }
    },
    onExpand(e, data) {
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          this.collapse(data.children);
        }
      } else {
        this.$set(data, "expand", true);
      }
    },
    //点击选项执行的方法，可以用于跳转到其他链接，注意一定要写协议头
    onNodeClick(e, data) {
      //console.log(data.label);
      if (data.url == null) {
        return false;
      } else {
        window.open(data.url);
      }
    },
    collapse(list) {
      var _this = this;
      list.forEach(function (child) {
        if (child.expand) {
          child.expand = false;
        }
        child.children && _this.collapse(child.children);
      });
    },
    expandChange() {
      this.toggleExpand(this.data, this.expandAll);
    },
    toggleExpand(data, val) {
      var _this = this;
      if (Array.isArray(data)) {
        data.forEach(function (item) {
          _this.$set(item, "expand", val);
          if (item.children) {
            _this.toggleExpand(item.children, val);
          }
        });
      } else {
        this.$set(data, "expand", val);
        if (data.children) {
          _this.toggleExpand(data.children, val);
        }
      }
    },
    initOrg() {
      this.$set(this.datas, "expand", true);
      if (this.datas.children) {
        this.datas.children.forEach((item, index) => {
          this.$set(item, "expand", true);
        });
      }
    },
    renderContent(h, data) {
      console.log(data);
      return (
        <span
          style="width:100%;height:100%;display:block;padding:10px 15px;border-radius:3px;margin-right:20px"
          class={
            data.relations === "1-1"
              ? "bg-tomato"
              : data.relations === "1-2"
              ? "bg-gold"
              : data.relations === "1-3"
              ? "bg-gray"
              : data.relations === "1-4"
              ? "bg-lightpink"
              : data.relations === "1-5"
              ? "bg-blue"
              : "bg-green"
          }
        >
          <el-popover placement="top-start" width="280" trigger="click">
            <el-button
              onclick={() => {
                this.addTeamItem(data);
              }}
              type="primary"
            >
              新增
            </el-button>
            <el-button
              type="primary"
              onclick={() => {
                this.editTeamItem(data);
              }}
            >
              修改
            </el-button>
            <el-button
            type="primary"
              onclick={() => {
                this.delTeamItem(data);
              }}
            >
              删除
            </el-button>
            <div slot="reference">
              <p style="height:6vh;padding:0;margin-bottom:1vh;">
                <img
                  style="width:6vh;height:6vh;"
                  src={this.manUrl}
                />
              </p>
              <p style="font-size:1.6vh;">{data.drillPost}</p>
              <p style="font-size:1vh;">{data.persons}</p>
            </div>
          </el-popover>
        </span>
      );
    },
    // 新增组织架构子级
    addTeamItem(data) {
      this.itemData = data;
      this.title = "新增";
      this.innerVisible = true;
    },
    //修改组织架构
    editTeamItem(data) {
      console.log(data);
      this.itemData = data;
      this.addTeam = {
        drillPost: data.drillPost === "请更新岗位" ? "" : data.drillPost,
        personList: data.personList || [],
      };
      this.title = "修改";
      this.innerVisible = true;
    },
    // 组织结构
    organization(id) {
      this.contingentId = id;
      getTree({ contingentId: id }).then((res) => {
        if (res.code === 200) {
          console.log(res);
          this.datas = res.data[0] || {};
          this.toggleExpand(this.datas, true);
          this.organizationAlert = true;
        }
      });
    },
    add() {
      this.addAlert = true;
      this.title = "添加演习队伍";
    },
    edit(item) {
      console.log(item);
      this.title = "编辑演习队伍";
      this.addForm = JSON.parse(JSON.stringify(item));
      this.addAlert = true;
    },
    del(id) {
      this.$confirm("确认删除这条演习队伍吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          removeTeam(id).then((res) => {
            if (res.code === 200) {
              if (this.list.length === 1 && this.pageNum > 1) {
                this.pageNum -= 1;
              }
              this.getList();
              this.$message.success(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message.error("已取消删除");
        });
    },
    //删除组织架构
    delTeamItem(data) {
      this.$confirm("确认删除这条数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log(data)
          if (data.parentId === '0') {
            this.$message.error("组织架构最底层不允许删除！");
            return
          }
          removeOrganizational(data.id).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.innerVisible = false;
              this.organization(this.contingentId);
            }
          });
        })
        .catch(() => {
          this.$message.error("已取消删除");
        });
    },
    getList() {
      getTeamList({
        contingentName: this.contingentName,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.code === 200) {
          this.list = res.rows;
          this.total = res.total;
        }
        console.log(res);
      });
    },
    teamSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "新增") {
            addOrganizational({
              contingentId: this.contingentId,
              parentId: this.itemData.id,
              drillPost: this.addTeam.drillPost,
              personList: this.addTeam.personList,
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.innerVisible = false;
                this.organization(this.contingentId);
                this.addTeam = {
                  drillPost: "",
                  personList: [],
                };
                this.$refs.addTeam.resetFields();
              }
            });
          } else {
            console.log(this.itemData);
            editOrganizational({
              contingentId: this.contingentId,
              id: this.itemData.id,
              drillPost: this.addTeam.drillPost,
              personList: this.addTeam.personList,
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.innerVisible = false;
                this.organization(this.contingentId);
                this.addTeam = {
                  drillPost: "",
                  personList: [],
                };
                this.$refs.addTeam.resetFields();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    addSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加演习队伍") {
            addTeam({
              contingentName: this.addForm.contingentName,
              contingentStatus: this.addForm.contingentStatus,
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.addAlert = false;
                this.getList();
              }
            });
          } else {
            editTeam({
              id: this.addForm.id,
              contingentName: this.addForm.contingentName,
              contingentStatus: this.addForm.contingentStatus,
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.msg);
                this.addAlert = false;
                this.getList();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    reset() {
      this.contingentName = "";
      this.pageNum = 1;
      this.pageSize = 10;
      this.getList();
    },
    addCancel() {
      this.addAlert = false;
      this.addForm = {
        contingentName: "",
        contingentStatus: 1,
      };
      this.$refs.addForm.resetFields();
    },
    teamCancel() {
      this.innerVisible = false;
      this.addTeam = {
                  drillPost: "",
                  personList: [],
                };
      this.$refs.addTeam.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.org-boxs {
  width: 100%;
  height: 100%;
  text-align: center;
  /*background: #030C24;*/
  /* background-image: -webkit-radial-gradient(
    ellipse farthest-corner at center 40%,
    #000d4d 0%,
    #000105 100%
  );
  background-image: radial-gradient(
    ellipse farthest-corner at center 40%,
    #000d4d 0%,
    #000105 100%
  ); */
  overflow-y: scroll;
}
.org-tree-container {
  background: none !important;
}
.org-tree-node-label {
  white-space: nowrap;
}
.bg-none {
  background-color: #030c24;
  color: #ffffed;
}
.bg-white {
  background-color: #ecf5ff;
}
.org-tree-node-label .org-tree-node-label-inner {
  width: 6vw;
  padding: 0px 0px;
  text-align: center;
  border-radius: 3px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15);
  /* border: 1px solid @colors;*/
  overflow: hidden;
  box-sizing: border-box;
}
.bg-tomato {
  background-color: #9e4a1c;
}
.bg-gold {
  background-color: #eca150;
}
.bg-gray {
  background-color: #deceaa;
}
.bg-lightpink {
  background-color: lightpink;
}
.bg-blue {
  background-color: #057d9f;
}
.bg-green {
  background-color: #50cb90;
}
</style>
