<template>
  <div>
    <MOSTY.PageTree :pageTitle="'用户管理'" :isShowLeftTree="false">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" isEnterSubmit @submit="handleFilter" />
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="addUserHander" :disabled="addDisabled">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <div class="main-box">
          <div class="treeBox">
            <MOSTY.DepartmentTree width="330px" placeholder="管理部门ID" clearable filterable v-model="listQuery.deptId"
              @getdeptData="getdeptData" />
          </div>
          <div class="tabBox ml10" style="height: calc(100vh - 380px)">
            <el-table :data="tableData" border stripe style="width: 100%" :height="'100%'" :key="keyCount"
              v-loading="loading">
              <el-table-column width="60" label="标记" #default="scope">
                <p style=" width: 12px; height: 12px;border-radius: 50%;margin: 0 auto"
                  :style="{ 'background-color': tableData[scope.$index].sign ? '#33CC00' : '#FC5F76' }"></p>
              </el-table-column>
              <el-table-column sortable prop="userName" align="center" label="用户名"></el-table-column>
              <el-table-column sortable prop="loginName" align="center" label="账号"></el-table-column>
              <el-table-column sortable prop="ssdwmc" align="center" label="所属单位"></el-table-column>
              <el-table-column sortable prop="deptName" label="所属部门"></el-table-column>
              <!-- <el-table-column sortable prop="idEntityCard" align="center" label="身份证号"></el-table-column>d -->
              <!-- <el-table-column sortable prop="mobile" align="center" label="电话号码"></el-table-column> -->
              <el-table-column align="center" sortable label="性别" width="80">
                <!-- <template #default="{ row }">
                  <dict-tag :options="D_BZ_XB" :value="row.sex" :tag="false" />
                </template> -->
                <template #default="{ row }">
                  <span>{{ row.sex === '1' ? '男' : '女' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" fixed="right" width="300">
                <template #default="{ row }">
                  <el-button @click="updateDict(row)" size="small">修改</el-button>
                  <el-dropdown style="margin-left: 12px; margin-right: 12px" @command="dropdownAction">
                    <el-button style="" size="small" @click="handleClick">
                      更多
                      <el-icon class="el-icon--right">
                        <arrow-down />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="getItem('USERID') == '000000'"
                          :command="commandValue('assignRoles', row)">分配角色
                        </el-dropdown-item>
                        <el-dropdown-item :command="commandValue('restPwd', row)">重置密码</el-dropdown-item>
                        <el-dropdown-item :command="commandValue('updatePwd', row)">修改密码</el-dropdown-item>
                        <el-dropdown-item v-if="getItem('USERID') == '000000'"
                          :command="commandValue('seedatePwd', row)">查看密码
                        </el-dropdown-item>
                        <el-dropdown-item v-if="getItem('USERID') == '000000'"
                          :command="commandValue('unbindQW', row)">解绑企业微信
                        </el-dropdown-item>
                        <el-dropdown-item v-if="getItem('USERID') == '000000'"
                          :command="commandValue('editLev', row)">修改层级
                        </el-dropdown-item>

                        <!-- <el-dropdown-item @click="Functionalhandel(row)">APP功能权限</el-dropdown-item> -->
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
<!--                  <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"-->
<!--                    @confirm="delRole(row)">-->
<!--                    <template #reference>-->
<!--                      <el-button type="danger" size="small">删除</el-button>-->
<!--                    </template>-->
<!--                  </el-popconfirm>-->
                  <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要移出?"
                                 @confirm="unEnableRole(row)">
                    <template #reference>
                      <el-button type="danger" size="small">移出</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
            <div class="fenye">
              <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="listQuery.pageNum" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
                layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
            </div>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>

    <!-- 弹窗 -->
    <div v-if="dialogFormVisible" class="dialog">
      <MOSTY.FromPage :title="isEdit ? '修改' : '新增'" @closeDialog="closeDialog">
        <template #content>
          <el-form class="mosty-from-wrap" ref="elform" :model="dialogForm" :inline="true" label-position="top"
            :rules="rules">
            <!-- <el-form-item label="部门:" prop="deptIds">
              <MOSTY.Department style="width: 100%" :searchType="'01'" placeholder="请选择部门" clearable :deptType="'01'"
                v-model="dialogForm.deptIds" :isEditDisabled="isEdit" @change="detpChange" />
            </el-form-item> -->
            <el-form-item label="部门:" prop="deptIds">
              <MOSTY.Department style="width: 100%" :searchType="'01'" placeholder="请选择部门" clearable :deptType="'01'"
                v-model="dialogForm.deptIds" :isEditDisabled="isEditDept" @change="detpChange" />
            </el-form-item>
            <el-form-item label="聘用人员类别:" prop="outsourcingLevel">
              <MOSTY.DictRidioAndSelect v-if="isEdit" selectType="select" :dictData="D_BZ_ZYWHRYLB"
                v-model="dialogForm.outsourcingLevel" />
              <MOSTY.DictRidioAndSelect v-else selectType="select" :dictData="D_BZ_ZYWHRYLB"
                v-model="dialogForm.outsourcingLevel" :disabledItem="isInvestmentCompany ? [] : ['3']" />
              <!-- <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_BZ_ZYWHRYLB"
                v-model="dialogForm.outsourcingLevel" :disabledItem="isInvestmentCompany ? [] : ['2', '3']" /> -->
            </el-form-item>
            <el-form-item label="岗位:" prop="positionName">
              <el-input v-model="dialogForm.positionName" readonly placeholder="请选择岗位"
                @click="showGwxz = true"></el-input>
            </el-form-item>
            <el-form-item label="职务:" prop="dutyName" v-if="dialogForm.outsourcingLevel == '1'">
              <el-input v-model="dialogForm.dutyName" readonly placeholder="请选择职务" @click="showZwxz = true"></el-input>
            </el-form-item>
            <el-form-item label="用户名:" prop="userName">
              <MOSTY.Other width="100%" placeholder="请输入用户名" clearable v-model="dialogForm.userName" />
            </el-form-item>
            <el-form-item label="登录账号:" prop="loginName">
              <el-input placeholder="请输入账号" v-model="dialogForm.loginName" type='text' clearable
                width="100%"></el-input>
            </el-form-item>
            <el-form-item label="密码:" v-if="!isEdit" prop="password">
              <el-input v-model="dialogForm.password" width="100%" @input="handleInput" placeholder="请输入密码">
                <template #append>
                  <el-icon>
                    <View />
                  </el-icon>
                </template>
              </el-input>
              <div class="input_span">
                <span
                  :style="{ 'background-color': (msgText > 1 || msgText == 1) ? '#FC5F76' : '#BBBBBB', 'color': (msgText > 1 || msgText == 1) ? '#FC5F76' : '#BBBBBB' }">弱</span>
                <span
                  :style="{ 'background-color': (msgText > 2 || msgText == 2) ? '#FF9900' : '#BBBBBB', 'color': (msgText > 2 || msgText == 2) ? '#FF9900' : '#BBBBBB' }">中</span>
                <span
                  :style="{ 'background-color': (msgText > 3 || msgText == 3) ? '#33CC00' : '#BBBBBB', 'color': (msgText > 3 || msgText == 3) ? '#33CC00' : '#BBBBBB' }">强</span>
              </div>
            </el-form-item>
            <el-form-item label="身份证号">
              <MOSTY.IdentityCard width="100%" v-model="dialogForm.idEntityCard" @change="fn" clearable>
              </MOSTY.IdentityCard>
            </el-form-item>
            <el-form-item label="用户类型:" prop="userType">
              <MOSTY.DictRidioAndSelect selectType="select" :dictData="D_ORG_USERTYPE" v-model="dialogForm.userType"
                placeholder="请选择用户类型" />
            </el-form-item>
            <el-form-item label="电话号码:" prop="telePhone">
              <MaskInput v-model="dialogForm.telePhone" placeholder="请输入电话号码" style="width: 337px" />
            </el-form-item>
            <el-form-item label="移动电话:" prop="mobile">
              <MaskInput v-model="dialogForm.mobile" placeholder="请输入移动电话" style="width: 337px" />
            </el-form-item>
            <el-form-item label="民族:" prop="nation">
              <MOSTY.PackageSelect v-model="dialogForm.nation" dictEnum="NATION" clearable filterable
                style="width: 100%" />
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_XB" v-model="dialogForm.sex" selectType="select"
                placeholder="请选择性别" />
            </el-form-item>
            <el-form-item label="文化程度:" prop="whcd">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYWHCD" v-model="dialogForm.whcd" selectType="select"
                placeholder="请选择文化程度" />
            </el-form-item>
            <el-form-item label="E-mail" prop="email">
              <el-input v-model="dialogForm.email" clearable />
            </el-form-item>
            <el-form-item label="出生日期：">
              <el-date-picker v-model="dialogForm.birthday" style="width: 100%" type="data" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择出生日期" :default-value="getDefaultDates"
                :disabled-date="disabledDate">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="政治面貌:" prop="politic">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYZZMM" v-model="dialogForm.politic" selectType="select"
                placeholder="请选择政治面貌" />
            </el-form-item>
            <el-form-item label="婚姻状况:" prop="marital">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_HYZK" v-model="dialogForm.marital" selectType="select"
                placeholder="请选择婚姻状况" />
            </el-form-item>
            <!-- <el-form-item label="人员类别:">
              <MOSTY.DictRidioAndSelect :dictData="D_ZDY_RYLB" v-model="dialogForm.type" selectType="select"
                placeholder="请选择人员类别" />
            </el-form-item> -->
            <el-form-item label="是否长期病假离岗人员:">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="dialogForm.longTermSickLeave" selectType="select"
                placeholder="请选择是否长期病假离岗人员" />
            </el-form-item>
            <el-form-item label="排序:">
              <el-input v-model="dialogForm.userNo" type="number"></el-input>
            </el-form-item>
            <el-form-item style="width: 100%" label="备注">
              <el-input v-model="dialogForm.bz" show-word-limit maxlength="200" :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </template>
        <template #footer>

          <!-- 修改 -->
          <el-button v-if="isEdit" type="primary" @click="onSave" :loading="buttonLoading">修改</el-button>
          <!-- 新增 -->
          <el-button v-else type="primary" @click="onAdd">保存</el-button>
          <el-button @click="closeDialog">关闭</el-button>
        </template>
      </MOSTY.FromPage>


    </div>
    <!-- 角色 -->
    <RolesDialog v-model="roleDialogVisible" :userId="currentUserId" @updateRole="handleFilter"></RolesDialog>
    <!-- 权限分配 -->
    <Functional v-model="FunctionalDialogVisible" :userid="currentRowFc.id" @close="close"></Functional>
    <!-- 岗位选择 -->
    <Gwxz v-model="showGwxz" @change="changeGwxz" />
    <!-- 职位选择 -->
    <Zwxz v-model="showZwxz" :isOrglevel="isOrglevel" @change="changeZwxz" />
    <!-- 修改密码 -->
    <updatePwd v-if="UpdatePwdVisible" v-model="UpdatePwdVisible" :userId="userId" :type="types"></updatePwd>
    <!-- 编辑层级 -->
    <editLev ref="editLevRef" @close="editLevClose" />
  </div>
</template>

<script setup>
import Gwxz from "@/views/systemConfig/user-list/components/Gwxz.vue"
import Zwxz from "@/views/systemConfig/user-list/components/Zwxz.vue"
import updatePwd from "./components/updatePwd.vue"
import * as MOSTY from "@/components/MyComponents/index"
import { ElMessage } from "element-plus"
import { filterqx } from "@/utils/auth.js"
import * as rule from "@/utils/rules.js"
import { getItem } from "@/utils/storage"
import { ref, watch, onMounted, getCurrentInstance, onUnmounted, reactive, computed } from "vue"
import RolesDialog from "./components/roles.vue"
import Functional from "./components/Functional.vue"
import { getSysUserList, editSysUser, addUser, getUserInfoToId, resetPassword, deleteSysUser, unEnableSysUser } from "@/api/user-manage"
import { arrayFiltering } from "@/utils/tools"
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessageBox } from "element-plus";
import editLev from "./components/editLev.vue"
import MaskInput from "@/components/MaskInput.vue"

const { proxy } = getCurrentInstance()
const {
  D_BZ_SF,
  D_BZ_XB,
  D_ZDY_XNYH,
  D_ZDY_RYLB,
  D_BZ_HYZK,
  D_BZ_AQRYZZMM,
  D_ORG_USERTYPE,
  D_BZ_ZYWHRYLB,
  D_BZ_AQRYWHCD
} =
  proxy.$dict("D_BZ_SF", "D_BZ_XB", "D_ZDY_XNYH", "D_ZDY_RYLB", "D_BZ_HYZK", "D_BZ_AQRYZZMM", "D_ORG_USERTYPE", "D_BZ_ZYWHRYLB", "D_BZ_AQRYWHCD")
const showZwxz = ref(false)
const showGwxz = ref(false)
const UpdatePwdVisible = ref(false)
const keyCount = ref(0) //tabel组件刷新值
const loading = ref(false)
const types = ref("01")
const deptId = ref(getItem("deptId") || {})

const searchArr = reactive([
  {
    showType: "input",
    label: "用户名:",
    prop: "loginName",
    width: "250px",
    placeholder: "请输入用户名或者账号"
  }
])
const editLevRef = ref({})
const rules = ref({
  userName: [{ required: true, message: "请填写用户名" }],
  loginName: [{ required: true, message: "请填写登录账号" }],
  userType: [{ required: true, message: "请选择用户类型" }],
  sex: [{ required: true, message: "请选择性别" }],
  // birthday: [{ required: true, message: "请选择出生日期" }],
  password: [{ required: true, message: "请填写密码" }],
  deptIds: [{ required: true, message: "请选择部门" }],
  inDustRialId: [{ required: true, message: "请填写警号" }],
  managerOrgId: [{ required: true, message: "请选择岗位" }],
  isVirtualUser: [{ required: true, message: "请选择虚拟用户" }],
  outsourcingLevel: [{ required: true, message: "请选择聘用人员类别" }],
  telePhone: [{ required: false, max: 13, message: "电话号码格式不正确", trigger: "blur" }],
  mobile: [{ required: false, max: 11, message: "移动电话格式不正确", trigger: "blur" }],
  // ...rule.identityCardRule({ require: false, validator: false }, "idEntityCard"),
  // ...rule.phoneRule({ validator: true, require: false, text: '电话号码', type: '02' }, "telePhone"),
  // ...rule.phoneRule({ validator: true, require: true, text: '移动电话' }, "mobile"),
  // ...rule.phoneRule({ validator: true, require: true, text: '移动电话' }, "mobile"),
  ...rule.emailRule({ validator: true, require: false }, "email"),
  type: [{ required: true, message: "请输入人员类别" }],
  dutyName: [{ required: true, message: "请选择职务" }],
  positionName: [{ required: true, message: "请选择岗位" }],
  packageSelect: [{ required: true, message: "请选择", trigger: "change" }],
  other: [{ required: true, message: "自由发挥", trigger: "blur" }],
  ...rule.numberzzsRule({ validator: true, require: false, num: 999 }, "userNo")
})
/** 获取数据标记字断 */
let signArr = ["deptName", "outsourcingLevel", "positionName", "dutyName", "userName", "loginName", "userType", "sex"]


const elform = ref(null)
const buttonLoading = ref(false)
const userId = ref("")
//查询参数
const total = ref(0)
const listQuery = ref({
  pageNum: 1,
  pageSize: 20,
  loginName: "",
  phone: ""
})
const isEdit = ref(true)
const dialogForm = ref({
  userName: "",
  deptIds: [],
  outsourcingLevel: "1"// 定死为“在册在岗”
})
const detpChange = (val) => {
  if (dialogForm.value.outsourcingLevel == '2') dialogForm.value.outsourcingLevel = ''
}
/** 是否投资公司 */
const isInvestmentCompany = computed(() => {
  let deptIds = dialogForm.value?.deptIds
  if (Array.isArray(deptIds)) deptIds = deptIds[deptIds.length - 1]
  return deptIds?.length && deptIds?.indexOf('5213') === 0
})
const msgText = ref("")
// 数据相关
const tableData = ref([])
const dialogFormVisible = ref(false)
onMounted(() => {
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data
  })
})
function handleInput(val) {
  if (/[\u4e00-\u9fa5]/.test(val)) {
    // 密码中包含中文
    ElMessage.error("密码不符合要求")
  } else {
    const sz = /[0-9]/.test(val)//数字
    const xx = /[a-z]/.test(val)//小写
    const dx = /[A-Z]/.test(val)//大写
    const tszf = /\W/.test(val)//特殊字符
    const Isarr = [sz, xx, dx, tszf].filter(item => {
      return item == true
    })
    const strongRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,}$/
    if (strongRegex.test(val) || Isarr.length >= 3) {
      msgText.value = 3
    } else if (Isarr.length >= 2) {
      msgText.value = 2
    } else {
      msgText.value = 1
    }
  }
}

