<template>
  <div class="p-2">
    <el-row :gutter="10">
      <!-- 部门树-->
      <el-col :lg="4" :xs="24">
        <el-card shadow="hover" class="h-700px">
          <div class="w-30 pt-3 pb-2 font-bold mb-6"><span class="text-red-500">部门列表</span></div>
          <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
          <el-scrollbar>
            <el-tree
              ref="deptTreeRef"
              v-loading="deptLoading"
              class="mt-2 w-250px h-560px inline-block overflow-auto tree"
              node-key="id"
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              highlight-current
              :default-expanded-keys="expandKeys"
              @node-click="handleNodeClick"
            />
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :lg="12" :xs="24">
        <el-card shadow="hover" class="h-700px">
          <div class="flex">
            <div class="w-30 pt-3 pb-2 font-bold"><span class="text-red-500">待选用户</span></div>
            <div>
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="pt-2 pb-2 ml-20">
                <el-form-item label="姓名" prop="realName" style="width: 25%">
                  <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="学/工号" prop="userNumb" style="width: 30%">
                  <el-input v-model="queryParams.userNumb" placeholder="请输入学/工号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <!-- <el-form-item label="手机号码" prop="phone" style="width: 20%">
                <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
              </el-form-item> -->
                <el-form-item style="width: 25%">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>

          <el-table
            ref="table1"
            v-loading="loading"
            row-key="userId"
            :data="list1"
            border
            height="500px"
            :row-style="{ 'height': '35px' }"
            :cell-style="{ 'padding': '0px', 'height': '30px' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column fixed type="selection" width="55" align="center" />
            <el-table-column label="姓名" align="center" prop="realName" :show-overflow-tooltip="true" />
            <el-table-column label="学/工号" align="center" prop="userNumb" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" prop="phone" :show-overflow-tooltip="true" />
            <el-table-column label="开户状态" align="center" prop="accountStatus">
              <template #default="scope">
                <dict-tag :options="account_open_status" :value="scope.row.accountStatus" />
              </template>
            </el-table-column>
            <el-table-column label="冻结状态" align="center" prop="freezeStatus">
              <template #default="scope">
                <dict-tag :options="sys_yes_no" :value="scope.row.freezeStatus" />
              </template>
            </el-table-column>
            <el-table-column label="账户状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>
            <template #empty>
              <!-- 自定义没有数据时的显示 -->
              <p>没有数据</p>
            </template>
          </el-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </el-card>
      </el-col>
      <el-col :lg="8" :xs="24">
        <el-card shadow="hover" class="h-700px">
          <div class="w-30 pt-3 pb-2 font-bold mb-6">
            <span class="text-red-500">当前已选（{{ list2.length }}）</span>
          </div>
          <el-table
            ref="table2"
            :data="list2"
            row-key="userId"
            border
            height="600"
            :row-style="{ 'height': '35px' }"
            :cell-style="{ 'padding': '0px', 'height': '30px' }"
            @selection-change="handleSelectionChange2"
          >
            <el-table-column fixed type="selection" width="55" align="center" />
            <el-table-column label="姓名" align="center" prop="realName" :show-overflow-tooltip="true" />
            <el-table-column label="学/工号" align="center" prop="userNumb" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
            <el-table-column label="手机号码" align="center" prop="phone" :show-overflow-tooltip="true" />
            <template #empty>
              <!-- 自定义没有数据时的显示 -->
              <div style="height: 0px">
                <!-- 内容 -->
              </div>
            </template>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" name="draggable1" setup>
import api from '@/api/payment/account';
import { PtUserAccountForm, PtUserAccountQuery, PtUserAccountVO } from '@/api/payment/account/types';
import { DeptVO } from '@/api/system/dept/types';
import { ref } from 'vue';
import { useDraggable } from 'vue-draggable-plus';

const table1 = ref();
const tbody1 = ref<HTMLTableSectionElement>();
const tbody2 = ref<HTMLTableSectionElement>();
const tTable1 = ref<HTMLElement>();
const tTable2 = ref<HTMLElement>();
const table2 = ref();
const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();

const ids1 = ref<Array<string | number>>([]);
const selected1 = ref<PtUserAccountVO[]>([]);
const ids2 = ref<Array<string | number>>([]);
const selected2 = ref<PtUserAccountVO[]>([]);

const deptOptions = ref<DeptVO[]>([]);
const deptName = ref('');
const expandKeys = ref<number[]>([]);
const initFormData: PtUserAccountForm = {
  userId: undefined,
  deptId: undefined,
  postId: undefined,
  userName: '',
  userNumb: '',
  realName: '',
  category: '',
  phone: undefined,
  accountStatus: '1',
  freezeStatus: 'N',
  consumePwd: undefined,
  cardType: 1,
  lifespan: '2050-12-31 23:59:59',
  status: '0',
  remark: '',
  accountBalance: '0'
};

const initData: PageData<PtUserAccountForm, PtUserAccountQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    realName: '',
    userNumb: '',
    phone: ''
  },
  rules: {}
};
const data = reactive<PageData<PtUserAccountForm, PtUserAccountQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<PtUserAccountForm, PtUserAccountQuery>>(data);

