<template>
  <!-- 添加或修改项目信息对话框 -->
  <div class="el-drawer__wrapper">
    <el-drawer :title="title" v-model="visible" direction="rtl" size="100%">
      <div class="page-container form-container">
        <div class="form-btns-container">
          <span class="title-label"><el-icon>
              <Document />
            </el-icon>
            {{ tenant.accountName }} 企业初始化</span>
          <el-button-group>
            <el-button v-hasPermi="['business:tenant:edit']" type="primary" size="small" icon="Finished"
              @click="initHandler">开始初始化</el-button>
          </el-button-group>
          <div class="screen-btn" @click="handleScreen">
            <template v-if="!isFullscreen">
              <i class="fa fa-window-maximize" aria-hidden="true" />
              <!-- <span>全屏</span> -->
            </template>
            <template v-else>
              <i class="fa fa-window-restore" aria-hidden="true" />
              <!-- <span>还原</span> -->
            </template>
          </div>
          <div class="close-btn" @click="cancel">
            <i class="fa fa-times" aria-hidden="true" />
            <!-- <span>关闭</span> -->
          </div>
        </div>
        <div class="Y-scrollbar" style="position: absolute; top: 32px; bottom: 0; width: 100%; overflow: auto;"></div>
        <el-form ref="tenantRef" class="master-container" size="size" :model="form" :rules="rules" label-width="140px">
          <el-row :gutter="10">
            <el-col :span="24">
              <el-card class="card" style="margin-bottom: 10px">
                <template #header><span>初始化流程</span></template>
                <el-row :gutter="10">
                  <el-col :span="24">
                    <el-collapse>
                      <!-- <el-collapse-item name="0">
                        <template #title>
                          <el-checkbox v-model="vaildityStatus" />审核通过 <span
                            :style="{ color: checkAdminRole ? 'green' : 'red', paddingLeft: '10px' }">{{ checkAdminRole ?
                              '已初始化管理员角色' :
                              '未初始化管理员角色' }}</span>
                        </template>
                      </el-collapse-item> -->
                      <el-collapse-item name="1">
                        <template #title>
                          <el-checkbox v-model="initAdminRole" />初始化管理员角色
                          <span :style="{
      color: checkAdminRole ? 'green' : 'red',
      paddingLeft: '10px',
    }">{{
      checkAdminRole
        ? "已初始化管理员角色"
        : "未初始化管理员角色"
    }}</span>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item name="2">
                        <template #title>
                          <el-checkbox v-model="initAdminSysUser" />
                          初始化管理员
                          <span :style="{
      color: checkAdmin ? 'green' : 'red',
      paddingLeft: '10px',
    }">{{
      checkAdmin ? "已初始化管理员" : "未初始化管理员"
    }}
                          </span>
                        </template>
                        <template #default>
                          <el-form-item label="管理员账号">
                            <el-input v-model="admin.userName" placeholder="请输入账号" />
                          </el-form-item>
                          <el-form-item label="管理员昵称">
                            <el-input v-model="admin.nickName" placeholder="请输入" />
                          </el-form-item>
                          <el-form-item label="性别">
                            <el-select v-model="admin.gender" placeholder="请选择">
                              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                            </el-select>
                          </el-form-item>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item name="3">
                        <template #title>
                          <el-checkbox v-model="initDept" />
                          初始化默认部门
                          <span :style="{
      color: initDept ? 'green' : 'red',
      paddingLeft: '10px',
    }">{{
      initDept ? "已初始化默认部门" : "未初始化默认部门"
    }}
                          </span>
                        </template>
                        <template #default>
                          <el-form-item label="部门名称">
                            <el-input v-model="dept.deptName" placeholder="请输入账号" />
                          </el-form-item>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item name="4">
                        <template #title>
                          <el-checkbox v-model="roleInit" />初始化默认角色
                          <span :style="{
      color: checkRole ? 'green' : 'red',
      paddingLeft: '10px',
    }">{{
      checkRole
        ? "已初始化默认角色"
        : "未初始化默认角色"
    }}</span>
                        </template>
                        <template #default>
                          <el-row>
                            <el-col :span="8">
                              <el-table ref="roleRef" :data="roleList" border fit highlight-current-row
                                @row-click="rowClick" @selection-change="roleSelectionChange" size="small">
                                <el-table-column type="selection" width="55" />
                                <el-table-column type="index" width="50" />
                                <el-table-column label="角色名称" align="center" prop="roleName" />
                              </el-table>
                            </el-col>
                          </el-row>
                        </template>
                      </el-collapse-item>
                      <el-collapse-item name="5">
                        <template #title>
                          <el-checkbox v-model="sourceInit" />
                          初始化其他默认数据
                          <span :style="{
      color: checkSource ? 'green' : 'red',
      paddingLeft: '10px',
    }">{{
      checkSource
        ? "已初始化其他默认数据"
        : "未初始化其他默认数据"
    }}</span>
                        </template>
                        <template #default> </template>
                      </el-collapse-item>
                    </el-collapse>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script setup>
