<template>
  <div class="p-2 auto-overflow-y">
    <el-row :gutter="10">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover" class="h-775px">
          <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
          <el-tree
            ref="deptTreeRef"
            class="mt-2 w-300px h-171 inline-block overflow-auto"
            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-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="姓名" prop="realName">
                  <el-input v-model="queryParams.realName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="学/工号" prop="userNumb">
                  <el-input v-model="queryParams.userNumb" placeholder="请输入学/工号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-has-permi="['payment:ptUserAccount:edit']" type="primary" plain icon="Plus" @click="handleOpen()">开户</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-has-permi="['payment:ptUserAccount:edit']" type="success" plain :disabled="single" icon="Minus" @click="handleClose()">
                  销户
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-has-permi="['payment:ptUserAccount:edit']"
                  type="danger"
                  plain
                  :disabled="multiple"
                  icon="Lock"
                  @click="handleFreezeStatus('Y')"
                >
                  冻结
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-has-permi="['payment:ptUserAccount:edit']"
                  type="warning"
                  plain
                  :disabled="multiple"
                  icon="Unlock"
                  @click="handleFreezeStatus('N')"
                >
                  解冻
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-dropdown v-hasPermi="['payment:ptUserAccount:edit']" class="mt-[1px]">
                  <el-button plain type="info">
                    更多
                    <el-icon class="el-icon--right"><arrow-down /></el-icon
                  ></el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item  icon="Refresh" @click="handleResetLifespan"
                        >重置有效期</el-dropdown-item>
                      <el-dropdown-item icon="RefreshLeft" @click="handleResetCardType"> 重置卡片类别</el-dropdown-item>
                      <el-dropdown-item icon="RefreshRight" @click="handleResetConsumePwd"> 重置消费密码</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="ptUserAccountList" max-height="calc(100vh - 23.75rem)" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="操作" align="center" width="100">
              <template #default="scope">
                <el-tooltip content="账户卡片" placement="top">
                  <el-button
                    v-hasPermi="['payment:ptUserAccount:edit']"
                    link
                    type="primary"
                    icon="CreditCard"
                    @click="handleAccountCard(scope.row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="账户钱包" placement="top">
                  <el-button
                    v-hasPermi="['payment:ptUserAccount:edit']"
                    link
                    type="primary"
                    icon="Money"
                    @click="handleAccountBag(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[0].visible" label="姓名" align="center" prop="realName" width="100" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[1].visible" label="学/工号" align="center" prop="userNumb" width="100" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[2].visible" label="部门" align="center" prop="deptName" width="150" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[3].visible" label="人员类型" align="center" prop="category" :show-overflow-tooltip="true">
              <template #default="scope">
                <dict-tag :options="CATEGORY" :value="scope.row.category" />
              </template>
            </el-table-column>
            <el-table-column v-if="columns[4].visible" label="手机号码" align="center" prop="phone" width="100" :show-overflow-tooltip="true" />
            <el-table-column v-if="columns[5].visible" 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 v-if="columns[6].visible" 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 v-if="columns[7].visible" label="账户余额" align="center" prop="accountBalance" width="100" />
            <el-table-column v-if="columns[8].visible" label="账户流水号" align="center" prop="userNo" width="100" />
            <el-table-column v-if="columns[9].visible" label="发卡情况" align="center" prop="accountCard" width="100">
              <template #default="scope">
                <span :style="{ color: getCardInfoColor(scope.row.accountCard) }">{{ scope.row.accountCard }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="columns[10].visible"
              label="卡片类型"
              align="center"
              prop="cardTypeName"
              width="100"
              :show-overflow-tooltip="true"
            />
            <el-table-column v-if="columns[11].visible" label="有效期" align="center" prop="lifespan" width="120">
              <template #default="scope">
                <span>{{ parseTime(scope.row.lifespan, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="columns[12].visible" label="账户状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
              </template>
            </el-table-column>
          </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-row>
    <!--    弹出重置有效期对话框 -->
    <reset-expiry-form ref="resetExpiryFormRef" apped-to-body @success="getList" />
    <!-- 弹出重置卡片类型对话框 -->
    <reset-card-type-form ref="resetCardTypeFormRef" apped-to-body @success="getList" />
    <!-- 弹出重置卡片类型对话框 -->
    <reset-consume-pwd-form ref="resetConsumePwdFormRef" apped-to-body @success="getList" />
  </div>
</template>

<script setup name="User" lang="ts">
import api from '@/api/payment/account/';
import { PtUserAccountForm, PtUserAccountQuery, PtUserAccountVO } from '@/api/payment/account/types';
import { DeptVO } from '@/api/system/dept/types';
import { ArrowDown } from '@element-plus/icons-vue';
import ResetExpiryForm from '@/views/payment/account/resetExpiryForm.vue';
import ResetConsumePwdForm from '@/views/payment/account/resetConsumePwdForm.vue';
import ResetCardTypeForm from '@/views/payment/account/resetCardTypeForm.vue';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
/** 当前页面引用的数据字典 */
const { sys_normal_disable, CATEGORY, sys_yes_no, account_open_status } = toRefs<any>(
  proxy?.useDict('sys_normal_disable', 'CATEGORY', 'sys_yes_no', 'account_open_status')
);
const ptUserAccountList = ref<PtUserAccountVO[]>();
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const names = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `姓名`, visible: true, children: [] },
  { key: 1, label: `学/工号`, visible: true, children: [] },
  { key: 2, label: `部门`, visible: true, children: [] },
  { key: 3, label: `人员类型`, visible: true, children: [] },
  { key: 4, label: `手机号码`, visible: true, children: [] },
  { key: 5, label: `开户状态`, visible: true, children: [] },
  { key: 6, label: `冻结状态`, visible: true, children: [] },
  { key: 7, label: `账户余额`, visible: true, children: [] },
  { key: 8, label: `卡流水号`, visible: true, children: [] },
  { key: 9, label: `卡片类型`, visible: true, children: [] },
  { key: 10, label: `发卡情况`, visible: true, children: [] },
  { key: 11, label: `有效期`, visible: true, children: [] },
  { key: 12, label: `账户状态`, visible: true, children: [] }
]);

const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();

const expandKeys = ref([]);

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 filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  handleQuery();
};
const getCardInfoColor = (cardInfo: string) => {
  if (cardInfo === '已销户') {
    return 'red';
  } else if (cardInfo === '实体卡') {
    return 'green';
  } else {
    return 'blue';
  }
};