const loading = ref(true);
const deptLoading = ref(false);
// const showSearch = ref(true);
const total = ref(0);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

/** 当前页面引用的数据字典 */
const { sys_normal_disable, sys_yes_no, account_open_status } = toRefs<any>(
  proxy?.useDict('sys_normal_disable', 'sys_yes_no', 'account_open_status')
);

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const list1 = ref<PtUserAccountVO[]>([]);
const list2 = ref<PtUserAccountVO[]>([]);

/** 多选框选中数据 */
const handleSelectionChange = (selection: PtUserAccountVO[]) => {
  selected1.value = selection;
  ids1.value = selection.map((item) => item.userId);
};

/** 多选框选中数据 */
const handleSelectionChange2 = (selection: PtUserAccountVO[]) => {
  selected2.value = selection;
  ids2.value = selection.map((item) => item.userId);
};

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id;
  handleQuery();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 查询用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await api.listPtUserAccount4Select(proxy?.addDateRange(queryParams.value, dateRange.value));
  loading.value = false;
  list1.value = res.rows;
  total.value = res.total;
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  deptLoading.value = true;
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
  expandKeys.value = [deptOptions.value[0].id as number];
  deptLoading.value = false;
};

onMounted(async () => {
  getTreeSelect(); // 初始化部门数据
  getList(); // 初始化列表数据
  await nextTick(); // 确保 DOM 更新完成
  tbody1.value = table1.value.$el.querySelector('.el-table__body-wrapper table.el-table__body > tbody');
  tbody2.value = table2.value.$el.querySelector('.el-table__body-wrapper table.el-table__body > tbody');
  useDraggable(tbody1, list1, {
    animation: 150,
    ghostClass: 'sortable-ghost',
    group: 'people',
    onAdd: (evt) => {
      if (selected2.value.length > 1) {
        list1.value.splice(evt.newIndex, 1, ...selected2.value); //添加所有选中的元素
      }
    },
    onStart: onStart,
    onRemove: () => {
      if (selected1.value.length > 1) {
        list1.value = list1.value.filter((item) => !ids1.value.includes(item.userId));
      }
    },
    onEnd: (evt) => {
      console.log('end1', list2.value.length);
      if (list2.value.length > 1) {
        //根据 userId 去重list中的数据
        list2.value = deduplicateByUserId(list2.value);
      }
    }
  });

  useDraggable(tbody2, list2, {
    animation: 150,
    ghostClass: 'sortable-ghost',
    group: 'people',
    onAdd: (evt) => {
      // console.log('add2', selected1.value.length);
      if (selected1.value.length > 1) {
        list2.value.splice(evt.newIndex, 1, ...selected1.value); //添加所有选中的元素
      }
    },
    onStart: (evt) => {
      if (selected2.value.length > 0) {
        const moveItem = toRaw(evt.data);
        if (!ids2.value.includes(moveItem.userId)) {
          //取消选中
          selected2.value = [];
          ids2.value = [];
        }
      }
    },
    onRemove: () => {
      if (selected2.value.length > 1) {
        list2.value = list2.value.filter((item) => !ids2.value.includes(item.userId));
      }
    }
  });

  tTable1.value = table1.value.$el.querySelector('.el-table__body-wrapper table.el-table__body');
  tTable2.value = table2.value.$el.querySelector('.el-table__body-wrapper table.el-table__body');
  tTable1.value.style.minHeight = '400px';
  tTable1.value.style.background = '#f2f2f2';
  tTable2.value.style.minHeight = '600px';
  tTable2.value.style.background = '#f2f2f2';
});

function deduplicateByUserId(list) {
  const map = new Map();
  list.forEach((item) => {
    if (!map.has(item.userId)) {
      map.set(item.userId, item);
    }
  });

  return Array.from(map.values());
}

function onStart(evt) {
  if (selected1.value.length > 0) {
    const moveItem = toRaw(evt.data);
    if (!ids1.value.includes(moveItem.userId)) {
      //取消选中
      selected1.value = [];
      ids1.value = [];
    }
  }
}
</script>
<style lang="scss" scoped>
/* .sortable-chosen {
  background: #ff4043 !important;
  color: #ee0f3b !important;
  border-color: #ff4043 !important;
  border-radius: 4px !important; 21af73
} */
//托拽时的样式
::v-deep .sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #21af73 !important;
}

::v-deep .el-tree > :nth-child(n + 1) {
  display: inline-block !important;
  min-width: 100% !important;
}

::v-deep .el-tree-node :nth-child(2) {
  padding: 1px !important;
  overflow: visible !important;
}

::v-deep .el-table__empty-block {
  display: none !important;
  height: 0px !important;
}

::v-deep .el-scrollbar__bar.is-vertical {
  width: 10px !important;
}

::v-deep .el-table__body-wrapper table.el-table__body > tbody td div.cell {
  padding: 0px !important;
  max-height: 30px !important;
}
</style>
