<template>
  <div class="app-container tenant-page">
    <div class="page-card search-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" class="search-form">
        <el-form-item label="租户编码" prop="tenantCode">
          <el-input
            v-model="queryParams.tenantCode"
            placeholder="请输入租户编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="租户名称" prop="tenantName">
          <el-input
            v-model="queryParams.tenantName"
            placeholder="请输入租户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" 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>
    </div>

    <div class="page-card toolbar-card">
      <el-row :gutter="10" class="mb8 toolbar-row">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['platform:platform:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['platform:platform:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['platform:platform:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['platform:platform:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div class="page-card table-card">
      <el-table border stripe highlight-current-row v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange" class="tenant-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="租户唯一ID" align="center" prop="id" />
        <el-table-column label="租户编码" align="center" prop="tenantCode" />
        <el-table-column label="租户名称" align="center" prop="tenantName" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="statusOptions" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="租户有效期" align="center" prop="expireTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--      <el-table-column label="数据库连接地址" align="center" prop="dbUrl" />-->
        <!--      <el-table-column label="数据库帐号" align="center" prop="dbAccount" />-->
        <!--      <el-table-column label="数据库密码" align="center" prop="dbPwd" />-->
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <el-table-column label="联系人" align="center" prop="contactName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div class="table-action-group">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['platform:platform:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['platform:platform:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleMenuChange(scope.row,'sys')"
                v-hasPermi="['platform:platform:edit']"
              >后台菜单权限</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleComMenuChange(scope.row,'com')"
                v-hasPermi="['platform:platform:edit']"
              >销售菜单权限</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-setting"
                @click="handleConfig(scope.row)"
                v-hasPermi="['platform:config:edit']"
              >修改配置</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改租户基础信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body class="tenant-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="tenant-data-form">
        <el-form-item label="租户编码" prop="tenantCode">
          <el-input v-model="form.tenantCode" placeholder="请输入租户编码" />
        </el-form-item>
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称" />
        </el-form-item>
        <!-- <el-form-item label="状态：" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="租户有效期" prop="expireTime" label-width="100px">
          <el-date-picker clearable size="small"
                          v-model="form.expireTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择租户有效期">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="数据库连接地址" prop="dbUrl">-->
        <!--          <el-input v-model="form.dbUrl" placeholder="请输入数据库连接地址" />-->
        <!--        </el-form-item>-->
        <el-form-item label="数据库IP" prop="dbIp" label-width="100px">
          <el-input v-model="form.dbIp" placeholder="请输入数据库ip地址" />
        </el-form-item>
        <el-form-item label="数据库端口" prop="dbPort" label-width="100px">
          <el-input v-model="form.dbPort" placeholder="请输入数据库端口" />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName" label-width="100px">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="数据库帐号" prop="dbAccount" label-width="100px">
          <el-input v-model="form.dbAccount" placeholder="请输入数据库帐号" />
        </el-form-item>
        <el-form-item label="数据库密码" prop="dbPwd" label-width="100px">
          <el-input v-model="form.dbPwd" placeholder="请输入数据库密码" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人" />
        </el-form-item>
      </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="title" :visible.sync="openMenu" width="500px" append-to-body class="tenant-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            :empty-text="treeEmptyText"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </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>

    <!-- 修改租户配置 -->
    <el-dialog title="修改配置" :visible.sync="openConfig" width="900px" append-to-body class="tenant-dialog">
      <config-index v-if="openConfig" :tenant-id="configTenantId" @success="handleConfigSuccess" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  exportTenant,
  roleMenuTreeselect,
  menuEdit
} from "@/api/tenant/tenant";

import ConfigIndex from "./config/index";

export default {
  name: "Tenant",
  components: {
    ConfigIndex
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户基础信息表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openMenu: false,
      menuFlag: "sys",
      // 状态：1-启用，0-禁用字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantCode: null,
        tenantName: null,
        status: null,
        expireTime: null,
        dbUrl: null,
        dbAccount: null,
        dbPwd: null,
        contactPhone: null,
        contactName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantCode: [
          { required: true, message: "租户编码不能为空", trigger: "blur" }
        ],
        tenantName: [
          { required: true, message: "租户名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        expireTime: [
          { required: true, message: "租户有效期不能为空", trigger: "change" }
        ],
        dbIp: [
          { required: true, message: "数据库ip地址不能为空", trigger: "blur" }
        ],
        dbPort: [
          { required: true, message: "数据库端口不能为空", trigger: "blur" }
        ],
        dbName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" }
        ],
        dbAccount: [
          { required: true, message: "数据库帐号不能为空", trigger: "blur" }
        ],
        dbPwd: [
          { required: true, message: "数据库密码不能为空", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ]
      },
      menuExpand: false,
      menuNodeAll: false,
      // 菜单列表
      menuOptions: [],
      treeEmptyText: "加载中，请稍后",
      defaultProps: {
        children: "children",
        label: "label"
      },
      isAdd: false,
      openConfig: false,
      configTenantId: null,
    };
  },
  created() {
    this.getList();
    this.getDicts("tenant_info_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询租户基础信息列表 */
    getList() {
      this.loading = true;
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantCode: null,
        tenantName: null,
        status: 0,
        expireTime: null,
        dbIp: null,
        dbPort: null,
        dbName: null,
        dbUrl: null,
        dbAccount: null,
        dbPwd: null,
        createTime: null,
        updateTime: null,
        contactPhone: null,
        contactName: null,
        tenantId: null,
        menuFlag: "sys",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isAdd = false;
      this.open = true;
      this.title = "添加租户基础信息";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isAdd = true;

      const id = row.id || this.ids
      getTenant(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改租户基础信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTenant(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTenant(this.form).then(response => {
              this.$message({
                message: response.msg,
                type: response.code === 200 ? "success" : 'error',
                duration: 5000
              });

              if (response.code === 200){
                this.open = false;
              }
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除租户基础信息编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delTenant(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有租户基础信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportTenant(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        if (value) {
          const ids = [];
          const walk = (nodes = []) => {
            nodes.forEach(node => {
              ids.push(node.id);
              if (node.children && node.children.length) {
                walk(node.children);
              }
            });
          };
          walk(this.menuOptions);
          this.$refs.menu.setCheckedKeys(ids);
        } else {
          this.$refs.menu.setCheckedKeys([]);
        }
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },

    cancelMenu:function(){
      this.openMenu = false;
      this.reset();
    },

    /** 提交按钮 */
    submitFormMenu: function() {
      // 1. 选中 + 半选中的 key
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();

      // 最终有权限的（选中+半选）
      let selectedKeys = [...checkedKeys, ...halfCheckedKeys];

      // 2. 递归获取所有菜单ID
      const getAllKeys = (tree) => {
        let keys = [];
        tree.forEach(item => {
          keys.push(item.id);
          if (item.children) keys.push(...getAllKeys(item.children));
        });
        return keys;
      };
      let allKeys = getAllKeys(this.menuOptions);

      // 3. 未选中的 key
      let unSelectedKeys = allKeys.filter(key => !selectedKeys.includes(key));

      const data = {selected: selectedKeys, unSelected: unSelectedKeys, id: this.form.tenantId,flag:this.menuFlag};
      menuEdit(data).then(res => {
        this.msgSuccess("修改成功");
      }).catch(res => {
        this.msgError(res.msg);
      })

    },


    handleMenuChange(row, flag) {
      this.reset();
      this.form.tenantId = row.id;
      this.menuFlag = flag;
      let data = {id: row.id, flag:flag}
      roleMenuTreeselect(data).then(res => {
        this.openMenu = true;
        this.menuOptions = res.menus;
        if (res.menus.length === 0) {
          this.treeEmptyText = "暂无数据";
        }
        this.title = "修改菜单权限";
        this.$nextTick(() => {
          const checkedIds = [];
          const walk = (nodes = []) => {
            nodes.forEach(node => {
              if (node.status === "0" && node.visible === "0") {
                checkedIds.push(node.id);
              }
              if (node.children && node.children.length) {
                walk(node.children);
              }
            });
          };
          walk(this.menuOptions);
          this.$refs.menu.setCheckedKeys(checkedIds);
        });
      })
    },

    handleComMenuChange(row, flag) {
      this.reset();
      this.form.tenantId = row.id;
      this.menuFlag = flag;
      let data = { id: row.id, flag: flag }
      roleMenuTreeselect(data).then(res => {
        this.openMenu = true;
        this.menuOptions = res.menus;
        if (res.menus.length === 0) {
          this.treeEmptyText = "暂无数据";
        }
        this.title = "修改菜单权限";
        this.$nextTick(() => {
          const checkedIds = [];
          const walk = (nodes = []) => {
            nodes.forEach(node => {
              if (node.status === "0" && node.visible === "0") {
                checkedIds.push(node.id);
              }
              if (node.children && node.children.length) {
                walk(node.children);
              }
            });
          };
          walk(this.menuOptions);
          this.$refs.menu.setCheckedKeys(checkedIds);
        });
      })
    },

    /** 修改配置按钮操作 */
    handleConfig(row) {
      this.configTenantId = row.id;
      this.openConfig = true;
    },
    /** 配置保存成功回调 */
    handleConfigSuccess() {
      this.openConfig = false;
    },
  }
};
</script>

<style scoped>
.tenant-page {
  background: #f5f7fb;
  min-height: calc(100vh - 84px);
  padding: 16px;
}

.page-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(25, 57, 99, 0.08);
  padding: 16px 16px 8px;
  margin-bottom: 14px;
}

.search-card {
  border: 1px solid #eef2f8;
}

.toolbar-card {
  padding: 12px 16px 4px;
}

.toolbar-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.tenant-page .search-form ::v-deep .el-form-item {
  margin-bottom: 12px;
}

.table-card {
  padding: 14px 14px 12px;
}

.tenant-page .tenant-table ::v-deep .el-table__header th {
  background: linear-gradient(180deg, #f7faff, #f3f8ff);
  color: #2f3f5c;
  font-weight: 600;
  height: 44px;
}

.tenant-page .tenant-table ::v-deep .el-table__body tr:hover > td {
  background: #f7fbff !important;
}

.tenant-page .tenant-table ::v-deep .el-table__body td {
  padding: 10px 0;
}

.tenant-page .tenant-table ::v-deep .el-table__body tr.current-row > td {
  background: #eef6ff !important;
}

.table-action-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 6px 8px;
}

.tenant-page .table-action-group ::v-deep .el-button--text {
  background: #f5f8ff;
  border: 1px solid #e7eefb;
  border-radius: 999px;
  padding: 4px 10px;
  line-height: 1.2;
}

.tenant-page .tenant-dialog ::v-deep .el-dialog {
  border-radius: 14px;
  overflow: hidden;
}

.tenant-page .tenant-dialog ::v-deep .el-dialog__header {
  background: linear-gradient(90deg, #f5f9ff, #ffffff);
  border-bottom: 1px solid #edf1f7;
}

.tenant-page .tenant-dialog ::v-deep .el-dialog__body {
  padding: 20px 24px 12px;
}

.tenant-data-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.tenant-page .tenant-data-form ::v-deep .el-form-item {
  width: calc(50% - 10px);
}

.tenant-page .tenant-data-form ::v-deep .el-input__inner,
.tenant-page .tenant-data-form ::v-deep .el-date-editor.el-input,
.tenant-page .tenant-data-form ::v-deep .el-date-editor.el-input__inner {
  width: 100%;
}

.tenant-page .tenant-data-form ::v-deep .el-radio-group {
  width: 100%;
  min-height: 34px;
  display: flex;
  align-items: center;
}

.tenant-page .tenant-dialog ::v-deep .dialog-footer .el-button {
  min-width: 84px;
  border-radius: 8px;
}

.tenant-page .tree-border {
  border-radius: 8px;
  border-color: #e6edf7;
  padding: 8px;
  background: #fbfdff;
}
</style>
