<template>
  <div class="back-color" style="overflow-y: hidden">
    <t-layout style="height: 100%; background-color: #f5f7fb">
      <t-aside class="asideTree">
        <t-space direction="vertical">
          <t-tree
            :data="personName"
            hover
            transition
            activable
            expandAll
            :expand-mutex="mutex"
            expand-on-click-node="true"
            @click="onClick"
          />
        </t-space>
      </t-aside>
      <t-content>
        <t-layout style="height: 100%; background-color: #f5f7fb">
          <t-header class="scarch-box">
            <t-form
              ref="form"
              :data="scarchData"
              label-width="calc(2em + 40px)"
              layout="inline"
              scroll-to-first-error="smooth"
              class="scarch-from"
              @reset="resetting"
              @submit="headerQuery"
            >
              <div style="margin-left: 1rem; margin-top: 1px">
                <t-form-item label="票据编号:" name="billserial">
                  <t-input
                    v-model="scarchData.billserial"
                    maxlength="10"
                  ></t-input>
                </t-form-item>

                <t-form-item label="退领时间:" name="receiptDate">
                  <t-date-picker v-model="scarchData.receiptDate" clearable />
                </t-form-item>
                <t-form-item
                  label="票据类型:"
                  name="billType"
                  style="margin-bottom: 0.3rem"
                >
                  <t-select
                    v-model="scarchData.billType"
                    placeholder="请选择票据类型"
                    clearable
                  >
                    <t-option
                      v-for="item in billType"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    ></t-option>
                  </t-select>
                </t-form-item>
              </div>
              <t-form-item style="margin-right: 1rem">
                <t-button theme="primary" type="submit">查询</t-button>
                <t-button theme="primary" type="reset">重置</t-button>
              </t-form-item>
            </t-form>
          </t-header>
          <t-content class="table-box">
            <div class="table-header">
              <div>
                <h4 style="font-size: 110%">票据退领列表</h4>
              </div>
              <div>
                <t-button
                  shape="circle"
                  theme="primary"
                  @click="refresh"
                  style="margin-left: 0.8rem"
                >
                  <template #icon><load-icon /></template>
                </t-button>
              </div>
            </div>
            <t-base-table
              hover
              row-key="index"
              :loading="loading"
              :data="tableData"
              :columns="columns"
              :pagination="pagination"
              class="table"
              :max-height="550"
            >
              <template #billType="{ row }">
                <div v-for="item in billType" :key="item">
                  <span v-if="row.billType === item.value">{{
                    item.label
                  }}</span>
                </div>
              </template>
              <template #receiptNum="{ row }">
                {{ `${row.receiptNum}张` }}
              </template>
            </t-base-table>
          </t-content>
        </t-layout>
      </t-content>
    </t-layout>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
import { LoadIcon } from "tdesign-icons-vue-next";
import { useReceiptList } from "@/stores/billReceipt";

const receiptList = useReceiptList();
const personName = ref([]);
const tableData = ref([]);
const data = ref([]);
const loading = ref(false);
const visiblePost = ref(false);
const columns = ref([
  {
    colKey: "serial-number",
    title: "序号",
    width: 50,
  },
  {
    colKey: "billserial",
    title: "票据编号",
    align: "center",
    width: 100,
  },
  {
    colKey: "proposer",
    title: "申请人",
    align: "center",
    width: 100,
  },
  {
    colKey: "billType",
    title: "票据类型",
    align: "center",
    width: 100,
  },
  {
    colKey: "quitneckNum",
    title: "退领数量",
    align: "center",
    width: 100,
  },
  {
    colKey: "quitneckDate",
    title: "退领时间",
    align: "center",
    width: 100,
  },
  {
    colKey: "quitneckInfo",
    title: "退领原来",
    ellipsis: true,
    align: "center",
    width: 200,
  },
]);
// 票据类型
const billType = ref([
  { label: "票据类型1", value: 0 },
  { label: "票据类型2", value: 1 },
  { label: "票据类型3", value: 2 },
  { label: "票据类型4", value: 3 },
  { label: "票据类型5", value: 4 },
]);
const dialogData = ref({
  quitneckDate: "",
  quitneckReason: "",
  quitneckNum: "",
});

// 查询表单
const scarchData = ref({
  billserial: "",
});

// 分页
const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 50,
});

// 获取票据列表
const personList = async () => {
  personName.value = await receiptList.getPersonNameList();
};

// 效验规则
const FORM_RULES = {
  quitneckNum: [{ required: true, message: "请输入退领张数", trigger: "blur" }],
  quitneckDate: [
    { required: true, message: "请选择退领日期", trigger: "change" },
  ],
  quitneckReason: [
    { required: true, message: "请输入退领原因", trigger: "blur" },
  ],
};