//选择岗位
const changeGwxz = (val) => {
  dialogForm.value.positionId = val.id
  dialogForm.value.positionName = val.name
  showGwxz.value = false
}
//选择职务
const changeZwxz = (val) => {
  dialogForm.value.dutyCode = val.dutyCode
  dialogForm.value.dutyName = val.dutyName
  showZwxz.value = false
}
/** 是否标红（有必填项未填写） */
const isSomeEmty = (row) => {
  const isEmpty = (val) => {
    return val === null || val === undefined || val === ''
  }
  let signArray = signArr.slice()
  // 劳务派遣人员 没有 【职务】
  if (row?.outsourcingLevel == '2') {
    signArray = signArr.filter(item => item !== 'dutyName')
  }
  return signArray.some(item => {
    return isEmpty(row[item])
  })
}
// 获取数据的方法
const getListData = async () => {
  loading.value = true
  const params = listQuery.value
  const res = await getSysUserList(params).finally(() => {
    loading.value = false
  })
  // if (res && res.records) {
  //   res.records.forEach(item => {
  //     if (item.idEntityCard && item.idEntityCard.length >= 2) {
  //       item.sex = Number(item.idEntityCard.substring(item.idEntityCard.length - 2, item.idEntityCard.length - 1)) % 2 == 0 ? "2" : "1"
  //     } else {
  //       item.sex = item.sex ? item.sex : "1"
  //     }
  //   })
  // }

  // tableData.value = res?.records
  tableData.value = res?.records.map(item => {
    return {
      ...item,
      sign: !isSomeEmty(item)
    }
  })
  total.value = Number(res.total)

  // console.log('表格数据')
  // console.log(tableData.value)
}


