MyComponent.vue 30.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
<!--
 * @Date: 2022-08-29 14:31:20
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2024-11-21 12:41:40
 * @FilePath: /data-table/src/components/OrgPickerField/MyComponent.vue
 * @Description: 树形组件
-->
<template>
  <div class="tree-field-page">
    <div class="select-tree-box" @click="openTree">
      <div class="select-tree-item" v-for="(dept) in emitCheckedGroup.dept" :key="dept.id" @click="clickNode(dept)">
        <van-icon name="wap-home-o" />&nbsp;{{ dept.name }}
      </div>
      <div class="select-tree-item" v-for="(role) in emitCheckedGroup.role" :key="role.id" @click="clickNode(role)">
        <van-icon name="user-o" />&nbsp;{{ role.name }}
      </div>
      <div class="select-tree-item" v-for="(user) in emitCheckedGroup.user" :key="user.id" @click="clickNode(user)">
        <van-icon name="contact-o" />&nbsp;
        <span>{{ user.name }}</span>
        <span v-if="user?.role_list?.length">/
          <span v-for="(role, index) in user?.role_list" :key="role.id">
            {{ role.name }}
            <span v-if="index !== (user?.role_list?.length - 1)">,</span>
          </span>
        </span>
      </div>
    </div>

    <van-popup
      v-model:show="showPopover"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '90vh' }"
    >
      <div v-if="!is_search" class="search-box" @click="onSearchFocus">
        <van-icon name="search" size="1.1rem" />&nbsp;点击搜索
      </div>
      <van-field
        v-else
        ref="searchInputRef"
        v-model="searchValue"
        placeholder="可通过名称,手机号或邮箱查询"
        :border="false"
        @blur="onSearchBlur"
        @focus="onSearchFocus"
      >
        <template #button>
          <van-button size="small" type="primary" @click="onCloseSearch">关闭</van-button>
        </template>
      </van-field>

      <div class="select-box">
        <div class="select-item" v-for="(dept) in checkedGroup.dept" :key="dept.id">
          {{ dept.name }}&nbsp;<van-icon @click="onRemoveDeptTag(dept)" name="close" />
        </div>
        <div class="select-item" v-for="(role) in checkedGroup.role" :key="role.id">
          {{ role.name }}&nbsp;<van-icon @click="onRemoveRoleTag(role)" name="close" />
        </div>
        <div class="select-item" v-for="(user) in checkedGroup.user" :key="user.id">
          <span>{{ user.name }}</span>
          <span v-if="user?.role_list?.length">/
            <span v-for="(role, index) in user?.role_list" :key="role.id">
              {{ role.name }}
              <span v-if="index !== (user?.role_list?.length - 1)">,</span>
            </span>
          </span>
          &nbsp;<van-icon @click="onRemoveUserTag(user)" name="close" />
        </div>
      </div>

      <div v-show="!is_search" class="tab-tree-container">
        <van-tabs ref="tabRef" :color="styleColor.baseColor" v-model:active="tabActive" @click-tab="onClickTab" style="margin-bottom: 1rem;">
          <!-- <van-tab title="组织结构" :name="0"></van-tab>
          <van-tab title="角色" :name="1"></van-tab>
          <van-tab title="成员" :name="2"></van-tab> -->
          <van-tab v-for="(tab, index) in tabList" :key="index" :title="tab.title" :name="tab.name"></van-tab>
        </van-tabs>

        <div v-show="tabActive === 0" style="padding: 0 0 0 1rem;">
          <Vtree
            id="deptTree"
            ref="deptTreeRef"
            v-model="select_dept_value"
            checkable
            titleField="name"
            keyField="id"
            :expandOnFilter="false"
            :showCheckedButton="false"
            :showFooter="false"
            :cascade="false"
            :defaultExpandAll="false"
            :disableAll="deptTreeDisableAll"
            @check="deptTreeCheck"
            @uncheck="deptTreeUncheck"
            @checked-change="deptTreeCheckedChange"
            style=" height: 60vh; overflow: scroll;"
          >
            <span slot="empty">暂无数据</span>
          </Vtree>
        </div>

        <div v-if="tabActive === 1" style="padding: 0 0 0 1rem; overflow: scroll; height: 60vh;" @click.stop>
          <van-checkbox-group
            v-model="role_checked"
            @change="roleChangeMethod"
          >
            <van-checkbox
              v-for="(role, index) in roleList"
              :ref="el => roleCheckboxRefs[index] = el"
              :id="role.id"
              :key="index"
              :name="role.id"
              shape="square"
              icon-size="13px"
              :checked-color="styleColor.baseColor"
              :disabled="role.disabled"
              style="margin-bottom: 0.5rem;"
              @click="onRoleClick(role, $event, index)"
            >{{ role.name }}</van-checkbox>
          </van-checkbox-group>
          <div style="height: 10vh;"></div>
        </div>

        <div v-if="tabActive === 2" style="padding: 0 0 0 1rem;">
          <van-row gutter="">
            <van-col span="10" style="border-right: 1px solid #eee; height: 60vh; overflow: scroll;">
              <Vtree
                id="userTree"
                ref="userTreeRef"
                v-model="select_user_value"
                selectable
                titleField="name"
                keyField="id"
                :expandOnFilter="false"
                :showCheckedButton="false"
                @update:modelValue="() => {}"
                @click="onUserTreeClick"
              >
                <span slot="empty">暂无数据</span>
              </Vtree>
            </van-col>
            <van-col span="14"  style="height: 60vh; overflow: scroll;">
              <van-checkbox-group
                v-model="user_checked"
                style="padding: 0 0 1rem 1rem;"
                @change="onUserChange"
              >
                <van-checkbox
                  @click="onCheckUserChange(user, $event, index)"
                  v-for="(user, index) in userList"
                  :ref="el => userCheckboxRefs[index] = el"
                  :id="user.id"
                  :type="user.type"
                  :text="user.name"
                  :key="index"
                  :name="user.id"
                  shape="square"
                  icon-size="13px"
                  :checked-color="styleColor.baseColor"
                  :disabled="user.disabled"
                  style="margin-bottom: 0.5rem;"
                >{{ user.name }}</van-checkbox>
              </van-checkbox-group>
              <div style="height: 10vh;"></div>
            </van-col>
          </van-row>
        </div>
      </div>

      <div v-show="is_search" class="search-container">
        <van-checkbox-group
          v-model="search_result_checked"
          style="padding: 0 0 1rem 1rem;"
          @change="onSearchResultChange"
        >
        <div>
          <p style="font-weight: bold;">部门</p>
          <div style="border-top: 1px solid #eee; margin: 0.5rem 0;"></div>
          <div style="margin-bottom: 1rem;">
            <van-checkbox
              @click="onSearchResultClick(dept, $event)"
              v-for="(dept) in user_dept_role.dept"
              :id="dept.id"
              :type="dept.type"
              :text="dept.name"
              :key="dept.id"
              :name="dept.id"
              shape="square" icon-size="13px"
              :checked-color="styleColor.baseColor"
              :disabled="dept.disabled"
              style="margin-bottom: 0.5rem;">
              {{ dept.name }}
            </van-checkbox>
            <div v-if="!user_dept_role.dept.length" style="color: #999;">暂无数据</div>
          </div>
        </div>
        <div>
          <p>角色</p>
          <div style="border-top: 1px solid #eee; margin: 0.5rem 0;"></div>
          <div style="margin-bottom: 1rem;">
            <van-checkbox
              @click="onSearchResultClick(role, $event)"
              v-for="(role) in user_dept_role.role"
              :id="role.id"
              :type="role.type"
              :text="role.name"
              :key="role.id"
              :name="role.id"
              shape="square"
              icon-size="13px"
              :checked-color="styleColor.baseColor"
              :disabled="role.disabled"
              style="margin-bottom: 0.8rem;">
              {{ role.name }}
            </van-checkbox>
            <div v-if="!user_dept_role.role.length" style="color: #999;">暂无数据</div>
          </div>
        </div>
        <div>
          <p>成员</p>
          <div style="border-top: 1px solid #eee; margin: 0.5rem 0;"></div>
          <div style="margin-bottom: 1rem; overflow: auto;">
            <van-checkbox
              @click="onSearchResultClick(user, $event)"
              v-for="(user) in user_dept_role.user"
              :id="user.id"
              :type="user.type"
              :text="user.name"
              :key="user.id"
              :name="user.id"
              shape="square"
              icon-size="13px"
              :checked-color="styleColor.baseColor"
              :disabled="user.disabled"
              style="margin-bottom: 0.5rem;">
              <div class="van-ellipsis" :style="{ maxWidth: maxWidth + 'px' }">
                <span>{{ user.name }}</span>
                <span v-if="user.role_list.length">/
                  <span v-for="(role, index) in user?.role_list" :key="role.id">{{ role.name }}&nbsp;</span>
                </span>
                <span v-if="user?.dept_list.length">/
                  <span v-for="(dept, index) in user?.dept_list" :key="dept.id">{{ dept.name }}&nbsp;</span>
                </span>
              </div>
            </van-checkbox>
            <div v-if="!user_dept_role.user.length" style="color: #999;">暂无数据</div>
          </div>
        </div>
        </van-checkbox-group>
      </div>

      <div style="position: fixed; bottom: 0; left: 0; width: 100%;">
        <van-row gutter="10" style="padding: 0 10px 1rem;">
          <van-col span="12">
            <van-button block round type="default" @click="onCancelClick">取消</van-button>
          </van-col>
          <van-col span="12">
            <van-button block round type="primary" @click="onConfirmClick">确定</van-button>
          </van-col>
        </van-row>
      </div>
    </van-popup>

    <van-dialog v-model:show="show_detail" title="详情" :confirm-button-color="styleColor.baseColor">
      <div style="padding: 0 1rem;">
        <div style="margin-bottom: 0.5rem;">名称:{{ node_info.name }}</div>
        <div style="margin-bottom: 0.5rem;">类型:{{ node_info.type }}</div>
        <div v-if="node_info.mobile" style="margin-bottom: 0.5rem;">手机号:<a :href="`tel:${node_info.mobile}`" :style="{ color: styleColor.baseColor }">{{ node_info.mobile }} </a></div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { inject, ref } from 'vue'
