<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">台账管理</span>
    </div>
    <div>
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>关键字 : </span>
            <el-input :clearable="true" @clear="searchBtn" v-model="searchInput.keyWord" class="w-50 m-2"
              placeholder="请输入订单、预定人、手机号" style="width: 250px" />
          </div>
          <div class="condition">
            <span>支付时间 : </span>
            <el-date-picker v-model="searchInput.createTime" type="daterange" range-separator="-" start-placeholder="起始时间"
              end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :prefix-icon="Calendar"
              placeholder="请选择日期" />
          </div>

          <el-button style="margin-left: 20px" color="rgba(9, 101, 98, 1)" type="primary" class="search"
            @click="searchBtn"><el-icon>
              <Search />
            </el-icon> <span>查询</span></el-button>
          <el-button style="margin-left: 20px" color="rgba(9, 101, 98, 1)" type="primary" class="search"
            @click="importExcel"><span>导出订单</span></el-button>
        </div>
      </div>
      <div class="footer" v-loading="loading">
        <el-table :row-class-name="tableRowClassName" :data="tableData.list" @selection-change="handleSelectionChange"
          style="width: 100%" :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }">
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <!-- <el-table-column
              width="150"
              align="center "
              type="index"
              label="序号"
            /> -->
          <el-table-column align="center" prop="orderNum" label="已消费订单号" />

          <el-table-column align="center" prop="userName" label="预订人" />
          <el-table-column align="center" prop="userPhone" label="手机号码" />
          <el-table-column align="center" prop="houseOrderNumber" label="房间数(间)" />
          <el-table-column align="center" prop="payAccount" label="订单金额(元)" />

          <el-table-column align="center" prop="payTime" label="支付时间" />

          <!-- <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="150"
          >
            <template #default="scope">
              <div class="edit">
                <div class="look" @click="edit(scope.row)">编辑</div>
                <el-popconfirm
                  width="220"
                  confirm-button-text="确认"
                  cancel-button-text="取消"
                  :icon="InfoFilled"
                  icon-color="#f89626"
                  title="是否删除此员工?"
                  @confirm="del(scope.row)"
                  @cancel="cancelEvent"
                >
                  <template #reference>
                    <div class="look">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pageSize">
        <span></span>
        <el-pagination background :current-page="currentPage" :page-size="pageSize"
          layout="total, prev, pager, next, jumper, slot" :total="total" @update:current-page="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  nextTick,
  watch,
  onBeforeMount,
  onUnmounted,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();
// 表格数据
const loading = ref(false);
const tableData = reactive({
  list: [
    // {
    //   userName: "111233342",
    //   userName2: "张三",
    //   userPhone: "1121311",
    //   teamName: 12,
    //   schoolName: 1200,
    //   workTypeName: "2023-08-01 12:09:08",
    // },
    // {
    //   userName: "111233342",
    //   userName2: "张三",
    //   userPhone: "1121311",
    //   teamName: 12,
    //   schoolName: 1200,
    //   workTypeName: "2023-08-01 12:09:08",
    // },
    // {
    //   userName: "111233342",
    //   userName2: "张三",
    //   userPhone: "1121311",
    //   teamName: 12,
    //   schoolName: 1200,
    //   workTypeName: "2023-08-01 12:09:08",
    // },
    // {
    //   userName: "111233342",
    //   userName2: "张三",
    //   userPhone: "1121311",
    //   teamName: 12,
    //   schoolName: 1200,
    //   workTypeName: "2023-08-01 12:09:08",
    // },
    // {
    //   userName: "111233342",
    //   userName2: "张三",
    //   userPhone: "1121311",
    //   teamName: 12,
    //   schoolName: 1200,
    //   workTypeName: "2023-08-01 12:09:08",
    // },
  ],
});

// 添加员工弹窗数据 (------------------------------------)
const dialongTitle = ref("添加员工"); // 弹窗标题

const checkAll = ref(false); // 判断物品种类是否全选
const articleIdsList = ref(); //  关联报修类型数据
const isIndeterminate = ref(false); // 不确定状态，表示只选择一部分
const checkedCities = ref([]); // 选中的数据

const userzzIdsList = ref(); //  身份下拉数据
const workTypeList = ref(); //  工种下拉数据
const props = reactive();
const treeValue = reactive({}); // 关联楼栋树形结构数据