const handleFilter = (obj) => {
  if (obj) {
    listQuery.value.loginName = obj.loginName ? obj.loginName : null
  }
  listQuery.value.pageNum = 1
  getListData()
}
const handleSizeChange = (currentSize) => {
  listQuery.value.pageSize = currentSize
  getListData()
}
const handleCurrentChange = (currentPage) => {
  listQuery.value.pageNum = currentPage
  getListData()
}
/**修改字典 */
const updateDict = async (row) => {
  getUserInfoToId(row.id).then((res) => {
    dialogForm.value = res
    dialogForm.value.loginName = res.loginName
    dialogForm.value.nation = res.nation
    dialogForm.value.isVirtualUser = res.isVirtualUser
    let orgLevel = JSON.parse(window.localStorage.getItem("deptId")).orgLevel.substring(0, 1)
    // if (res.idEntityCard && res.idEntityCard.length >= 2) {
    //   dialogForm.value.sex = Number(res.idEntityCard.substring(res.idEntityCard.length - 2, res.idEntityCard.length - 1)) % 2 == 0 ? "2" : "1"
    // } else {
    //   dialogForm.value.sex = dialogForm.value.sex ? dialogForm.value.sex : "1"
    // }
    if (orgLevel == "1") {
      //省
      dialogForm.value.deptIds = res.deptPath
    } else if (orgLevel == "2") {
      //市
      let depid = res.deptIds.toString().substring(0, 4)
      dialogForm.value.deptIds = res.deptPath.filter((item) => {
        return depid == item.substring(0, 4)
      })
    } else {
      // 县
      if (filterqx("isaqbm") == "1") {
        // let depid = res.deptIds.toString().substring(0, 5)
        let depid = getItem("deptId").ssdwid
        const index = res.deptPath.findIndex(item => item == depid)
        if (index >= 0) {
          dialogForm.value.deptIds = res.deptPath.slice(index)
        }

        // dialogForm.value.deptIds = res.deptPath.filter((item) => {
        //   return depid == item.substring(0, 5)
        // })
      } else {
        dialogForm.value.deptIds = res.deptIds
      }
    }
    console.log(dialogForm.value.deptIds)
    isOrglevel.value = ''
    isEdit.value = true
    isEditDept.value = false
    dialogFormVisible.value = true
  })
}