import { checkTenantInit, initTenant } from "@/api/business/tenant";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");
/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => { },
  },
});
const { getList } = toRefs(props);
/** 字典数组区 */
/** 表单抽屉 页变量 */
const title = ref("");
const loading = ref(false);
const multiple = ref(true);
const visible = ref(false);
const editStatus = ref(false);
const isFullscreen = ref(false);
const checkAdminRole = ref(false);
const checkAdmin = ref(false);
const checkRole = ref(false);
const initAdminRole = ref(false);
const initAdminSysUser = ref(false);
const initDept = ref(false);
const userInit = ref(false);
const sourceInit = ref(false);
const initRoles = ref([]);
const roleSelections = ref([]);
const roleList = ref([]);
const roleInit = ref(false);
const roleRef = ref(null);
const tenantId = ref(null);
const checkSource = ref(false);
const checkDept = ref(false);
const tenant = ref({});
const dept = ref({});

const versions = ref([]);
const admin = ref({});
const adminRole = ref({});
const userEmpty = {
  id: null,
  userName: "",
  nickName: "",
  gender: "男",
  tenantId: "",
};
const deptEmpty = {
  id: null,
  deptName: "",
};
const roleEmpty = {
  id: null,
  roleName: "",
  isInit: 1,
  editDisable: 0,
  roleSort: 2,
  status: 0,
};
const data = reactive({
  form: {},
  rules: {},
});
const { form, rules } = toRefs(data);
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(id) {
  reset();
  tenantId.value = id;
  visible.value = true;
  if (id) {
    checkTenantInit(id).then((res) => {
      console.log("res.data", res.data);
      checkAdminRole.value = res.data.checkAdminRole;
      checkAdmin.value = res.data.checkAdmin;
      admin.value = res.data.admin
        ? res.data.admin
        : JSON.parse(JSON.stringify(userEmpty));
      adminRole.value = res.data.adminRole
        ? res.data.adminRole
        : JSON.parse(JSON.stringify(roleEmpty));
      dept.value = res.data.initDept
        ? res.data.initDept
        : JSON.parse(JSON.stringify(deptEmpty));
      adminRole.value.roleName = "管理员";
      adminRole.value.roleKey = "tenantAdmin";
      adminRole.value.editDisable = "1";
      checkSource.value = res.data.checkSource;
      checkDept.value = res.data.checkDept;
      initRoles.value = res.data.initRoles ? res.data.initRoles : [];
      roleList.value = res.data.initRoleData;
      tenant.value = res.data.tenant;
      checkRole.value = res.data.checkRole;
      setRoleSelection(res.data.initRoles);
      // console.log(adminRole.value)
    });
  }
}