import { useCustomFieldValue } from '@vant/use';
import { styleColor } from "@/constant.js";
import { getFlowDeptListAPI, getFlowRoleListAPI, searchUserDeptRoleAPI } from "@/api/component.js";
// 大家可以根据需要是否引入VTreeNode, VTreeSearch, VTreeDrop
import Vtree, { VTreeNode, VTreeSearch, VTreeDrop } from '@wsfe/vue-tree'
import '@wsfe/vue-tree/style.css';
// import role_list from './flow_role_list.json'
// import dept_list from './flow_dept_list.json'
import $ from 'jquery';
import _ from 'lodash';
import { showDialog, showToast } from 'vant';
import Cookies from 'js-cookie';

// 获取父组件传值
const props = inject('props');

const emit = defineEmits(["active"]);

const $route = useRoute();
const $router = useRouter();

let role_list = [];
let dept_list = [];

let check_type = ref(''); // 单选/多选模式

// 处理Tab显示问题
// TODO:等待后台数据
const tree_tabs = ['dept', 'role', 'user'];
const tabList = computed(() => {
  let arr = [];
  if (tree_tabs.indexOf('dept') !== -1) {
    arr.push({
      title: '组织结构',
      name: 0
    })
  }
  if (tree_tabs.indexOf('role') !== -1) {
    arr.push({
      title: '角色',
      name: 1
    })
  }
  if (tree_tabs.indexOf('user') !== -1) {
    arr.push({
      title: '成员',
      name: 2
    })
  }
  return arr;
});