//身份证号计算出生日期
function getBirthdayFromIdCard(idCard) {
  var birthday = ""
  if (idCard != null && idCard != "") {
    if (idCard.length == 15) {
      birthday = "19" + idCard.substr(6, 6)
    } else if (idCard.length == 18) {
      birthday = idCard.substr(6, 8)
    }
    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-")
  }
  return birthday
}

function fn(e) {
  // let text = 0
  // if (e.length >= 17) {
  //   dialogForm.value.birthday = getBirthdayFromIdCard(e)
  //   text = e[e.length - 2] * 1
  //   if (text % 2 === 0) {
  //     dialogForm.value.sex = "2"
  //   } else {
  //     dialogForm.value.sex = "1"
  //   }
  // }
}
const unbindQW = (row) => {
  ElMessageBox.confirm(
    '确定解绑企业微信?',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      getApi({}, `/mosty-base/sysUser/unbindQW?id=${row.id}`).then(res => {
        console.log(res, 'res');
        ElMessage({
          type: 'success',
          message: '解绑企业微信成功！',
        })
      })
    }).catch(() => {
    })

}
/** 编辑层级弹框关闭，备用 */
const editLevClose = () => {
}
const editLevClick = (row) => {
  editLevRef.value?.open?.(row)
}
const commandValue = (type, command) => {
  return {
    type: type,
    command: command
  }
}
const dropdownAction = (item) => {
  const { type, command } = item
  if (type === "assignRoles") {
    assignRoles(command)
  } else if (type === "restPwd") {
    proxy.$modal.confirm("确认要重置密码？")
      .then(() => {
        restPwd(command)
      })
      .catch(() => {
        // catch error
      })

  } else if (type == "updatePwd") {
    updatePwds(command)
  } else if (type == "seedatePwd") {
    seedatePwds(command)
  } else if (type == "unbindQW") {
    unbindQW(command)
  } else if (type == 'editLev') {
    editLevClick(command)
  }
}
const isEditDept = ref(false)
const addUserHander = () => {
  isEdit.value = false
  dialogForm.value = {}
  dialogForm.value.loginName = null
  dialogForm.value.password = null
  dialogForm.value.outsourcingLevel = "1"
  isEditDept.value = true
  addDeptData()
  dialogFormVisible.value = true
}
const onSave = () => {
  elform.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true
      if (typeof dialogForm.value.deptIds == "string") {
        dialogForm.value.deptIds = dialogForm.value.deptIds.split(",")
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      } else if (Array.isArray(dialogForm.value.deptIds)) {
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      }
      dialogForm.value.deptIds = [dialogForm.value.deptIds]
      editSysUser(dialogForm.value).then(() => {
        dialogFormVisible.value = false
        ElMessage.success("修改成功")
        buttonLoading.value = false
        handleFilter()
      }).finally(() => {
        buttonLoading.value = false
      })
    } else {
      ElMessage.error("请填写完必填项!")
      return false
    }
  })
}
//新增人员
const onAdd = () => {
  elform.value.validate((valid) => {
    if (valid) {
      if (typeof dialogForm.value.deptIds == "string") {
        dialogForm.value.deptIds = dialogForm.value.deptIds.split(",")
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      } else if (Array.isArray(dialogForm.value.deptIds)) {
        dialogForm.value.deptIds = dialogForm.value.deptIds[dialogForm.value.deptIds.length - 1]
      }
      dialogForm.value.deptIds = [dialogForm.value.deptIds]
      buttonLoading.value = true
      if (dialogForm.value.password.length < 8) {
        ElMessage.error("密码长度不能低于8位")
      } else if (msgText.value != 3) {
        ElMessage.error("密码必须满足强密码要求!")
      } else {
        // 劳务派遣人员 没有 【职务】
        if (dialogForm.value.outsourcingLevel == '2') {
          delete dialogForm.value.dutyCode
          delete dialogForm.value.dutyName
        }
        console.log(dialogForm.value, 'dialogForm.value.')
        addUser(dialogForm.value).then((res) => {
          dialogFormVisible.value = false
          ElMessage.success("新增成功")
          handleFilter()
        }).finally(() => {
          dialogForm.value.deptIds = dialogForm.value.deptIds ? dialogForm.value.deptIds[0] : null
          buttonLoading.value = false
        })
      }

    } else {
      ElMessage.error("请填写完必填项!")
      return false
    }
  })
}