/** 取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {};
  checkAdmin.value = false;
  checkAdminRole.value = false;
  checkSource.value = false;
  checkRole.value = false;
  initAdminSysUser.value = false;
  initAdminRole.value = false;
  admin.value = {};
  initRoles.value = [];
  roleList.value = [];
  adminRole.value = {};
  roleSelections.value = [];
  tenant.value = {};
  initDept.value = {};
  roleInit.value = false;
  checkDept.value = false;
  proxy.resetForm("tenantRef");
}

/** 全屏缩放 */
function handleScreen() {
  const dom = document.querySelector(
    ".list-container > .el-drawer__wrapper > .el-overlay"
  );
  isFullscreen.value = !isFullscreen.value;
  dom.style.position = isFullscreen.value ? "fixed" : "absolute";
}

/** 提交按钮 */
function initHandler() {
  let initFlows = [];
  // 假设未创建管理员角色，单选中创建管理员却为选中创建管理员角色 则报错
  if (!checkAdminRole.value && !initAdminRole.value && initAdminSysUser.value) {
    proxy.$message.error("未初始化管理角色，不能初始化管理员");
    return;
  }
  if (initAdminSysUser.value && !admin.value.userName) {
    proxy.$message.error("请输入管理员名称");
    return;
  }
  if (roleInit.value && roleSelections.length === 0) {
    proxy.$message.error("请至少选择一个角色");
    return;
  }
  if (tenant.value.status <= 1) {
    const auditingTenant = {};
    auditingTenant.tenantId = tenantId.value;
    auditingTenant.flowName = "auditingTenant";
    initFlows.push(auditingTenant);
  }
  if (initAdminRole.value) {
    const adminRoleFlow = {};
    adminRoleFlow.tenantId = tenantId.value;
    adminRoleFlow.adminRole = adminRole.value;
    adminRoleFlow.flowName = "initAdminRole";
    initFlows.push(adminRoleFlow);
  }
  if (initAdminSysUser.value) {
    const adminFlow = {};
    adminFlow.tenantId = tenantId.value;
    adminFlow.admin = admin.value;
    adminFlow.adminRole = adminRole.value;
    adminFlow.flowName = "initAdminSysUser";
    initFlows.push(adminFlow);

    const adminAuthFlow = {};
    adminAuthFlow.tenantId = tenantId.value;
    adminAuthFlow.flowName = "initAdminAuth";
    initFlows.push(adminAuthFlow);
  }
  if (roleInit.value) {
    const roleInitFlow = {};
    roleInitFlow.tenantId = tenantId.value;
    roleInitFlow.initRoles = roleSelections.value;
    roleInitFlow.flowName = "initRoles";
    initFlows.push(roleInitFlow);
  }
  if (initDept.value) {
    const deptInitFlow = {};
    deptInitFlow.tenantId = tenantId.value;
    dept.value.deptName =
      dept.value.deptName.trim() == ""
        ? tenant.value.companyName
        : dept.value.deptName.trim();
    deptInitFlow.dept = dept.value;
    deptInitFlow.flowName = "initDept";
    initFlows.push(deptInitFlow);
  }
  if (sourceInit.value) {
    const sourceInitFlow = {
      tenantId: tenantId.value,
      flowName: "initSource",
    };
    initFlows.push(sourceInitFlow);
  }

  initTenant(initFlows).then((res) => {
    getList.value();
    cancel();
  });
}

/** 查询表单信息  */
function getForm() {
  loading.value = true;
  getTenant(form.value.id).then((response) => {
    loading.value = false;
    form.value = response.data;
  });
}
function setRoleSelection() {
  roleList.value.forEach((l) => {
    if (initRoles.value.findIndex((v) => l.initId === v.initId) >= 0) {
      roleRef.value.toggleRowSelection(l, true);
    } else {
      roleRef.value.toggleRowSelection(l, false);
    }
  });
}

function roleSelectionChange(selections) {
  roleSelections.value = selections;
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