const maxWidth = ref(0);

/**
 * 计算选中框数量
 * 选中框的数量 >= 1
 * @returns {boolean}
 */
const treeCheckedCount = computed(() => {
  let dept_count = checkedGroup.value.dept.length;
  let user_count = checkedGroup.value.user.length;
  let role_count = checkedGroup.value.role.length;

  return dept_count + user_count + role_count >= 1;
});

onMounted(async () => {
  // TAG: 获取后台数据
  const flowDeptList = await getFlowDeptListAPI({ form_code: $route.query.code });
  if (flowDeptList.code) {
    role_list = flowDeptList.data;
  }
  const flowRoleList = await getFlowRoleListAPI({ form_code: $route.query.code });
  if (flowRoleList.code) {
    dept_list = flowRoleList.data;
  }
  // TODO:等待后台数据
  check_type.value = '';
  // 获取已选中数据
  // 如果有默认值处理
  props.value = props.component_props.default;
  //
  if (props.value) {
    props.value.forEach(item => {
      if (item.type === 'dept') {
        emitCheckedGroup.value.dept.push(item);
      } else if (item.type === 'role') {
        emitCheckedGroup.value.role.push(item);
      } else if (item.type === 'user') {
        emitCheckedGroup.value.user.push(item);
      }
    });
    // 发送到表单数据
    tree_select_value.value = [].concat(...Object.values(emitCheckedGroup.value));
  }
  // 获取宽度处理成员角色值可能太长显示问题
  nextTick(() => {
    maxWidth.value = $('.select-tree-box').width();
  })
});

