<template>
  <div style="padding: 0 20px 100px; background-color: white; margin: 0 auto">
    <div style="">
      <div style="margin-top: 20px">
        <el-form
          :inline="true"
          :model="searchForm"
          ref="search1"
          class="demo-form-inline"
        >
          <el-form-item label="图书名称">
            <el-input
              v-model="searchForm.bookName"
              placeholder="请输入图书名称"
            />
          </el-form-item>
          <el-form-item label="借阅人">
            <el-input
              v-model="searchForm.borrowPerson"
              placeholder="请输入借阅人姓名"
            />
          </el-form-item>
          <el-form-item label="借阅日期">
            <el-date-picker
              v-model="searchForm.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button style="float: right" type="primary" @click="search"
              ><el-icon> <Search /> </el-icon>搜索</el-button
            >
            <el-button style="float: right" type="" @click="refresh"
              ><el-icon> <RefreshRight /> </el-icon>重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div>
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs"
        @tab-click="handleClick"
      >
        <el-tab-pane label="未归还" name="first">
          <el-table
            :data="tableData"
            v-loading="tabLoading"
            style="width: 100%"
          >
            <el-table-column
              label="序号"
              width="80"
              align="center"
              type="index"
            >
            </el-table-column>
            <el-table-column
              label="图书名称"
              prop="bookName"
              width="240"
              align="center"
            >
            </el-table-column>
            <el-table-column label="封面" width="100" align="center">
              <template #default="scope">
                <!-- <img :src="scope.row.img" style="width: 100%;" alt="" /> -->
                <el-image
                  style="width: 100%"
                  :src="scope.row.img"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  z-index="999"
                  preview-teleported
                  :preview-src-list="[scope.row.img]"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="借阅数量"
              prop="borrowNumber"
              align="center"
            ></el-table-column>
            <el-table-column
              label="借阅人"
              prop="borrowPerson"
              align="center"
            ></el-table-column>
            <el-table-column label="借阅期限" align="center">
              <template #default="scope">
                {{ scope.row.borrowDate + " 至 " + scope.row.returnDate }}
              </template>
            </el-table-column>
            <el-table-column label="借阅状态" align="center">
              <template #default="scope">
                <dict-tag
                  :options="book_borrow_state"
                  :value="scope.row.state"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="returnBook(scope.$index, scope.row)"
                  >归还</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 20px; float: right"
            v-model:page-size="pageSize4"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>
        <el-tab-pane label="已逾期" name="second">
          <el-table
            :data="tableData"
            v-loading="tabLoading"
            style="width: 100%"
          >
            <el-table-column
              label="序号"
              width="80"
              align="center"
              type="index"
            >
            </el-table-column>
            <el-table-column
              label="图书名称"
              prop="bookName"
              width="240"
              align="center"
            >
            </el-table-column>
            <el-table-column label="封面" width="100" align="center">
              <template #default="scope">
                <!-- <img :src="scope.row.img" style="width: 100%;" alt="" /> -->
                <el-image
                  style="width: 100%"
                  :src="scope.row.img"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  z-index="999"
                  preview-teleported
                  :preview-src-list="[scope.row.img]"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="借阅数量"
              prop="borrowNumber"
              align="center"
            ></el-table-column>
            <el-table-column
              label="借阅人"
              prop="borrowPerson"
              align="center"
            ></el-table-column>
            <el-table-column label="借阅期限" align="center">
              <template #default="scope">
                {{ scope.row.borrowDate + " 至 " + scope.row.returnDate }}
              </template>
            </el-table-column>
            <el-table-column label="借阅状态" align="center">
              <template #default="scope">
                <dict-tag
                  :options="book_borrow_state"
                  :value="scope.row.state"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="returnBook(scope.$index, scope.row)"
                  >归还</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="margin-top: 20px; float: right"
            v-model:page-size="pageSize4"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 归还图书弹窗 -->
    <el-dialog
      v-model="returnShow"
      title="图书归还"
      width="50%"
      :before-close="returnClose"
    >
      <div>
        <el-form
          :model="returnForm"
          ref="returnForm1"
          class="demo-form-inline"
          :rules="returnRules"
          :label-position="right"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="图书名称" prop="title">
                <el-input
                  v-model="returnForm.bookName"
                  placeholder="请输入图书名称"
                  readonly
                />
              </el-form-item>
              <el-form-item label="借阅人" prop="borrowPerson">
                <el-input
                  v-model="returnForm.borrowPerson"
                  placeholder="请输入图书作者"
                  readonly
                />
              </el-form-item>
              <el-form-item label="借阅部门" prop="borrowDept">
                <el-input
                  v-model="returnForm.borrowDept"
                  placeholder="请输入图书版本"
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="借阅数量" prop="borrowNumber">
                <el-input
                  v-model="returnForm.borrowNumber"
                  placeholder="请输入库存余量"
                  readonly
                />
              </el-form-item>
              <!-- <el-form-item label="归还人" prop="returnPerson">
								<div style="display: flex;align-items: center;">
									<div style="width: 70%;">
										<el-input v-model="returnForm.returnPerson" placeholder="请输入借阅部门" readonly />
									</div>
									<div style="width:30%;">
										<el-button type="primary" size="default"
											@click="userShow = true">选择人员</el-button>
									</div>
								</div>
							</el-form-item> -->
              <el-form-item label="归还数量" prop="returnNumber">
                <el-input
                  v-model="returnForm.returnNumber"
                  type="number"
                  placeholder="请输入借阅数量"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnClose">取消</el-button>
          <el-button type="primary" @click="returnSubmit" :loading="returnBtn">
            归还
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 人员选择弹窗 -->
    <el-dialog v-model="userShow" title="借阅人员选择" width="50%">
      <div>
        <el-row :gutter="20">
          <!--部门数据-->
          <el-col :span="8" :xs="24">
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                prefix-icon="Search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="deptOptions"
                :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>
          <!--用户数据-->
          <el-col :span="16" :xs="24">
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
            >
              <el-form-item label="用户名称" prop="userName">
                <el-input
                  v-model="queryParams.userName"
                  placeholder="请输入用户名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                  >搜索</el-button
                >
                <el-button icon="RefreshRight" @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>

            <el-table
              v-loading="userLoading"
              :data="userList"
              @current-change="selectPeo"
            >
              <el-table-column
                label="用户昵称"
                align="center"
                key="nickName"
                prop="nickName"
                v-if="columns[2].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="部门"
                align="center"
                key="deptName"
                prop="dept.deptName"
                v-if="columns[3].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="手机号码"
                align="center"
                key="phonenumber"
                prop="phonenumber"
                v-if="columns[4].visible"
              />
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { Timer } from "@element-plus/icons-vue";
import { borrowPeople, bookReturn } from "@/api/books/economizingSchedule";
import { ElMessage, ElMessageBox } from "element-plus";
import { listUser, getUser, deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { book_borrow_state } = proxy.useDict("book_borrow_state");
const activeName = ref("first");
const userList = ref([]);
const userLoading = ref(true);
const showSearch = ref(true);
const userTotal = ref(0);
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const userShow = ref(false);
// 列显隐信息
const columns = ref([
  {
    key: 0,
    label: `用户编号`,
    visible: true,
  },
  {
    key: 1,
    label: `用户名称`,
    visible: true,
  },
  {
    key: 2,
    label: `用户昵称`,
    visible: true,
  },
  {
    key: 3,
    label: `部门`,
    visible: true,
  },
  {
    key: 4,
    label: `手机号码`,
    visible: true,
  },
  {
    key: 5,
    label: `状态`,
    visible: true,
  },
  {
    key: 6,
    label: `创建时间`,
    visible: true,
  },
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: 0,
    deptId: undefined,
  },
});

