<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="子系统名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入子系统名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </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>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          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="tenantList">
      <el-table-column label="子系統名称" prop="name" width="120" />
      <el-table-column label="负责人姓名" prop="contact" align="center" />
      <el-table-column
        label="负责人电话"
        prop="contact_mobile"
        align="center"
      />
      <el-table-column label="ip地址" prop="ip" align="center" />
      <el-table-column label="域名" prop="domain" align="center" />
      <el-table-column label="所在地" prop="area" align="center" />
      <el-table-column label="创建时间" prop="created_at" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.tenantId !== 1">
          <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-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleAccountSet"
                icon="el-icon-setting"
                >账号设置</el-dropdown-item
              >
              <el-dropdown-item command="handleAuthMenu" icon="el-icon-user"
                >菜单权限</el-dropdown-item
              >
              <el-dropdown-item
                command="handleDataScope"
                icon="el-icon-circle-check"
                >基本权限</el-dropdown-item
              >
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                >重置密码</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="子系统名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入子系统名称" />
        </el-form-item>
        <el-form-item label="ip地址:" prop="ip">
          <el-input
            v-model="form.ip"
            placeholder="请输入ip地址"
            :disabled="form.id ? true : false"
          />
        </el-form-item>
        <el-form-item label="域名:" prop="domain">
          <el-input
            v-model="form.domain"
            placeholder="请输入域名"
            :disabled="form.id ? true : false"
          />
        </el-form-item>
        <el-form-item label="所在地:" required>
          <el-row type="flex" justify="space-between">
            <el-col :span="11">
              <el-form-item prop="province">
                <el-select
                  v-model="form.province"
                  clearable
                  placeholder="请选择"
                  @change="provinceCodeChange"
                >
                  <el-option
                    v-for="(key, value) in provinceSelectList"
                    :key="value"
                    :label="key"
                    :value="value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item prop="city">
                <el-select v-model="form.city" clearable placeholder="请选择">
                  <el-option
                    v-for="(key, value) in citySelectList"
                    :key="value"
                    :label="key"
                    :value="value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="姓名:" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="负责人电话:" prop="contact_mobile">
          <el-input
            v-model="form.contact_mobile"
            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="menuTitle"
      :visible.sync="openMenuScope"
      width="500px"
      append-to-body
    >
      <el-form :model="menuForm" label-width="100px">
        <el-form-item label="子系统名称">
          <el-input v-model="menuForm.name" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            default-expand-all
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMenuScope">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 账号设置 -->
    <el-dialog title="账号设置" :visible.sync="memberOpen" width="500px">
      <el-form
        ref="memberForm"
        :model="memberForm"
        :rules="memberRules"
        label-width="100px"
      >
        <el-form-item label="登陆账号:" prop="mobile">
          <el-input v-model="memberForm.mobile" placeholder="请输入登陆账号" />
        </el-form-item>
        <el-form-item label="登录密码:" prop="password">
          <el-input
            v-model="memberForm.password"
            placeholder="请输入登录密码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMemberForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  tenant,
  tenantAdd,
  tenantEdit,
  tenantDelete,
  tenantMember,
  tenantMemberBind,
  tenantMenuList,
  tenantMenuBind,
  tenantAuthList,
  tenantAuthBind,
} from "@/api/subPlatform/tenant";
import { areaList } from "@/api/config";
import { resetUserPwd } from "@/api/system/user";
export default {
  data() {
    var validateIp = (rule, value, callback) => {
      if (value === "" || typeof value === "undefined" || value == null) {
        callback(new Error("请输入正确的IP地址"));
      } else {
        const reg =
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
        if (!reg.test(value) && value !== "") {
          callback(new Error("请输入正确的IP地址"));
        } else {
          callback();
        }
      }
    };
    return {
      loading: true,
      showSearch: true,
      queryParams: {
        name: undefined,
        page_num: 1,
        page_size: 10,
      },
      total: 0,
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      provinceSelectList: [],
      citySelectList: [],
      // 表单参数
      form: {},
      // 账号设置弹窗
      memberOpen: false,
      // 是否显示弹出层（菜单权限）
      openMenuScope: false,
      menuTitle: "",
      menuForm: {},
      // 菜单列表
      menuOptions: [],
      // 是否为菜单权限弹窗和基本权限弹窗
      tenantFlag: true,
      defaultProps: {
        children: "children",
        label: "name",
      },
      memberForm: {
        mobile: undefined,
        password: undefined,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "子系统名称不能为空", trigger: "blur" },
        ],
        ip: [
          {
            required: true,
            message: "请输入正确的IP地址",
            validator: validateIp,
            trigger: "blur",
          },
        ],
        domain: [{ required: true, message: "域名不能为空", trigger: "blur" }],
        province: [
          {
            required: true,
            message: "省不能为空",
            trigger: ["blur", "change"],
          },
        ],
        city: [
          {
            required: true,
            message: "市不能为空",
            trigger: ["blur", "change"],
          },
        ],
        contact: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        contact_mobile: [
          { required: true, message: "负责人电话不能为空", trigger: "blur" },
        ],
      },
      memberRules: {
        mobile: [
          { required: true, message: "登陆账号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "登录密码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.page_num = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      tenant(this.queryParams).then((res) => {
        this.tenantList = res.data.data;
        this.total = res.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.memberOpen = false;
      this.openMenuScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        ip: undefined,
        domain: undefined,
        province: "",
        city: "",
        contact: undefined,
        contact_mobile: undefined,
      };
      this.resetForm("form");
    },
    getProvinceByParent(id) {
      return new Promise((resolve, reject) => {
        areaList({ code: id })
          .then(({ code, msg, data }) => {
            if (code == 200) {
              resolve(data);
            } else {
              this.$message.error(msg);
              reject({ msg, code });
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async provinceCodeChange(id) {
      delete this.form.city;
      if (!id) {
        this.citySelectList = [];
        return false;
      }
      this.citySelectList = await this.getProvinceByParent(id);
    },
    getCityList() {
      areaList().then((res) => {
        this.provinceSelectList = res.data;
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子系统";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await this.provinceCodeChange(row.province);
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改子系统";
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleAccountSet":
          this.handleAccountSet(row);
          break;
        case "handleAuthMenu":
          this.tenantFlag = true;
          this.handleAuthMenu(row);
          break;
        case "handleDataScope":
          this.tenantFlag = false;
          this.handleAuthMenu(row);
          break;
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        default:
          break;
      }
    },
    handleAccountSet(row) {
      tenantMember({ tenant_id: row.id }).then((res) => {
        if (res.data.id) {
          this.$modal.msgError("您已添加过账号信息，请勿重复添加");
        } else {
          this.memberOpen = true;
          this.memberForm["tenant_id"] = row.id;
        }
      });
    },
    /** 菜单权限操作 */
    handleAuthMenu: function (row) {
      this.menuForm = Object.assign({}, row);
      this.openMenuScope = true;
      if (this.tenantFlag) {
        tenantMenuList({ tenant_id: row.id }).then((res) => {
          this.menuOptions = res.data;
          const checkedKeys = [];
          this.filterSetChecked(res.data, "checked", checkedKeys);
          this.$refs.menu.setCheckedKeys(checkedKeys);
        });
        this.menuTitle = "分配菜单权限";
      } else {
        tenantAuthList({ tenant_id: row.id }).then((res) => {
          console.log(res);
          this.menuOptions = res.data;
          const checkedKeys = [];
          this.filterSetChecked(res.data, "checked", checkedKeys);
          this.$refs.menu.setCheckedKeys(checkedKeys);
        });
        this.menuTitle = "分配基本权限";
      }
    },
    filterSetChecked(data, field, out) {
      data.map((item) => {
        if (item[field]) {
          out.push(item.id);
        }
        if (item.children.length) {
          this.filterSetChecked(item.children, field, out);
        }
      });
    },
    /** 提交按钮（菜单权限） */
    submitMenuScope: function () {
      if (this.menuForm.id) {
        if (this.tenantFlag) {
          tenantMenuBind({
            tenant_id: this.menuForm.id,
            menu_ids: this.$refs.menu.getCheckedKeys(),
          }).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.openMenuScope = false;
            this.getList();
          });
        } else {
          // Todo...
          // tenantAuthBind
          console.log("提交基本权限");
        }
      }
    },
    // 重置密码按钮操作
    handleResetPwd(row) {
      this.$prompt('请输入子系统名称为"' + row.name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd({ id: row.id, password: this.md5(value) }).then(
            (response) => {
              this.$modal.msgSuccess("修改成功，新密码是：" + value);
            }
          );
        })
        .catch(() => {});
    },
    /** 提交按钮 - 修改名称普通数据 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            tenantEdit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            tenantAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitMemberForm() {
      this.$refs["memberForm"].validate((valid) => {
        if (valid) {
          const memberForm = Object.assign({}, this.memberForm);
          memberForm.password = this.md5(this.memberForm.password);
          tenantMemberBind(memberForm).then((res) => {
            this.$modal.msgSuccess("设置成功");
            this.memberOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除子系统名为"' + row.name + '"的数据项？')
        .then(function () {
          return tenantDelete({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
  created() {
    this.getList();
    this.getCityList();
  },
};
</script>