const openTree = () => { // 点击组件展示框回调
  if (props.component_props.readonly) return false; // 只读判断
  // 打开弹窗
  showPopover.value = true;

  // 获取数据
  nextTick(() => {
    // 动态判断点击显示的tab,默认点击第一个
    onClickTab({ title: tabList.value[0]['title'] })
    // getDeptTreeData();
    setTimeout(() => { // 延时处理,防止数据未加载完就执行
      // 获取已选择的数据
      checkedGroup.value = _.cloneDeep(emitCheckedGroup.value);
      syncResultToList(); // 同步勾选状态
    }, 100);
    // 树形结构底部高度可视度
    if (!$('#deptTree').find('.tree-placeholder').length) {
      $('#deptTree').find('.ctree-tree__block-area').append('<div class="tree-placeholder" style="height: 10vh;"></div>');
    }

  });
}
/**
 * 点击节点详情
 * @param {*} id
 * @param {*} type
 * @param {*} name
 * @param {*} mobile
 */
const node_info = ref({});
const show_detail = ref(false);

/******************** END ****************/

// 点击显示框,显示节点详情
const clickNode = ({ id, type, name, mobile='' }) => {
  if (!props.component_props.readonly) return false; // 非只读不予许操作
  const obj = {
    dept: '部门',
    role: '角色',
    user: '成员'
  }
  if (mobile === null) {
    mobile = ''
  }
  node_info.value = {
    id,
    type: obj[type],
    name,
    mobile
  }
  show_detail.value = true;
}

/**
 * 勾选数据结构
 * @type {Object}
 * @property {Array} dept 组织结构
 * @property {Array} role 角色
 * @property {Array} user 成员
 */
const emitCheckedGroup = ref({
  dept: [], // 组织结构
  role: [], // 角色
  user: [] // 成员
});

/**
 * 勾选数据---发送表单数据
 * @type {Array}
 */
const tree_select_value = ref([]);

/******* 搜索输入项 *******/
const showPopover = ref(false); // 显示/隐藏弹框

const onCancelClick = () => { // 取消操作
  showPopover.value = false;
}