const { queryParams } = toRefs(data);
// 顶部搜索
const searchForm = ref({
  title: null,
  pageSize: 10,
  pageNum: 1,
  start: null,
  end: null,
  borrowPerson: null,
  time: [],
  state: 0,
});
const input = ref("");
const value2 = ref("");
const pageSize4 = ref(100);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
//表格相关
const tableData = ref([]);
const total = ref(null);
const tabLoading = ref(false);
//归还相关
const returnShow = ref(false);
const returnForm = ref({
  borrowId: null,
  bookName: null,
  borrowDept: null,
  borrowPerson: null,
  borrowDate: null,
  userId: null,
  returnPerson: null,
  returnNumber: null,
  returnUserId: null,
  borrowNumber: null,
});
const validatePass1 = (rule, value, callback) => {
  if (value === "" || value === null) {
    callback(new Error("请输入归还数量"));
  } else if (value <= 0) {
    callback(new Error("归还数量需大于0"));
  } else if (value > returnForm.value.borrowNumber) {
    callback(new Error("归还数量不能大于借阅数量"));
  } else {
    callback();
  }
};
const returnRules = {
  returnPerson: [
    {
      required: true,
      trigger: "change",
      message: "请选择归还人",
    },
  ],
  returnNumber: [
    {
      required: true,
      validator: validatePass1,
      trigger: "change",
    },
  ],
};
const returnBtn = ref(false);
// 分页
const handleSizeChange = (val) => {
  searchForm.value.pageNum = val;
  getList();
};
const handleCurrentChange = (val) => {
  searchForm.value.pageNum = val;
  getList();
};
//获取借阅列表
function getList() {
  tabLoading.value = true;
  borrowPeople(searchForm.value).then((res) => {
    tableData.value = res.rows;
    total.value = res.total;
    setTimeout(() => {
      tabLoading.value = false;
    }, 1000);
  });
}
//根据条件查询借阅信息
function search() {
  if (searchForm.value.time.length != 0) {
    searchForm.value.start = searchForm.value.time[0];
    searchForm.value.end = searchForm.value.time[1];
  }
  searchForm.value.pageNum = 1;
  getList();
}
//重置搜索内容
function refresh() {
  searchForm.value = {
    title: null,
    pageSize: 10,
    pageNum: 1,
    start: null,
    end: null,
    borrowPerson: null,
    time: [],
  };
  getList();
}
//归还图书
function returnBook(index, row) {
  returnForm.value = {
    borrowId: row.id,
    bookName: row.bookName,
    borrowDept: row.borrowDept,
    borrowPerson: row.borrowPerson,
    borrowDate: row.borrowDate,
    borrowNumber: row.borrowNumber,
    userId: row.userId,
    returnPerson: row.borrowPerson,
    returnNumber: row.borrowNumber,
    returnUserId: row.userId,
  };
  returnShow.value = true;
}
function returnSubmit() {
  proxy.$refs.returnForm1.validate((valid) => {
    if (valid) {
      returnBtn.value = true;
      bookReturn(returnForm.value).then((res) => {
        ElMessage({
          message: "归还成功",
          type: "success",
        });
        returnBtn.value = false;
        returnShow.value = false;
        getList();
      });
    } else {
    }
  });
}
function returnClose() {
  returnForm.value = {
    borrowId: null,
    bookName: null,
    borrowDept: null,
    borrowPerson: null,
    borrowDate: null,
    userId: null,
    returnPerson: null,
    returnNumber: null,
    returnUserId: null,
    borrowNumber: null,
  };
  proxy.$refs.returnForm1.resetFields();
  returnShow.value = false;
}
//
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
/** 查询用户列表 */
function getUserList() {
  userLoading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      userLoading.value = false;
      userList.value = res.rows;
      userTotal.value = res.total;
    }
  );
}
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getUserList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}
//选择用户
function selectPeo(val) {
  returnForm.value.returnUserId = val.userId;
  returnForm.value.returnPerson = val.nickName;
  userShow.value = false;
}
function handleClick(tab, event) {
  if (tab.index == "0") {
    searchForm.value.state = 0;
    searchForm.value.pageNum = 1;
    getList();
  } else {
    searchForm.value.state = 2;
    searchForm.value.pageNum = 1;
    getList();
  }
}
//
getList();
getDeptTree();
getUserList();
</script>

<style lang="scss" scoped></style>