const delRole = (row) => {
  deleteSysUser({ id: row.id, type: "01" }).then(() => {
    ElMessage.success("删除成功")
    handleFilter()
  })
}

const unEnableRole = (row) => {
  unEnableSysUser({ id: row.id}).then(() => {
    ElMessage.success("停用成功")
    handleFilter()
  })
}

const closeDialog = () => {
  proxy.$modal.confirm("离开会丢失页面中修改的内容，确认离开吗？")
    .then(() => {
      dialogForm.value = {}
      dialogForm.value.loginName = null
      dialogForm.value.password = null
      dialogFormVisible.value = false
    })
    .catch(() => {
      // catch error
    })

}

//分配角色
const currentUserId = ref("")
const roleDialogVisible = ref(false)
const assignRoles = (row) => {
  roleDialogVisible.value = true
  currentUserId.value = row.id
}
const updatePwds = (row) => {
  types.value = "01"
  userId.value = row.id
  UpdatePwdVisible.value = true

}
const seedatePwds = (row) => {
  types.value = "02"
  userId.value = row.id
  UpdatePwdVisible.value = true
}
//分配功能
const currentRowFc = ref({})
const FunctionalDialogVisible = ref(false)
const Functionalhandel = (row) => {
  FunctionalDialogVisible.value = true
  currentRowFc.value = { ...row }
}
//弹窗关闭
const close = () => {
  FunctionalDialogVisible.value = false
  getListData()
}
const restPwd = (row) => {
  resetPassword({ userId: row.id }).then(() => {
    dialogFormVisible.value = false
    ElMessage.success("操作成功")
    handleFilter()
  })
}
const handleClick = (e) => {
}
// 新增控制
const addDisabled = ref(true)
const deptIdData = ref([])
const isOrglevel = ref('')
const levelFlag = ref(0)
const levelNum = ref(0)