const onConfirmClick = () => { // 确定操作
  showPopover.value = false;
  if (is_search.value) {
    onCloseSearch();
  }
  //
  emitCheckedGroup.value = _.cloneDeep(checkedGroup.value);
  // 发送到表单数据
  tree_select_value.value = [].concat(...Object.values(emitCheckedGroup.value));
  // 适配cookie保存未完成表单
  const currentValue = tree_select_value.value;
  const existingCookie = Cookies.get($route.query.code);

  if (existingCookie) {
    // 如果Cookie存在,更新它
    let obj = JSON.parse(existingCookie);
    obj[props.key] = currentValue; // 替换掉旧值
    Cookies.set($route.query.code, JSON.stringify(obj));
  } else {
    // 如果Cookie不存在,新增它
    Cookies.set($route.query.code, JSON.stringify({ [props.key]: currentValue }));
  }
}

const searchInputRef = ref(null); // 搜索输入框Ref
const searchValue = ref(''); // 搜索输入框值
const is_search = ref(false); // 默认不显示搜索框

/**
 * 搜索选中结果集
 * @param {Number} id
 */
const search_result_checked = ref([]);

const onSearchBlur = async () => { // 搜索框失去焦点
  const { code, data } = await searchUserDeptRoleAPI({ form_code: $route.query.code, word: searchValue.value })
  if (code) {
    // 单选模式
    if (check_type.value === 'single') {
      if (treeCheckedCount.value) {
        let arr = [...checkedGroup.value.dept, ...checkedGroup.value.role, ...checkedGroup.value.user]
        let current = arr[0]; // 单选模式下,勾选值只会有一个
        //
        for (const key in data) {
          const element = data[key];
          // 遍历数组,设置特定元素的禁用状态
          element.forEach(item => {
            if (item.id === current.id) {
              // 设置该项不禁用
              item.disabled = false;
            } else {
              // 设置该项禁用
              item.disabled = true;
            }
          });
        }
      }
    }
    // 赋值搜索结果集
    user_dept_role.value = data;
  }
}

const onSearchFocus = () => { // 搜索框获取焦点回调
  is_search.value = true; // 打开搜索状态

  // 自动选中搜索框
  nextTick(() => {
    searchInputRef.value.focus();
  });

  // 如果选中框有值,点击搜索框后把结果选中到搜索结果集里面
  handleSelectToSearch();
}

const handleSelectToSearch = () => { // 把选中结果集同步,到搜索结果集上勾中显示
  let dept = checkedGroup.value.dept.map(item => item.id);
  let role = checkedGroup.value.role.map(item => item.id);
  let user = checkedGroup.value.user.map(item => item.id);
  search_result_checked.value = [...dept, ...role, ...user]; // 搜索选中结果集
}

const syncResultToList = () => { // 把弹框结果集同步到树形选择树的勾选状态
  // 组织结构,勾选状态还原
  deptTreeRef.value?.setCheckedKeys(checkedGroup.value.dept.map(item => item.id), true);
  // 角色选中,勾选状态还原
  role_checked.value = checkedGroup.value.role.map(item => item.id);
  // 成员选中,勾选状态还原
  user_checked.value = checkedGroup.value.user.map(item => item.id)
}

const onCloseSearch = () => { // 点击搜索关闭按钮回调
  searchValue.value = ''; // 清空搜索框
  user_dept_role.value = {
    dept: [],
    role: [],
    user: []
  }; // 清空搜索结果
  tabActive.value = 0; // 默认选中组织结构
  is_search.value = false; // 关闭搜索状态
  syncResultToList(); // 同步勾选状态
}
/****************************** END ********************************/

/**
 * 中间通用显示勾选结果集
 */

const checkedGroup = ref({
  dept: [], // 组织结构
  role: [], // 角色
  user: [] // 成员
});

/**
* 重置搜索结果列表的disable状态
*/
const resetSearchDisable = () => {
  for (const key in user_dept_role.value) {
    const element = user_dept_role.value[key];
    element.forEach(item => {
      item.disabled = false;
    });
  }
}

