<template>
  <div class="page-wrapper role-add" style="overflow: auto">
    <div class="page-container">
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addFormRules"
        class="addForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-collapse
          :bordered="false"
          default-active-key="a"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  prop="userName"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :rules="[
                    {
                      required: true,
                      message: $t('PLACEENTER'),
                      trigger: 'blur',
                    },
                    {
                      max: 32,
                      required: true,
                      message: $t('PLACEENTER') + 32 + $t('LENGTH_TIP'),
                      trigger: 'blur',
                    },
                  ]"
                  :label="$t('USER_NAME')"
                >
                  <a-input
                    v-model="addForm.userName"
                    :placeholder="$t('PLACEENTER')"
                    disabled
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="password"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :label="$t('PASSWORD')"
                >
                  <a-input
                    id="b"
                    v-model="addForm.password"
                    type="password"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                    @focus="fourPassword"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="deptId"
                  :label="$t('DEPARTMENTCODE')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :rules="{
                    required: true,
                    message: $t('PLACEENTER'),
                    trigger: 'change',
                  }"
                >
                  <a-tree-select
                    v-model="addForm.deptId"
                    :replace-fields="treeProps"
                    tree-check-strictly
                    :tree-data="treeData"
                    allow-clear
                    @change="(val) => handChangeDep(val, true)"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  prop="name"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :rules="[
                    {
                      required: true,
                      message: $t('PLACEENTER'),
                      trigger: 'blur',
                    },
                    {
                      max: 64,
                      required: true,
                      message: $t('PLACEENTER') + 32 + $t('LENGTH_TIP'),
                      trigger: 'blur',
                    },
                  ]"
                  :label="$t('USER_REAL_NAME')"
                >
                  <a-input
                    v-model="addForm.name"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="sex"
                  :rules="{
                    required: true,
                    message: $t('PLACESELECT'),
                    trigger: 'blur',
                  }"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :label="$t('GENDER')"
                >
                  <a-radio-group v-model="addForm.sex">
                    <a-radio
                      v-for="(sex, index) in sexTypeList"
                      :key="index"
                      :value="sex.value"
                    >
                      {{ sex.label }}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="email"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :label="$t('EMAIL')"
                >
                  <a-input
                    v-model="addForm.email"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex">
              <a-col :span="8">
                <a-form-model-item
                  prop="workPhone"
                  :label="$t('WORK_PHONE')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                >
                  <a-input
                    v-model="addForm.workPhone"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="mobilePhone"
                  :label="$t('PHONE_NO')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                >
                  <a-input
                    v-model="addForm.mobilePhone"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  prop="wechatCorpUserId"
                  :label="$t('PERSONAL_ENTERPRISE_WECHAT')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                >
                  <a-input
                    v-model="addForm.wechatCorpUserId"
                    :placeholder="$t('PLACEENTER')"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex">
              <a-col :span="8">
                <a-form-model-item
                  prop="mgrType"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  :label="$t('USER_TYPE')"
                  :rules="[
                    {
                      required: true,
                      message: $t('PLACEENTER'),
                      trigger: 'blur',
                    },
                  ]"
                >
                  <a-select
                    v-model="addForm.mgrType"
                    show-search
                    allow-clear
                    :placeholder="$t('PLACEENTER')"
                  >
                    <a-select-option
                      v-for="item in typeList"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('WECHAT_OFFICIAL_ID')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  prop="openId"
                >
                  <a-input v-model="addForm.openId" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('REMARK')"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 12 }"
                  prop="remark"
                >
                  <a-input
                    v-model="addForm.remark"
                    type="textarea"
                    allow-clear
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          :bordered="false"
          default-active-key="b"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('RIGHT_INFO')">
            <a-row class="roleCodes">
              <a-col :span="24">
                <a-form-model-item
                  :label="$t('ROLE')"
                  prop="rolesIds"
                  style="width: 100%"
                  :label-col="{ span: 2 }"
                  :wrapper-col="{ span: 20 }"
                >
                  <!-- 选择角色 -->
                  <SelectRole
                    ref="selectRoleRef"
                    row-key="id"
                    style="position: relative"
                    :default-selected-rows="selectedRoleRows"
                    @confirm="getReturnData"
                  >
                    <!-- :class="item.disabled ? 'tagError' : ''" -->
                    <div class="tagInt">
                      <a-tag
                        v-for="(item, index) in selectedRoleRows"
                        :key="item.id"
                        :closable="!item.disabled"
                        @close="() => changeSelectedRoleRows(item, index)"
                      >
                        {{ item.roleName }}
                      </a-tag>
                    </div>
                  </SelectRole>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-tabs type="card">
              <a-tab-pane
                v-for="(item, index) in dataScope"
                :key="item.type"
                :tab="item.typeName"
              >
                <a-row
                  v-if="item.modeList && item.modeList.length"
                  class="roleCodes"
                >
                  <a-col :span="24">
                    <a-form-model-item
                      :label="$t('权限范围')"
                      :label-col="{ span: 2 }"
                      :wrapper-col="{ span: 20 }"
                    >
                      <a-select
                        show-search
                        :value="ranges[index]"
                        :placeholder="$t('PLACESELECT')"
                        @change="
                          (val) => changeAuthRange(val, index, item.modeList)
                        "
                      >
                        <a-select-option
                          v-for="d in item.modeList"
                          :key="d.key"
                          :value="d.key"
                          >{{ d.value }}</a-select-option
                        >
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row
                  v-if="item.dataList && item.dataList.length && displayTree"
                  class="roleCodes"
                >
                  <a-col :span="24">
                    <a-form-model-item
                      :label="$t('数据权限')"
                      :label-col="{ span: 2 }"
                      :wrapper-col="{ span: 20 }"
                    >
                      <div>
                        <a-checkbox
                          :checked="scopeAllChecked[index]"
                          @change="() => toggleAllSelected(index)"
                        >
                          {{ $t("ALL_SELECT") }}/{{ $t("UNSELECT_ALL") }}
                        </a-checkbox>
                        <a-checkbox
                          :checked="scopeUnfoldChecked[index]"
                          :disabled="
                            dataScopeIds[index].length === item.dataList.length
                          "
                          @change="
                            () => toggleUnfoldSelected(index, item.dataList)
                          "
                          >{{ $t("UNFOLD") }}/{{ $t("FOLD") }}</a-checkbox
                        >
                        <a-checkbox
                          :checked="item.parentLink"
                          :disabled="
                            dataScopeIds[index].length === item.dataList.length
                          "
                          @change="
                            () => toggleFatheerSelected(item.parentLink, index)
                          "
                          >{{ $t("FATHEER_SON_LINKAGE") }}</a-checkbox
                        >
                      </div>
                      <a-tree
                        :ref="'functionTree' + index"
                        :tree-data="item.dataList"
                        :replace-fields="{
                          children: 'children',
                          key: 'id',
                          value: 'id',
                          title: 'label',
                        }"
                        :check-strictly="!item.parentLink"
                        checkable
                        :checked-keys="leafScopeIds[index] || []"
                        :expanded-keys="expandScopeIds[index] || []"
                        @expand="
                          (checkedKeys, info) =>
                            handleNodeClick(
                              checkedKeys,
                              info,
                              index,
                              item.dataList
                            )
                        "
                        @check="
                          (checkedKeys, info) =>
                            handleTreeChecked(checkedKeys, info, index)
                        "
                      >
                      </a-tree>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-tab-pane>
            </a-tabs>
          </a-collapse-panel>
        </a-collapse>
        <!-- 扩展字段 -->
        {{
          fieldExRenderFn($createElement, "sys_user", {
            layout: "grid",
            itemSpan: 8,
          })
        }}
        <slot name="RenderFieldExtendDom"></slot>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <FieldExtend
        v-if="hasAuth('MODELING:MATERIEL:INFO:FIELD_AUTH')"
        :table-name-list="tableNameList"
        class="mr-2"
        @update="handleRefresh"
      />
      <FieldAuth
        v-if="hasAuth('MODELING:MATERIEL:INFO:FIELD_AUTH')"
        ref="FieldAuthComp"
        :table-name-list="tableNameList"
        class="mr-2"
        @update="handleRefresh"
      />
      <a-button type="primary" @click="confirm">
        <Icon type="icon-cur-save_1" :size="18" />
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <Icon type="icon-dir-f-rollback" :size="18" />
        {{ $t("CANCEL") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { validCellphone, validEmail, getLevelMark } from "@mega-apps/utils";
import { mapState } from "vuex";
import { uniqBy } from "lodash";
import { Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FieldMixin from "@/components/ExtendAndAuthField/mixin";
import SelectRole from "@/components/SelectRole";
import FieldExtend from "@/components/ExtendAndAuthField/Extend";
import FieldAuth from "@/components/ExtendAndAuthField/Auth";

export default {
  components: {
    SelectRole,
    FieldExtend,
    FieldAuth,
    Icon,
  },
  mixins: [FieldMixin],
  data() {
    return {
      plainOptions: [],
      selectedRoleRows: [], // 目前用户已拥有角色
      sexTypeList: [], // 性别列表
      checked: false,
      treeData: [], // 部门树
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      roleList: [],
      typeList: [], // 用户类型列表
      addForm: {
        userName: "", // 用户名
        mgrType: "USER", // 用户类型
        password: "******",
        lastName: "", // 姓
        firstName: "", // 名
        sex: "", // 性别
        mobilePhone: "", // 手机号码
        wechatCorpUserId: "", // 个人企业微信ID
        email: "", // 邮箱
        deptId: "", // 所属部门
        workPhone: "", // 办公电话
        openId: "", // 微信公众号ID
        remark: "",
        isSave: true,
        titleError: "",
        factType: "",
        selectedRowKeys: [],
        rolesIds: [],
      },
      dataAttr: {
        form: "addForm",
      },
      tableNameList: [
        {
          key: "sys_user",
          tab: "用户管理",
        },
      ],

      dataScope: [],
      // 权限树所有id集合
      dataScopeIds: [],
      // 权限范围
      ranges: [],
      // 菜单多颗树 选中的节点（半选和全选）每棵树的集合
      scopeIds: [],
      // 菜单多颗树 所有叶子节点 code 的集合
      leafScopeIds: [],
      // 全选集合
      scopeAllChecked: [],
      // 展开收起集合
      scopeUnfoldChecked: [],
      // 父子级联
      scopeFatheerChecked: [],
      // 需要展开的节点集合
      expandScopeIds: [],
      // 是否显示组织树
      displayTree: false,
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
    addFormRules() {
      return {
        password: [
          {
            validator: this.changePassword,
            trigger: "blur",
          },
        ],
        mobilePhone: [
          {
            validator: (rule, value, callback) => {
              if (value && !validCellphone(value)) {
                callback(new Error(this.$t("PHONE_FORMAT_ERROR")));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value && !validEmail(value)) {
                callback(new Error(this.$t("EMAIL_FORMAT_ERROR")));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      };
    },
  },
  async mounted() {
    // 扩展字段
    this.queryField();
    await this.initModuleTree();
  },
  methods: {
    // 切换全选状态
    toggleAllSelected(index) {
      if (this.scopeIds[index]?.length === this.dataScopeIds[index]?.length) {
        this.$set(this.scopeIds, index, []);
        this.$set(this.leafScopeIds, index, []);
      } else if (this.dataScope[index].parentLink) {
        this.$set(this.scopeIds, index, this.dataScopeIds[index]);
        const [leafArr] = this.getSelectedData(
          this.dataScope[index].dataList,
          this.dataScopeIds[index]
        );
        this.$set(this.leafScopeIds, index, leafArr);
      } else {
        this.$set(this.scopeIds, index, this.dataScopeIds[index]);
        this.$set(this.leafScopeIds, index, this.dataScopeIds[index]);
      }
      // 判断全选
      this.$set(
        this.scopeAllChecked,
        index,
        this.scopeIds[index]?.length === this.dataScopeIds[index]?.length
      );
    },
    // 切换展开和折叠状态
    toggleUnfoldSelected(index, list) {
      const arr = getLevelMark(list, "children", "id");
      if (this.expandScopeIds[index]?.length === arr?.length) {
        this.$set(this.scopeIds, index, []);
        this.$set(this.expandScopeIds, index, []);
      } else {
        this.$set(this.expandScopeIds, index, arr);
      }
      // 判断全部展开
      this.$set(
        this.scopeUnfoldChecked,
        index,
        this.expandScopeIds[index]?.length === arr?.length
      );
    },
    handleNodeClick(keys, info, index, list) {
      const arr = getLevelMark(list, "children", "id");
      this.$set(this.expandScopeIds, index, [].concat(keys));
      // 判断全部展开
      this.$set(
        this.scopeUnfoldChecked,
        index,
        this.expandScopeIds[index]?.length === arr?.length
      );
    },
    toggleFatheerSelected(val, index) {
      this.$set(this.dataScope[index], "parentLink", !val);
      if (this.scopeAllChecked[index]) {
        this.$set(this.leafScopeIds, index, this.dataScopeIds[index]);
      }
    },
    // 范围
    changeAuthRange(val, index, list) {
      const itemIndex = list.findIndex((item) => item.key === val);
      this.displayTree = list[itemIndex]?.displayTree;
      this.$set(this.ranges, index, val);
    },
    // 单颗树选中全数据 得到 树选中叶子节点和选中所有节点)
    getSelectedData(data, selected, leafArr = [], arr = []) {
      data.forEach((item) => {
        selected.includes(item.id) && arr.push(item.id);
        // eslint-disable-next-line
        item.key = item.id;
        // eslint-disable-next-line
        item.value = item.id;
        // eslint-disable-next-line
        item.title = this.$t(item.label);
        if (item?.children?.length) {
          this.getSelectedData(item.children, selected, leafArr, arr);
        } else if (selected.includes(item.id)) {
          leafArr.push(item.id);
        }
      });
      return [leafArr, arr];
    },
    // 菜单权限tree点击
    handleTreeChecked(checkedKeys, info, index) {
      // 树父子节点关联
      if (checkedKeys instanceof Array) {
        // 设置选中(全选和半选)数据
        this.$set(
          this.scopeIds,
          index,
          [].concat(checkedKeys).concat(info?.halfCheckedKeys || [])
        );
        // 页面菜单权限树结构的选中数据(只有叶子节点id)
        const [leafArr] = this.getSelectedData(
          this.dataScope[index].dataList,
          this.scopeIds[index]
        );
        this.$set(this.leafScopeIds, index, leafArr);
      } else {
        // 树父子节点非关联
        const { checked } = checkedKeys;
        // 设置选中(全选和半选)数据
        this.$set(this.scopeIds, index, [].concat(checked));
        this.$set(this.leafScopeIds, index, [].concat(checked));
      }

      // 判断全选
      this.$set(
        this.scopeAllChecked,
        index,
        this.scopeIds[index]?.length === this.dataScopeIds[index]?.length
      );
    },
    // 设置部门权限
    handleDepScope(ids) {
      const index = this.dataScope.findIndex((item) => item.type === "FAC");
      if (index !== -1) {
        this.$set(this.scopeIds, index, ids);

        // 页面菜单权限树结构的选中数据(只有叶子节点id)
        const [leafArr] = this.getSelectedData(
          this.dataScope[index].dataList,
          ids
        );
        this.$set(this.leafScopeIds, index, leafArr);
      }
    },
    // 设置部门角色
    handleDepRole(roles) {
      if (roles.length > 0) {
        this.selectedRoleRows = roles.map((e) => ({
          id: e.roleId,
          disabled: true,
          roleName: e.roleName,
        }));
      } else {
        this.selectedRoleRows = [];
      }
    },
    // 用户详情角色
    handleUserRole(rolesIds, deptId) {
      const p = [
        this.$axios.get(`${ApiConstant.PREFIX_CORE}/api/sys/role/search`, {
          params: {
            ids: rolesIds.join(),
            appId: "0",
            size: rolesIds.length,
          },
        }),
      ];
      deptId &&
        p.push(
          this.$axios.get(
            `${ApiConstant.PREFIX_CORE}/api/sys/org/org-data-scope`,
            {
              params: { id: deptId },
            }
          )
        );
      Promise.all(p).then(([roleRes, depRes]) => {
        const depRoleIds =
          depRes?.data?.data?.roles?.map((e) => e.roleId) || [];
        this.selectedRoleRows = roleRes.data.data.records.map((e) => ({
          id: e.id,
          roleName: e.roleName,
          disabled: depRoleIds.includes(e.id) || false,
        }));
      });
    },
    fourPassword() {
      this.addForm.password = "";
    },
    selectRole() {
      this.$refs.selectRoleRef.openDialog();
    },
    // 删除某一个角色
    changeSelectedRoleRows(item, index) {
      this.selectedRoleRows.splice(index, 1);
      this.addForm.rolesIds = this.selectedRoleRows.map((e) => e.id);
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      if (!selectedKeys || selectedKeys.length === 0) {
        this.selectedRoleRows = this.selectedRoleRows.filter(
          (item) => item.disabled
        );
        this.addForm.rolesIds = this.selectedRoleRows.map((e) => e.id);
      } else {
        this.selectedRoleRows = selectedRows;
        this.addForm.rolesIds = selectedKeys;
      }
    },
    changePassword(rule, value, callback) {
      if (value && value !== "******") {
        this.verification(
          value,
          this.systemConfig.PWD_LENGTH,
          this.systemConfig.PWD_LEVEL
        );
        if (!this.isSave && value) {
          callback(this.titleError);
        } else {
          callback();
        }
      } else {
        this.isSave = true;
        callback();
      }
    },
    verification(val, length, level) {
      if (val.length < length) {
        this.isSave = false;
        this.titleError = this.$t("PASSWORD_LENGTH");
      } else {
        if (level === "M") {
          const reg = /^(?![^a-zA-Z]+$)(?!\D+$)/;
          if (!reg.test(val)) {
            this.isSave = false;
            this.titleError = this.$t("PASSWORD_LETTER");
          } else {
            this.isSave = true;
          }
        }
        if (level === "H") {
          const res =
            /([0-9].*([a-zA-Z].*[!$#%?.&@~^]|[!$#%?.&~^].*[a-zA-Z])|[a-zA-Z].*([0-9].*[!$#%?.&~^]|[!$#%?.&~^].*[0-9])|[!$#%?.&].*([0-9].*[a-zA-Z]|[a-zA-Z].*[0-9]))/;
          if (!res.test(val)) {
            this.isSave = false;
            this.titleError = this.$t("PASSWORD_SPECIAL");
          } else {
            this.isSave = true;
          }
        }
        if (level === "L") {
          this.isSave = true;
        }
      }
    },
    // 遍历找出所有子节点
    findAllChildren(data, arr) {
      data.forEach((item, index) => {
        if (item.children.length !== 0) {
          this.findAllChildren(item.children, arr);
        } else if (
          this.addForm.userDataScopes &&
          this.addForm.userDataScopes.includes(item.code)
        ) {
          arr.push(item.code);
        }
      });
    },
    // 权限列表和用户信息权限对应
    queryUserScope() {
      // 获取树key
      const fn = (data, levelAttr = "children", attr = "id", arr = []) => {
        data.forEach((item) => {
          arr.push(item[attr]);

          if (item?.[levelAttr]?.length) {
            fn(item[levelAttr], levelAttr, attr, arr);
          }
        });
        return arr;
      };
      const { id } = this.$route.query;
      if (id) {
        Promise.all([
          this.$axios.get(
            `${ApiConstant.PREFIX_CORE}/api/sys/userdatascope/tree`
          ),
          this.$axios.get(
            `${ApiConstant.PREFIX_CORE}/api/sys/user/get-by-id/${id}`
          ),
        ]).then(([userDataScopeRes, userDetailRes]) => {
          // 权限列表数据
          this.dataScope = (userDataScopeRes.data.data || []).map((item) => ({
            ...item,
          }));
          // 用户数据
          const { password, sex, deptId, rolesIds, userDataScopeVOS } =
            userDetailRes.data.data;
          userDataScopeVOS.forEach((item, index) => {
            if (item.type === this.dataScope[index].type) {
              this.$set(
                this.dataScope[index],
                "parentLink",
                item.parentLink === "Y"
              );
            }
          });
          // dataList所有ID
          this.dataScope.forEach((item, index) => {
            this.$set(
              this.dataScopeIds,
              index,
              fn(item.dataList, "children", "id")
            );
          });
          this.addForm = {
            ...userDetailRes.data.data,
            deptId: deptId || "",
            password: password || "******",
            sex: sex || "UNKNOW",
            rolesIds,
          };
          this.employeeNoList = [userDetailRes.data.data.employeeNo];
          // 权限数据
          this.dataScope.forEach((item, index) => {
            const curr = userDataScopeVOS.find((e) => e.type === item.type);
            if (curr) {
              this.$set(this.ranges, index, curr.mode);
              this.$set(this.scopeIds, index, curr.ids);
              this.changeAuthRange(curr.mode, index, item.modeList);
              // 判断是否为父子联动效果
              // 联动的 leafArr 非联动 curr.ids
              if (item.parentLink) {
                // 页面菜单权限树结构的选中数据(只有叶子节点id)
                const [leafArr] = this.getSelectedData(item.dataList, curr.ids);
                this.$set(this.leafScopeIds, index, leafArr);
              } else {
                this.$set(this.leafScopeIds, index, curr.ids);
              }
            }
            // 判断全选
            this.$set(
              this.scopeAllChecked,
              index,
              this.scopeIds[index]?.length === this.dataScopeIds[index]?.length
            );
          });
          // 设置角色
          this.handleUserRole(rolesIds, deptId);
        });
      } else {
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/sys/userdatascope/tree`)
          .then((res) => {
            this.dataScope = (res.data.data || []).map((item) => ({
              ...item,
              parentLink: item.parentLink || false,
            }));
            this.dataScope.forEach((item, index) => {
              this.$set(
                this.dataScopeIds,
                index,
                fn(item.dataList, "children", "id")
              );
            });
          });
      }
    },
    initModuleTree() {
      // 用户数据
      this.queryUserScope();
      // 获取部门列表
      const params = {
        enableFlag: "Y",
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`, { params })
        .then((res) => {
          // 设置数据isLeaf字段值为bool类型
          const fn = (data) => {
            data.forEach((item) => {
              // eslint-disable-next-line no-param-reassign
              item.isLeaf = [1, "1"].includes(item.isLeaf);
              if (item?.children?.length) {
                fn(item.children);
              }
            });
          };
          fn(res.data.data);
          this.treeData = res.data.data;
        });
      // 获取性别列表
      this.getDictByCode("DIC:COMMON:SEX_TYPE").then((res) => {
        this.sexTypeList = res.data.data;
      });
      // 获取用户类型
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/user/list-user-mrg-type`)
        .then((res) => {
          this.typeList = res.data.data;
        });
    },
    handChangeDep(val) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/org-data-scope`, {
          params: { id: val },
        })
        .then((res) => {
          // 部门完全控制角色和 FAC(工厂)权限
          this.handleDepRole(res.data.data.roles || []);
          this.handleDepScope(res.data.data.siteIds || []);
        });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/upms/system/setting/user" },
        vm: this,
      });
    },
    confirm() {
      const req = {
        ...this.addForm,
        password:
          this.addForm.password === "******" ? null : this.addForm.password,
        rolesIds: this.selectedRoleRows?.map((e) => e.id) || [],
        userDataScopeTypeFormParams: this.dataScope.map((item, index) => {
          return {
            mode: this.ranges[index] || undefined,
            type: item.type,
            parentLink: item.parentLink ? "Y" : "N",
            userDataScopeFormParams: this.scopeIds[index]?.map((e) => ({
              objectId: e,
            })),
          };
        }),
      };
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/user`, req)
            .then((res) => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/upms/system/setting/user" },
                vm: this,
              });
            });
        } else {
          this.$message.error(this.$t("REQUIRED_INFO"));
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .role-add {
  .roleCodes {
    display: flex;
    align-items: center;
  }
  .width-150 {
    width: 120px;
  }
  .node-label {
    display: inline-block;
    width: 120px;
    margin-right: 30px !important;
  }
  .btns {
    margin-top: 40px;
  }
  .ant-tabs {
    padding-bottom: 14px;
  }
}
.user_box {
  padding: 0 10px;
  height: 100%;
  overflow-y: auto;
  /deep/ .ant-checkbox-group-item {
    display: block;
  }
}
.tagInt {
  border: 1px solid #ccc;
  border-radius: 5px;
  height: 36px;
  line-height: 36px;
  padding-left: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.tagError {
  background: red;
}
</style>