// 计算树深度
function getTreeDepth(nodeOrArray, childrenKey = "children") {
  if (!nodeOrArray) return 0

  if (Array.isArray(nodeOrArray)) {
    if (nodeOrArray.length === 0) return 0
    return nodeOrArray.reduce((max, item) => {
      return Math.max(max, getTreeDepth(item, childrenKey))
    }, 0)
  }

  const children = nodeOrArray[childrenKey]
  if (!children || children.length === 0) return 1
  return 1 + children.reduce((max, child) => {
    return Math.max(max, getTreeDepth(child, childrenKey))
  }, 0)
}

// orglevel 对应的最大层级
function getMaxDepthByOrgLevel(orglevel) {
  switch (orglevel) {
    case "10": return 4
    case "20": return 3
    case "21": return 3
    case "30": return 2
    case "31": return 1
    default: return 0
  }
}

// 点击部门节点时触发
const getdeptData = (e) => {
  isOrglevel.value = ""
  console.log(e, '部门信息')
  if (e && e.orglevel.slice(-1) === "1") {
    if (e.orglevel === '41') {
      isOrglevel.value = e.orglevel
      deptIdData.value = []
      addDisabled.value = true
    } else {
      isOrglevel.value = e.orglevel
      addDisabled.value = false
      listQuery.value.deptId = listQuery.value.deptId ? listQuery.value.deptId : e.orgcode
    }
  } else {
    isOrglevel.value = e.orglevel
    deptIdData.value = []
    addDisabled.value = true
  }
  // 只在第一次点击时计算层级
  if (levelFlag.value === 0) {
    const depth = getTreeDepth(e)
    const maxAllowed = getMaxDepthByOrgLevel(e.orglevel)
    // 实际层级不能超过最大值
    levelNum.value = Math.min(depth, maxAllowed)
    levelFlag.value = 1
  }
}