const onRemoveDeptTag = (dept) => { // 移除部门标签
  // 移除选中框显示
  const index = checkedGroup.value.dept.findIndex(item => JSON.stringify(item) === JSON.stringify(dept));
  checkedGroup.value.dept.splice(index, 1);
  // 组织结构移除对应ID
  deptTreeRef.value?.setChecked(dept.id, false);
  // 移除搜索结果选中显示
  const idx = search_result_checked.value.findIndex(item => JSON.stringify(item) === JSON.stringify(dept));
  search_result_checked.value.splice(idx, 1);
  // 单选模式
  if (check_type.value === 'single') {
    resetSearchDisable();
  }
}

const onRemoveRoleTag = (role) => { // 移除角色标签
  const index = checkedGroup.value.role.findIndex(item => JSON.stringify(item) === JSON.stringify(role));
  checkedGroup.value.role.splice(index, 1);
  //
  const idx = role_checked.value.findIndex(item => JSON.stringify(item) === JSON.stringify(role));
  role_checked.value.splice(index, 1);
  // 移除搜索结果选中显示
  const i = search_result_checked.value.findIndex(item => JSON.stringify(item) === JSON.stringify(role));
  search_result_checked.value.splice(i, 1);
  // 单选模式
  if (check_type.value === 'single') {
    resetSearchDisable();
  }
}

const onRemoveUserTag = (user) => { // 移除成员标签
  const index = checkedGroup.value.user.findIndex(item => JSON.stringify(item) === JSON.stringify(user));
  checkedGroup.value.user.splice(index, 1);
  //
  const idx = user_checked.value.findIndex(item => JSON.stringify(item) === JSON.stringify(user));
  user_checked.value.splice(index, 1);
  // 移除搜索结果选中显示
  const i = search_result_checked.value.findIndex(item => JSON.stringify(item) === JSON.stringify(user));
  search_result_checked.value.splice(i, 1);
  // 单选模式
  if (check_type.value === 'single') {
    resetSearchDisable();
  }
}

/*************** Tab 功能模块 ****************/
const tabRef = ref(null);
const tabActive = ref(0);
const deptTreeRef = ref();

const onClickTab = ({ title }) => { // tab点击事件
  nextTick(() => {
    if (title === '组织结构') {
      deptListReset();
    }
    if (title === '角色') {
      roleListReset();
    }
    if (title === '成员') {
      userListReset();
      // 树形结构底部高度可视度
      if (!$('#userTree').find('.tree-placeholder').length) {
        $('#userTree').find('.ctree-tree__block-area').append('<div class="tree-placeholder" style="height: 10vh;"></div>');
      }
    }
  });
};

const deptListReset = () => { // 组织重置列表
  deptTreeRef.value.setData(role_list);
  deptTreeRef.value.setExpand(35697, true)
}

const roleListReset = () => { // 角色重置列表
  roleList.value = dept_list;
}

const userListReset = () => { // 成员重置列表
  userTreeRef.value.setData(role_list);
  userTreeRef.value.setExpand(35697, true);
}
/**************** END *****************/

/************* 组织结构模块 ***************/
const select_dept_value = ref(); // 组织结构树形选中值
const deptTreeDisableAll = ref(false); // 组织结构树形禁用

/**
 * 组织结构单选勾中
 * @param {*} node
 */
const deptTreeCheck = (node) => {
  // 单选模式
  if (check_type.value === 'single') {
    if (treeCheckedCount.value) {
      showToast('单选模式下,只能勾选一个')
      // 移除树结构选中的项
      deptTreeRef.value?.setChecked(node.id, false);
    }
  }
}

/**
 * 组织结构单选取消
 * @param {*} node
 */
const deptTreeUncheck = (node) => {
  // 单选模式
  if (check_type.value === 'single') {
    // 移除选中框显示
    const index = checkedGroup.value['dept'].findIndex(item => item.id === node.id);
    checkedGroup.value['dept'].splice(index, 1);
  }
}

/**
 * 组织结构勾选回调
 * @param {*} arr
 */
const deptTreeCheckedChange = (arr) => {
  // 单选模式
  if (check_type.value === 'single') {
    if (treeCheckedCount.value) {
      return false
    }
  }

  checkedGroup.value.dept = arr.map((item) => {
    return {
      id: item.id,
      name: item.name,
      type: 'dept'
    }
  });
}
/**************** END *****************/