// 查询
const headerQuery = () => {
  tableData.value = data.value;
  console.log(
    scarchData.value.billserial,
    scarchData.value.billType,
    scarchData.value.receiptDate
  );
  if (
    scarchData.value.billserial === "" &&
    (scarchData.value.billType === undefined ||
      scarchData.value.billType === "") &&
    (scarchData.value.receiptDate === undefined ||
      scarchData.value.receiptDate === "")
  ) {
    getNewTable();
  } else {
    const list = tableData.value.filter((item) => {
      let arrList;
      if (scarchData.value.billserial === item.billserial) {
        arrList = item;
      }
      if (scarchData.value.billType === item.billType) {
        arrList = item;
      }
      if (scarchData.value.receiptDate === item.receiptDate) {
        arrList = item;
      }
      if (
        scarchData.value.billserial === "" &&
        scarchData.value.billType === "" &&
        scarchData.value.receiptDate === ""
      ) {
        arrList = item;
      }
      return arrList;
    });
    tableData.value = list;
    pagination.value.total = list.length;
  }
};
// 查询表单重置
const resetting = () => {
  scarchData.value = {
    billserial: "",
    billType: "",
    receiptDate: "",
  };
  getNewTable();
};
const rowItem = ref({});
const Quitneck = (value) => {
  dialogData.value = {
    quitneckDate: "",
    quitneckReason: "",
    quitneckNum: "",
  };
  visiblePost.value = true;
  rowItem.value = value;
};
//  表单提交
const quitneckAdd = async ({ validateResult, firstError }) => {
  if (validateResult === true) {
    if (rowItem.value.row.receiptNum - dialogData.value.quitneckNum < 0) {
      return MessagePlugin.error("退领数量不能大于领用数量");
    }
    dialogData.value.quitneckNum =
      rowItem.value.row.receiptNum - dialogData.value.quitneckNum;
    dialogData.value.id = rowItem.value.row.id;
    await receiptList.getquitneckNum(dialogData.value);
    getTableData();
    MessagePlugin.success("提交成功");
    visiblePost.value = false;
  } else {
    console.log("Validate Errors: ", firstError, validateResult);
  }
};
const onClick = async (context) => {
  // 判断是否为顶层节点（无父节点）
  if (context.node.value === "t1") {
    return;
  }
  loading.value = true;
  // 获取票据列表
  tableData.value = await receiptList.getReceiptList({
    name: context.node.label,
  });
  data.value = await receiptList.getReceiptList({
    name: context.node.label,
  });
  pagination.value.total = tableData.value.length;
  const timerId = setTimeout(() => {
    loading.value = false;
    clearInterval(timerId);
  }, 300);
};
// 刷新列表
const refresh = () => {
  getTableData();
};
// 判断menuManagement里面是否存在数据
const getPersonName = () => {
  let arr = JSON.parse(localStorage.getItem("ReceiptList"));
  if (arr) {
    personName.value = arr.personName;
  } else {
    personList();
  }
};
// 判断menuManagement里面是否存在数据
const getTableData = async () => {
  let arr = JSON.parse(localStorage.getItem("ReceiptList"));
  if (arr.receiptList.length > 0) {
    loading.value = true;
    tableData.value = arr.receiptList;
    pagination.value.total = tableData.value.length;
    const timerId = setTimeout(() => {
      loading.value = false;
      clearInterval(timerId);
    }, 300);
  } else {
    await nextTick();
    // 找到第一个具有子节点的节点并模拟点击
    const firstNodeWithChildren = personName.value.find(
      (node) => Array.isArray(node.children) && node.children.length > 0
    );
    if (firstNodeWithChildren) {
      const simulatedContext = {
        node: {
          label: "孙东宇",
        },
      };
      onClick(simulatedContext);
    }
  }
};

onMounted(async () => {
  getPersonName();
  getTableData();
  // 等待 personName 数据加载完成
});
</script>

<style scoped lang="less">
.asideTree {
  margin-right: 2rem;
  display: flex;
  justify-content: center;
  padding: 1rem;
}
.scarch-box {
  width: 100%;
  background-color: @base-white-color;
  margin-bottom: 2rem;
  .scarch-from {
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.table-box {
  height: 41rem;
  background-color: @base-white-color;
  padding: 1rem;
  padding-top: 0;
  .table-header {
    height: 3rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
:deep(.t-tree--transition .t-tree__label) {
  width: 10rem;
}
:deep(.t-form__controls-content) {
  justify-content: space-between;
}
</style>