const searchInput = reactive({
  keyWord: "",
  teamId: "",
  schoolId: "",
  createTime: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据

const addDialogVisible = ref(false); // 控制添加员工弹窗

// 添加员工表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const articleIdsRef = ref(); // 关联报修类型ref
const buildIdsRef = ref(); // 关联楼栋ref
const ruleForm = reactive({
  userName: "",
  cardNumber: "",
  userzzId: "",
  userPhone: "",
  schoolId: "",
  workType: "",
  articleIds: [],
  buildIds: [],
  teamId: "",
  acceptanceTime: "",
  maintenanceTime: "",
  id: "",
});
// 表单验证
const rules = reactive({
  // serial: [{ required: true, message: "序列号不能为空", trigger: "blur" }],
  userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  cardNumber: [
    { required: true, message: "微校卡号不能为空", trigger: "blur" },
  ],
  userzzId: [{ required: true, message: "身份不能为空", trigger: "blur" }],
  userPhone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
  schoolId: [{ required: true, message: "校区不能为空", trigger: "blur" }],
  workType: [{ required: true, message: "工种不能为空", trigger: "blur" }],
  teamId: [{ required: true, message: "维修班不能为空", trigger: "blur" }],
  articleIds: [
    { required: true, message: "关联报修类型不能为空", trigger: "blur" },
  ],
  buildIds: [{ required: true, message: "关联楼栋不能为空", trigger: "blur" }],
  acceptanceTime: [
    { required: true, message: "接单考核时间不能为空", trigger: "blur" },
  ],
  maintenanceTime: [
    { required: true, message: "维修考核时间不能为空", trigger: "blur" },
  ],
});

watch(
  () => searchInput.createTime,
  (newVal, oldVal) => {
    console.log("监听时间:", newVal);
    if (newVal == null) {
      getList();
    }
  }
);

// 查看员工列表
const getList = async () => {
  loading.value = true;
  let data = {
    page: currentPage.value,
    rows: pageSize.value,
    ledgerParam: searchInput.keyWord, // 关键字查询
    managerId: sessionStorage.getItem("token"),
  };
  if (searchInput.createTime) {
    data.payStartTime = searchInput.createTime[0];
    data.payEndTime = searchInput.createTime[1];
  }
  let res = await axios({
    method: "post",
    url: api.value + "/mhotel/bookquearyLedgerPage.action",
    headers: {
      // token: sessionStorage.getItem("token"),
      // user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, "台账数据");
  if (res.data.code == 200) {
    tableData.list = res.data.data.bookIPage.pageList;
    total.value = res.data.data.bookIPage.total;
    loading.value = false;
    // ElMessage({
    //   type: "success",
    //   showClose: true,
    //   message: res.data.message,
    //   center: true,
    // });
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);

// 改变校区  关联楼栋和关联报修类型也改变(---------------)
const changeSchool = async (val) => {
  if (val == 1) {
    ruleForm.schoolId = 1;
  } else {
    ruleForm.schoolId = 2;
  }
  //  报修（故障类型）类型关联 (接口-------)
  let data = {
    schoolId: val,
  };
  let resss = await axios({
    method: "get",
    url: api.value + "/repairArticleType/queryRepairArticleType",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(resss, "报修（故障类型）类型关联数据");
  articleIdsList.value = resss.data.data;
  // 关联楼栋数据 （接口---------）
  let datas = { schoolId: val };
  let res = await axios({
    method: "get",
    url: api.value + "/repairArea/queryRepairAreaSecond",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: datas,
  });
  console.log(res, "关联楼栋数据");
  treeValue.list = res.data.data;
};

//新增员工 （--------------------------------------）
const addlist = async () => {
  dialongTitle.value = "添加员工";
  changeSchool(1);
  addDialogVisible.value = true;
  ruleForm.userName = "";
  ruleForm.cardNumber = "";
  ruleForm.userzzId = "";
  ruleForm.userPhone = "";
  ruleForm.workType = "";
  ruleForm.articleIds = [];
  ruleForm.buildIds = [];
  ruleForm.teamId = "";
  ruleForm.acceptanceTime = "";
  ruleForm.maintenanceTime = "";
  ruleForm.id = "";
};
// 种类是否全选按钮
// const handleCheckAllChange = (val) => {
//   console.log(val);
//   console.log(articleIdsList.value);
//   let checkedCitie = [];
//   articleIdsList.value.forEach((item) => {
//     checkedCitie.push(item.name);
//   });
//   checkedCities.value = val ? checkedCitie : [];
//   isIndeterminate.value = false;
// };
// //单独勾选种类
// const handleCheckedCitiesChange = (value) => {
//   console.log(value);
//   const checkedCount = value.length;
//   checkAll.value = checkedCount === articleIdsList.value.length;
//   isIndeterminate.value =
//     checkedCount > 0 && checkedCount < articleIdsList.value.length;
// };

// 关联报修类型  当复选框被点击的时候触发
const handleArticleIds = (data, checked, indeterminate) => {
  console.log(data, checked, indeterminate);
  // let keys = articleIdsRef.value.getCheckedNodes();
  let keys = articleIdsRef.value.getCheckedKeys();
  // console.log(keys);
  // let arr = [];
  // keys.forEach((item) => {
  //   if (item.parentId != 1) {
  //     arr.push(item.id);
  //   }
  // });
  ruleForm.articleIds = keys;
};
//  关联楼栋 当复选框被点击的时候触发
const handleCheckChange = (data, checked, indeterminate) => {
  // console.log(data, checked);
  let keys = buildIdsRef.value.getCheckedNodes();
  let arr = [];
  keys.forEach((item) => {
    if (item.parentId != 1) {
      arr.push(item.id);
    }
  });
  ruleForm.buildIds = arr;
};

//编辑按钮  （-------------------------------------------）
const edit = (row) => {
  changeSchool(row.schoolId);
  // console.log(row.articleIds, row.buildIds);
  dialongTitle.value = "编辑员工";
  addDialogVisible.value = true;
  ruleForm.userName = row.userName;
  ruleForm.cardNumber = row.cardNumber;
  ruleForm.userzzId = row.userZzid;
  ruleForm.userPhone = row.userPhone;
  ruleForm.schoolId = row.schoolId;
  ruleForm.workType = row.workType;
  ruleForm.teamId = row.teamId;
  ruleForm.acceptanceTime = row.acceptanceTime;
  ruleForm.maintenanceTime = row.maintenanceTime;
  ruleForm.id = row.id;
  nextTick(() => {
    articleIdsRef.value.setCheckedKeys(row.articleIds);
    buildIdsRef.value.setCheckedKeys(row.buildIds);
  });
  ruleForm.articleIds = row.articleIds;
  ruleForm.buildIds = row.buildIds;
};
// 取消添加员工
const cancelAdd = () => {
  addDialogVisible.value = false;
  ruleFormRef.value.resetFields();
};
// 确认添加员工
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "添加员工") {
        let data = {
          userName: ruleForm.userName,
          cardNumber: ruleForm.cardNumber,
          userzzId: ruleForm.userzzId,
          userPhone: ruleForm.userPhone,
          schoolId: ruleForm.schoolId,
          workType: ruleForm.workType,
          articleIds: ruleForm.articleIds,
          buildIds: ruleForm.buildIds,
          teamId: ruleForm.teamId,
          acceptanceAssessTime: ruleForm.acceptanceTime,
          maintenanceAssessTime: ruleForm.maintenanceTime,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairUser/insertRepairUserSetting",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        console.log(res, "添加员工");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        let data = {
          userName: ruleForm.userName,
          cardNumber: ruleForm.cardNumber,
          userzzId: ruleForm.userzzId,
          userPhone: ruleForm.userPhone,
          schoolId: ruleForm.schoolId,
          workType: ruleForm.workType,
          articleIds: ruleForm.articleIds,
          buildIds: ruleForm.buildIds,
          teamId: ruleForm.teamId,
          acceptanceAssessTime: ruleForm.acceptanceTime,
          maintenanceAssessTime: ruleForm.maintenanceTime,
          id: ruleForm.id,
        };
        let res = await axios({
          method: "post",
          url: api.value + "/repairUser/updateRepairUserSettingById",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        console.log(res, "编辑员工");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//删除按钮
const del = async (row) => {
  let data = {
    id: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairUser/deleteRepairUserSettingById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  if (res.data.code == 200) {
    if (tableData.list.length == 1 && currentPage.value != 1) {
      currentPage.value = currentPage.value - 1;
    }
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  console.log(res);
};

// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};
//导出功能
const importExcel = lodash.debounce(async () => {
  let data = {
    ledgerParam: searchInput.keyWord, // 关键字查询
    managerId: sessionStorage.getItem("token"),
  };
  if (searchInput.createTime) {
    data.payStartTime = searchInput.createTime[0];
    data.payEndTime = searchInput.createTime[1];
  }
  let res = await axios({
    method: "post",
    url: api.value + "/mhotel/booktoLedgerExcel.action",
    headers: {
      // token: sessionStorage.getItem("token"),
    },
    params: data,
  });
  console.log(res, "导出台账管理");
  if (res.data.code == 200) {
    var downloadPath = res.data.downurl;
    // window.open(downloadPath);
    window.location.href = downloadPath;
    var downloadLink = document.createElement("a");
    downloadLink.style.display = "none"; // 使其隐藏
    downloadLink.href = downloadPath;
    downloadLink.download = "";
    downloadLink.click();
    document.body.appendChild(downloadLink);
    document.body.removeChild(downloadLink);
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
}, 1000);

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

onBeforeMount(async () => {
  api.value = store.state.user.api;
  getList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: 97.5%;
  height: 89%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: rgb(0, 0, 0);
    font-size: 18px;
    font-weight: 600;

    span {
      margin-right: 20px;
      cursor: pointer;
    }

    .is_active {
      color: rgba(111, 182, 184, 1);
    }
  }

  .middle {
    width: 96%;
    margin: 0 auto;

    color: #000;

    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin: 15px 0 15px 0;

      .search {
        color: #fff;
      }

      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;

        :deep(.el-input .el-input__inner) {
          font-size: 14px;
        }

        span {
          margin: 0 10px 0 0;
        }
      }
    }

    .gongneng {
      margin: 10px 0 20px 0;

      span {
        color: #fff;
      }
    }

    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }

    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }

    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }

    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }

  .footer {
    width: 96%;
    height: 550px;
    margin: 10px auto 30px;

    .el-table--fit {
      height: 100%;

      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 15px;

        tr {
          color: #000;
        }
      }

      :deep(.el-table__row) {
        height: 50px;
        font-size: 15px;
        color: #000;
      }

      :deep(.el-table__row):nth-child(2n) {
        .el-table-fixed-column--right {
          background-color: rgba(240, 243, 247, 1);
        }
      }

      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }

      :deep(.el-table__body .even) {
        background-color: #fff;
      }

      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }

      :deep(.edit) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(111, 182, 184, 1);
      }

      :deep(.look) {
        padding: 0 10px;
        cursor: pointer;
      }

      :deep(.look):hover {
        color: red;
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;

      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;

        .el-dialog__headerbtn {
          outline: none;
        }
      }

      .el-dialog__body {
        padding: 30px 20px 10px 20px;

        .el-input {
          width: 200px;
        }

        // 关联报修类型样式（-----------------）
        // .checkbox {
        //   .el-form-item__content {
        //     display: flex;
        //     flex-direction: column;
        //     align-items: flex-start;
        //     .el-checkbox-group {
        //       display: flex;
        //       flex-direction: column;
        //     }
        //   }
        // }

        .options {
          .el-form-item__content {
            .queding {
              margin-left: 20px;
              color: #fff;
            }

            display: flex;
            flex-direction: row-reverse;
          }
        }
      }
    }
  }

  .pageSize {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 30px;

    span {
      color: #000;
    }

    .el-pagination {

      // width: 1600px;
      :deep(.el-pagination__total) {
        color: #000;
      }

      :deep(.el-pagination__goto) {
        color: #000;
      }

      :deep(.el-pagination__classifier) {
        color: #000;
      }

      :deep(.el-input__wrapper) {
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        box-shadow: none;
      }

      :deep(.el-pager li) {
        margin: 0 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.el-pager li.is-active) {
        background-color: rgba(111, 182, 184, 1);
      }

      :deep(.btn-prev) {
        margin-right: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.btn-next) {
        margin-left: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }
    }
  }
}

.el-input {
  width: 192px;
}
</style>