/************* 角色模块 ***************/
/**
 * 角色选中值集合
 */
const role_checked = ref([]);
/**
 * 角色列表数据集合
 */
const roleList = ref([]);

const roleCheckboxRefs = ref([]);
const userCheckboxRefs = ref([]);

/**
 * 角色多选值变化回调
 * @param {*} val
 */
const roleChangeMethod = (val) => {
  // 单选模式
  if (check_type.value === 'single') {
    if (treeCheckedCount.value) {
      return;
    }
  }

  let result = val.map(id => roleList.value.find(obj => obj.id === id));
  // 过滤掉未找到的项(即返回undefined的项)
  checkedGroup.value.role = result.filter(item => item !== undefined);
}

/**
 * 角色单击选项回调
 * @param {*} role
 * @param {*} evt
 */
const onRoleClick = (role, evt, index) => {
  // 单选模式
  if (check_type.value === 'single') {
    const current_idx = checkedGroup.value['role'].findIndex(item => item.id === role.id);
    if (treeCheckedCount.value) {
      if (current_idx === -1) {
        showToast('单选模式下,只能勾选一个')
        setTimeout(() => {
          roleCheckboxRefs.value[index].toggle();
        }, 10);
        return;
      } else {
        checkedGroup.value['role'].splice(current_idx, 1);
      }
    }
  }
}
/**************** END *****************/

/************* 成员模块 ***************/
const userTreeRef = ref();
const select_user_value = ref(); // 成员树形选中值
/**
 * 成员选中值集合
 */
const user_checked = ref([]);

/**
 * 成员Tab列表
 */
const userList = ref([]);

const onUserTreeClick = (node) => { // 点击成员树形回调
  userList.value = node.user;
  user_checked.value = checkedGroup.value.user.map(item => item.id);
}

const onUserChange = (val) => { // 成员多选组点击回调
}

const onCheckUserChange = (val, evt, index) => { // 成员列表点击右侧选项回调
  nextTick(() => {
    // 单选模式
    if (check_type.value === 'single') {
      const current_idx = checkedGroup.value['user'].findIndex(item => item.id === val.id);
      if (treeCheckedCount.value) {
        if (current_idx === -1) {
          showToast('单选模式下,只能勾选一个')
          setTimeout(() => {
            userCheckboxRefs.value[index].toggle();
          }, 10);
          return;
        } else {
          checkedGroup.value['user'].splice(current_idx, 1);
        }
      }
    }

    let checked = false;
    let id = '';
    let name = '';
    let type = '';
    if ($(evt.target).attr('aria-checked') === undefined) {
      checked = $(evt.target).parents('.van-checkbox').attr('aria-checked');
      id = $(evt.target).parents('.van-checkbox').attr('id');
      name = $(evt.target).parents('.van-checkbox').attr('text');
      type = $(evt.target).parents('.van-checkbox').attr('type');
    } else {
      checked = $(evt.target).attr('aria-checked');
      id = $(evt.target).attr('id');
      name = $(evt.target).attr('text');
      type = $(evt.target).attr('type');
    }
    let obj = {
      id: +id,
      name,
      type,
      role_list: val?.role_list?.length ? val?.role_list : []
    }
    checkedGroup.value.user.push(obj);
    checkedGroup.value.user = _.uniqBy(checkedGroup.value.user, 'id');
    //
    if (checked === 'false') {
      if (val.type === 'user') {
        const index = checkedGroup.value.user.indexOf(val);
        checkedGroup.value.user.splice(index, 1);
      }
    }
  });
}
/**************** END *****************/

/***************** 搜索结果集模块 ********************/
/**
 * 搜索结果集合
 */
const user_dept_role = ref({
  dept: [],
  role: [],
  user: []
});

const onSearchResultChange = (val) => { // 监听搜索结果集点击回调,结果集为选中项
}