const addDeptData = () => {
  getApi({}, `/mosty-base/deptFeign/getOrgById?id=${listQuery.value.deptId}`).then(res => {
    deptIdData.value = []
    deptIdData.value = res.rootPath.split("_")
    dialogForm.value.deptIds = deptIdData.value
    if (levelNum.value === 4) {
      //省公司
      dialogForm.value.deptIds = deptIdData.value
    } else if (levelNum.value === 3) {
      //市公司
      deptIdData.value.shift()
      dialogForm.value.deptIds = deptIdData.value
    } else if (levelNum.value === 2) {
      //县公司
      deptIdData.value.shift()
      deptIdData.value.shift()
      dialogForm.value.deptIds = deptIdData.value
    } else {
      // 县部门 市部门 省部分
      dialogForm.value.deptIds = [deptIdData.value[deptIdData.value.length - 1]]
    }
  })
}
//watch监听路由变化
watch(roleDialogVisible, (val) => {
  if (!val) currentUserId.value = ""
})

watch(
  () => listQuery.value.deptId,
  () => {
    handleFilter()
  },
  {
    immediate: true
  }
)


onUnmounted(() => {
  proxy.mittBus.off("mittFn")
})
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.treeBox {
  overflow: auto;
  height: calc(100vh - 330px);
}

::v-deep .el-form {
  flex-wrap: wrap;
}

.input_span {
  height: 8px;
  display: flex;
  float: right;
  width: 35%;

  span {
    display: inline-block;
    width: 30%;
    border-radius: 8px;
    margin-right: 3px;
    text-align: center;
    margin-top: 3px;
  }
}

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