/** 开户按钮操作 */
const handleOpen = async () => {
  const userIds = ids.value;
  const realNames = names.value;
  if (userIds.length > 0) {
    await proxy?.$modal.confirm('确认是否开户姓名为"' + realNames + '"的数据项？');
    await api.openAccount(userIds);
    await getList();
  } else {
    proxy?.$modal.alertWarning('请选择要开户的账户！');
  }
};
/** 销户按钮操作 */
const handleClose = async () => {
  const userIds = ids.value;
  const realNames = names.value;
  if (userIds.length > 0) {
    await proxy?.$modal.confirm('确认是否销户姓名为"' + realNames + '"的数据项？');
    await api.closeAccount(userIds);
    await getList();
  } else {
    proxy?.$modal.alertWarning('请选择要销户的账户！');
  }
};
/** 冻结/解冻按钮操作 */
const handleFreezeStatus = async (status: string, row?: PtUserAccountVO) => {
  const userIds = row?.userId || ids.value;
  const realNames = row?.realName || names.value;
  const operation = status === 'N' ? '解冻' : '冻结';
  await proxy?.$modal.confirm('是否确认' + operation + '姓名为"' + realNames + '"的数据项？');
  await api.changeFreezeStatus(userIds, status);
  await getList();
  proxy?.$modal.msgSuccess(operation + '成功');
};

/** 重置账户有效期按钮操作 */
const resetExpiryFormRef = ref();
const handleResetLifespan = () => {
  const userIds = ids.value;
  const realNames = names.value;
  if (userIds.length > 0) {
    resetExpiryFormRef?.value.open(userIds, realNames);
  } else {
    proxy?.$modal.alertWarning('请选择要重置有效期的账户！');
  }
};
/** 重置卡类  */
const resetCardTypeFormRef = ref();
const handleResetCardType = async () => {
  const userIds = ids.value;
  const realNames = names.value;
  if (userIds.length > 0) {
    resetCardTypeFormRef?.value.open(userIds, realNames);
  } else {
    proxy?.$modal.alertWarning('请选择要重置卡类的账户！');
  }
};
/** 重置消费密码按钮操作 */
const resetConsumePwdFormRef = ref();
const handleResetConsumePwd = async () => {
  const userIds = ids.value;
  const realNames = names.value;
  if (userIds.length > 0) {
    resetConsumePwdFormRef?.value.open(userIds, realNames);
  } else {
    proxy?.$modal.alertWarning('请选择要重置消费密码的账户！');
  }
};

/** 跳转账户卡片 */
const handleAccountCard = (row: PtUserAccountVO) => {
  const userId = row.userId;
  router.push('/payment/account-other/card/' + userId);
};
/** 跳转账户钱包 */
const handleAccountBag = (row: PtUserAccountVO) => {
  const userId = row.userId;
  router.push('/payment/account-other/bag/' + userId);
};

/** 选择条数  */
const handleSelectionChange = (selection: PtUserAccountVO[]) => {
  ids.value = selection.map((item) => item.userId);
  names.value = selection.map((item) => item.realName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

onMounted(async () => {
  await getTreeSelect(); // 初始化部门数据
  getList(); // 初始化列表数据
  const first = deptOptions.value[0];
  expandKeys.value = [first.id as number];
});
</script>

<style lang="scss" scoped>
.el-tree > :nth-child(n + 1) {
  display: inline-block !important;
  min-width: 100% !important;
}
</style>