const deptCheckboxRef = ref(null);

const onSearchResultClick = (val, evt) => { // 搜索结果集项点击回调
  nextTick(() => {
    let checked = false;
    let id = '';
    let name = '';
    let type = '';

    if ($(evt.target).attr('aria-checked') === undefined) { // 点击子元素
      checked = $(evt.target).parents('.van-checkbox').attr('aria-checked');
      id = $(evt.target).parents('.van-checkbox').attr('id');
      name = $(evt.target).parents('.van-checkbox').attr('text');
      type = $(evt.target).parents('.van-checkbox').attr('type');
    } else { // 点击父元素
      checked = $(evt.target).attr('aria-checked');
      id = $(evt.target).attr('id');
      name = $(evt.target).attr('text');
      type = $(evt.target).attr('type');
    }

    let obj = { // 点击元素属性
      id: +id,
      name,
      type,
      role_list: val?.role_list?.length ? val?.role_list : []
    }

    // 对应类型添加到选中组
    checkedGroup.value[type].push(obj);
    checkedGroup.value[type] = _.uniqBy(checkedGroup.value[type], 'id');

    // 取消选中处理
    if (checked === 'false') {
      // 移除对应的数据集
      const index = checkedGroup.value[type].findIndex(item => item.id === obj.id);
      checkedGroup.value[type].splice(index, 1);

      if (type === 'dept') {
        // 树形 组织结构移除对应ID
        deptTreeRef.value?.setChecked(obj.id, false);
      }
    }


    // 单选模式
    if (check_type.value === 'single') {
        if (val.disabled) { // 节点禁用时不能操作
          showToast('单选模式下,只能勾选一个')
          return;
        }
        if (treeCheckedCount.value) {
          for (const key in user_dept_role.value) {
            const element = user_dept_role.value[key];
            element.forEach(item => {
              if (item.id === val.id) { // 禁用其他
                item.disabled = false;
              } else {
                item.disabled = true;
              }
            });
          }
        } else {
          resetSearchDisable();
        }
    }
  });
}

// 此处传入的值会替代 Field 组件内部的 value
useCustomFieldValue(() => tree_select_value.value);

// defineExpose({ handleReset, show_control });
</script>

<style lang="less" scoped>
.tree-field-page {
  width: 100%;
  .select-tree-box {
    height: 4rem;
    // width: calc(100vw - 5rem);
    border: 1px dashed #dfdfdf;
    margin: 1rem 0;
    overflow: scroll;
    border-radius: 5px;
    padding: 0.5rem;
    display: flex;
    flex-wrap: wrap;
    .select-tree-item {
      margin-right: 5px;
      margin-bottom: 5px;
      font-size: 0.85rem;
      padding: 5px 8px;
      background-color: #C2915F;
      color: #fff;
      height: 1.2rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

:deep(.van-field__body) {
  border: var(--border-style);
  border-radius: 0.25rem;
  padding: 0.25rem 0.5rem;
}

.search-box {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eee;
  margin: 1rem;
  border-radius: 3px;
  padding: 0.6rem;
  font-size: 0.9rem;
}

:deep(.ctree-tree-node__checkbox_checked) {
  border-color: #C2915F;
  background-color: #C2915F;
}

:deep(.ctree-tree-node__title_selected) {
  background-color: #f8e2cb;
}

// :deep(.ctree-tree__scroll-area) {
//   margin-bottom: 2rem;
// }

.select-box {
  height: 4rem;
  border: 1px dashed #dfdfdf;
  margin: 0 1rem;
  overflow: scroll;
  border-radius: 5px;
  padding: 0.5rem;
  display: flex;
  flex-wrap: wrap;
  .select-item {
    margin-right: 5px;
    margin-bottom: 5px;
    font-size: 0.85rem;
    padding: 5px 8px;
    background-color: #C2915F;
    color: #fff;
    height: 1.2rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.search-container {
  margin: 1rem 5px;
  height: 60vh;
  overflow: scroll;
}
</style>