<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否可用" prop="enabled">
				<el-select v-model="queryParams.enabled" clearable placeholder="请选择" size="small">
					<el-option label="可用" :value="true" />
					<el-option label="禁用" :value="false" />
				</el-select>
      </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="companyList">
      <el-table-column prop="companyName" label="公司名称" align="center" />
      <el-table-column label="Enable?" align="center" prop="enabled">
        <template slot-scope="scope">
          <span>{{ scope.row.enabled ? "可用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="remark" label="备注" align="center" />
      <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="handleMenu(scope.row)"
            >分配菜单</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <div style="width: 10px; display: inline-block"></div>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDelete(scope.row)"
          >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增或修改 -->
    <el-dialog
      :title="title"
      :visible.sync="openScope"
      width="350px"
      append-to-body
    >
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            v-model="form.companyName"
            placeholder="请输入公司名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="是否可用" prop="enabled">
          <el-switch v-model="form.enabled" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.remark"
            placeholder="请输入备注"
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitScope">确 定</el-button>
        <el-button @click="cancelScope">取 消</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"
              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 { getCompanyList, AddCompany, editCompany, deleteCompany, configCompanyMenus, getCompanyMenus } from "@/api/system/company";
import { allOfTree, getModule } from "@/api/system/menu";
export default {
  data() {
    return {
      // 查询参数
      queryParams: {
        pageSize: 20,
        pageNum: 1
      },
      // 显示搜索条件
      showSearch: true,
      // loading
      loading: false,
      // 列表数据
      companyList: [],
      // 列表个数
      total: 0,
      // 新增公司弹窗控制
      openScope: false,
      // 新增公司弹窗名字
      title: "",
      // 新增参数
      form: { enabled: true },
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" },
        ],
      },
      // 平台菜单
      platformData: [],
      menuTitle: '',
      formMenu: {},
      menuOpen: false,
      defaultProps: {
        children: "children",
        label: "title"
      },
    };
  },
  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();
      configCompanyMenus(this.formMenu).then(response => {
        if (response.code === 200) {
          this.msgSuccess("分配成功");
          this.menuOpen = false;
          this.getList()
        }
      })
    },
    // 所有菜单节点数据
    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.companyName
      let moduleData = await getModule()
      let ajaxS = moduleData.data.map((item) => allOfTree(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.companyId = row.id
        getCompanyMenus(row.id).then((response) => {
          let menuIdMapping = response.data;
          this.$nextTick(() => {
            setTimeout(() => {
              for (const key in menuIdMapping) {
                if (Object.hasOwnProperty.call(menuIdMapping, key)) {
                  const element = menuIdMapping[key];
                  element.forEach((element) => {
                    let node = this.$refs[key][0].getNode(element);
                    if (node.isLeaf) {
                      this.$refs[key][0].setChecked(node, true);
                    }
                  })
                }
              }
            }, 100);
          });
        });
      });
    },
    /** 搜索 */
    handleQuery() {
			this.getList()
		},
    /** 重置 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增公司 */
    handleAdd() {
      this.openScope = true;
      this.title = "新增消息分组";
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      getCompanyList(this.queryParams).then((res) => {
        this.loading = false;
        this.companyList = res.data.records;
        this.total = res.data.total
      });
    },
    /** 新增弹窗确定 */
    submitScope() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
						editCompany(this.form).then((response) => {
              if (response.data) {
                this.msgSuccess("修改成功");
                this.openScope = false;
                this.form = {};
                this.getList();
              }
            });
          } else {
						AddCompany(this.form).then(res => {
							if (res.data) {
                this.msgSuccess("新增成功");
                this.openScope = false;
                this.form = {};
                this.getList();
              }
						})
          }
        }
      });
    },
		/** 新增弹窗取消 */
    cancelScope() {
      this.form = {};
      this.openScope = false;
    },
		/** 修改数据 */
    handleUpdate(row) {
			let { companyName, enabled, id, remark } = row
			this.form = { companyName, enabled, id, remark }
      this.openScope = true;
      this.title = "修改消息分组";
    },
		/** 删除数据 */
    handleDelete(row) {
      deleteCompany(row.id).then((res) => {
        if (res.data) {
          this.msgSuccess("删除成功");
          this.getList();
        }
      });
    }
  },
};
</script>