<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="deptName"
        label="部门名称"
        width="260"
      ></el-table-column>
      <el-table-column
        prop="orderNum"
        label="排序"
        width="200"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handlePost(scope.row)"
            >岗位</el-button
          >
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="deptOptions"
                :normalizer="normalizer"
                placeholder="选择上级部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="enabled">
              <el-radio-group v-model="form.enabled">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 岗位 -->
    <el-dialog
      :title="postTitle"
      :visible.sync="postoOpen"
      width="800px"
      append-to-body
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handlePostAdd"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="postData" style="width: 100%">
        <el-table-column prop="postName" label="岗位名称" />
        <el-table-column prop="postSort" label="排序" />
        <el-table-column prop="postSort" label="展示">
          <template slot-scope="scope">
            <span>{{ scope.row.enabled ? "显示" : "隐藏" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleMenu(scope.row)"
              >分配菜单</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handlePostUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handlePostDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="postoOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="postEdittitle"
      :visible.sync="postEditopen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="postEditForm"
        :model="postEditForm"
        :rules="rulesPost"
        label-width="80px"
      >
        <el-form-item label="岗位名称" prop="postName">
          <el-input
            v-model="postEditForm.postName"
            placeholder="请输入岗位名称"
          />
        </el-form-item>
        <el-form-item label="岗位顺序" prop="postSort">
          <el-input-number
            v-model="postEditForm.postSort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="显示排序" prop="enabled">
          <el-radio-group v-model="postEditForm.enabled">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="postEditForm.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPostForm">确 定</el-button>
        <el-button @click="cancelPost">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配菜单 -->
    <el-dialog
      :title="menuTitle + ' 岗位分配菜单'"
      :visible.sync="menuOpen"
      width="500px"
      append-to-body
    >
      <el-form :model="formMenu" label-width="120px">
        <template v-for="(item, index) in platformData">
          <el-form-item :label="item.platformName" v-if="item.data.length > 0" :key="item.platformKey + index">
            <el-tree
              :data="item.data"
              show-checkbox
              :ref="item.platformKey"
              :check-strictly="true"
              node-key="menuId"
              empty-text="加载中，请稍后"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormMenu">确 定</el-button>
        <el-button @click="cancelMenu">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
} from "@/api/system/dept";
import {
  listPost,
  getPost,
  delPost,
  addPost,
  updatePost,
  fenPeiMenu
} from "@/api/system/post";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { companyOfTree, getModuleUser } from "@/api/system/menu";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        deptName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 岗位信息
      postData: [],
      // 岗位title
      postTitle: "",
      // 岗位弹窗控制
      postoOpen: false,
      // 部门ID
      deptId: null,
      // 新增岗位弹窗
      postEdittitle: "",
      postEditopen: false,
      rulesPost: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
      },
      postEditForm: {
        postSort: 0,
        enabled: true,
      },
      // 平台菜单
      platformData: [],
      platform: {
        admin: "管理平台",
        mp_operation: "运营平台",
        ad_put_data: "投放数据系统",
        ad_put: "广告投放系统",
        store: "电商商城",
        wechat_corp: "企业微信"
      },
      // 分配菜单弹窗
      menuOpen: false,
      formMenu: {},
      defaultProps: {
        children: "children",
        label: "title"
      },
      // 分配菜单title
      menuTitle: '',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 分配菜单取消 */
    cancelMenu() {
      this.menuOpen = false;
      this.platformData.forEach(item => {
        if (this.$refs[item.platformKey] != undefined) {
          this.$refs[item.platformKey][0].setCheckedKeys([]);
        }
      })
    },
    /** 分配菜单提交 */
    submitFormMenu() {
      this.formMenu.menuIds = this.getMenuAllCheckedKeys();
      fenPeiMenu(this.formMenu).then(response => {
        if (response.code === 200) {
          this.msgSuccess("分配成功");
          this.menuOpen = false;
          this.getPostList(this.deptId);
        }
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeysList = []
      this.platformData.forEach(item => {
        if (this.$refs[item.platformKey] != undefined) {
          let checkedKeys = [], halfCheckedKeys = []
          checkedKeys = this.$refs[item.platformKey][0].getHalfCheckedKeys();
          halfCheckedKeys = this.$refs[item.platformKey][0].getCheckedKeys();
          checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
          checkedKeysList = [ ...checkedKeysList, ...checkedKeys ]
        }
      })
      return checkedKeysList
    },
    /** 分配菜单按钮 */
    async handleMenu(row) {
      this.menuTitle = row.postName
      let moduleData = await getModuleUser()
      let ajaxS = moduleData.data.map((item) => companyOfTree(item.platformKey));

      Promise.all(ajaxS).then((res) => {
        let data = moduleData.data.map((item, index) => {
          return {
            ...item,
            data: res[index].data
          }
        })
        this.platformData = data
        this.menuOpen = true;
        this.formMenu.postId = row.postId
        getPost(row.postId).then((response) => {
          let menuIdMapping = response.data.menuIdMapping;
          this.$nextTick(() => {
            setTimeout(() => {
              for (const key in menuIdMapping) {
                if (Object.hasOwnProperty.call(menuIdMapping, key)) {
                  const element = menuIdMapping[key];
                  console.log(11111, element)
                  element.forEach((element) => {
                    let node = this.$refs[key][0].getNode(element);
                    this.$refs[key][0].setChecked(node, true);
                  })
                }
              }
            }, 100);
          });
        });
      });
    },
    /** 新增修改取消 */
    cancelPost() {
      this.postEditopen = false;
      this.resetPost();
    },
    /** 岗位新增修改重置 */
    resetPost() {
      this.postEditForm = {
        postSort: 0,
        enabled: true,
      };
    },
    /** 岗位修改 */
    handlePostUpdate(row) {
      this.resetPost();
      this.postEditForm = {
        ...this.postEditForm,
        ...row,
      };
      this.postEdittitle = "修改岗位";
      this.postEditopen = true;
    },
    /** 岗位删除 */
    handlePostDelete(row) {
      const postIds = row.postId;
      this.$confirm('是否确认删除岗位编号为"' + postIds + '"的数据项?', "警告",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () { return delPost(postIds); }).then(() => {
        this.getPostList(this.deptId);
        this.msgSuccess("删除成功");
      }).catch(function () {});
    },
    /** 岗位新增修改提交 */
    submitPostForm() {
      this.$refs["postEditForm"].validate((valid) => {
        if (valid) {
          if (this.postEditForm.postId != undefined) {
            updatePost(this.postEditForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.postEditopen = false;
                this.resetPost();
                this.getPostList(this.deptId);
              }
            });
          } else {
            addPost(this.postEditForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.postEditopen = false;
                this.resetPost();
                this.getPostList(this.deptId);
              }
            });
          }
        }
      });
    },
    /** 新增岗位 */
    handlePostAdd() {
      this.postEditForm = {
        ...this.postEditForm,
        deptId: this.deptId,
      };
      this.postEdittitle = "新增岗位";
      this.postEditopen = true;
    },
    /** 岗位 */
    handlePost(row) {
      console.log(row);
      this.postTitle = row.deptName;
      this.deptId = row.deptId;
      this.postEditForm = {
        ...this.postEditForm,
        deptId: row.deptId,
      };
      this.getPostList(row.deptId);
    },
    // 获取岗位列表
    getPostList(deptId) {
      listPost(deptId).then((res) => {
        this.postData = res.data;
        this.postoOpen = true;
      });
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept().then((response) => {
        this.deptList = this.handleTree(response.data, "deptId");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        enabled: true,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加部门";
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
      });
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addDept(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.deptName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delDept(row.deptId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
  },
};
</script>