<!--
 * @Author: 倚楼听风雨 18408246387@163.com
 * @Date: 2022-11-16 17:16:17
 * @LastEditors: 倚楼听风雨 18408246387@163.com
 * @LastEditTime: 2023-02-20 15:47:22
 * @FilePath: \log-server-web\src\view\logComputer\list_computer_distinct.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <div class="gva-search-box">
      <div class="gva-btn-list">
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="电脑编号">
            <el-input
              v-model="searchInfo.pc_num"
              placeholder="编号"
              size="small"
            />
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchInfo.shop_id" size="small">
              <el-option
                v-for="item in shopOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="套餐">
            <el-select v-model="searchInfo.set_meal_id" size="small"
              ><el-option
                v-for="item in setMealOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            /></el-select>
          </el-form-item>
          <el-form-item label="日期" prop="new_date">
            <el-date-picker
              v-model="searchInfo.new_date"
              popper-class="picker-popovers"
              class="timefilter"
              type="date"
              :disabled-date="disabledDate"
              :shortcuts="shortcuts"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="是否到期">
            <el-select v-model="searchInfo.is_expire" size="small">
              <el-option label="否" value="0" />
              <el-option label="是" value="1" />
              <el-option label="明日到期" value="2" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button
              size="small"
              type="primary"
              icon="search"
              @click="onSubmit"
              >查询</el-button
            >
            <el-button size="small" icon="refresh" @click="onReset"
              >重置</el-button
            >
            <el-button
              class="excel-btn"
              size="small"
              type="primary"
              icon="download"
              @click="handleExcelRentExport"
              >导出表格</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- <div class="gva-btn-list">
        <el-button
          icon="delete"
          size="small"
          type="danger"
          :disabled="!apis.length"
          style="margin-left: 10px"
          @click="deletesMenu()"
          >删除</el-button
        >
      </div> -->
    </div>
    <div class="row center">
      <el-tag size="large">电脑数量 : {{ computerNum }} </el-tag>
    </div>
    <div class="gva-table-box">
      <el-table
        height="500px"
        :data="tableData"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          align="left"
          label="日期"
          min-width="80"
          prop="new_date"
        />
        <el-table-column
          align="left"
          label="供应商"
          min-width="70"
          prop="shop_name"
        />
        <el-table-column
          align="left"
          label="编号"
          min-width="80"
          prop="pc_num"
        />
        <el-table-column
          align="left"
          label="机房名称"
          min-width="80"
          prop="pc_name"
        />
        <el-table-column
          align="left"
          label="起租时间"
          min-width="150"
          prop="rent_start_then"
        />
        <el-table-column
          align="left"
          label="到期时间"
          min-width="150"
          prop="rent_end_then"
        />
        <el-table-column
          align="left"
          label="租期"
          min-width="50"
          prop="rent_duration_then"
        />
        <el-table-column
          align="left"
          label="套餐"
          min-width="70"
          prop="set_meal_name"
        />
        <el-table-column
          align="left"
          label="价格"
          min-width="70"
          prop="rent_price_then"
        />
        <!-- <el-table-column
          align="center"
          label="套餐"
          min-width="150"
          prop="set_meal_name"
        >
          <template #default="scope">
            <span v-if="scope.row.price_type == 0">{{
              scope.row.set_meal_name +
              "-天卡(" +
              scope.row.rent_price_then +
              "元)"
            }}</span>
            <span v-else-if="scope.row.price_type == 1">{{
              scope.row.set_meal_name +
              "-周卡(" +
              scope.row.rent_price_then +
              "元)"
            }}</span>
            <span v-else>{{
              scope.row.set_meal_name +
              "-月卡(" +
              scope.row.rent_price_then +
              "元)"
            }}</span>
          </template>
        </el-table-column> -->
        <el-table-column
          align="left"
          label="折算天租金"
          min-width="100"
          prop="rent_price_day_then"
        />
        <el-table-column
          align="left"
          label="已产生租金"
          min-width="100"
          prop="rent_price_used_then"
        />
        <!-- <el-table-column
          align="center"
          label="是否到期"
          min-width="100"
          prop="is_expire"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.is_expire == 2"
              size="small"
              type="warning"
              plain
              >即将到期</el-button
            >
            <el-button
              v-if="scope.row.is_expire == 1"
              size="small"
              type="info"
              plain
              >到期未续</el-button
            >
            <el-button
              v-if="scope.row.is_expire == 0"
              size="small"
              type="success"
              plain
              >在租期中</el-button
            >
          </template>
        </el-table-column> -->
        <el-table-column
          align="left"
          label="备注"
          min-width="150"
          prop="remark"
          show-overflow-tooltip
        />
        <el-table-column
          align="left"
          label="更新时间"
          min-width="150"
          prop="update_time"
        />
        <el-table-column align="left" fixed="right" label="操作" width="130">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              icon="edit"
              @click="editMenu(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              link
              icon="delete"
              @click="deleteMenu(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- </el-scrollbar> -->
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "computer",
};
</script>

<script setup>
import {
  getRentComputerLedgerList,
  getRentComputerLedgerNum,
  listRentComputerShopList,
  listRentSetMealList,
  getRentComputerById,
  exportRentLedgerListExcel,
  editRentComputer,
  deleteRentComputerById,
  deleteRentComputerByIds,
} from "@/api/rentComputer";
// import { useUserStore } from "@/pinia/modules/user";
import { toSQLLine } from "@/utils/stringFun";
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/utils/format";
// import { downloadTemplate } from "@/api/excel";
// import dayjs from "dayjs";

const apis = ref([]);
const form = ref({
  id: 0,
  pc_num: "",
  pc_name: "",
  shop_id: null,
  set_meal_id: null,
  todesk_id: "",
  todesk_password: "",
  sunflower_id: "",
  sunflower_password: "",
  rent_start: new Date(),
  rent_duration: 0,
  rent_end: new Date(),
  remark: "",
  // is_expire: -1,
  is_off_shelf: -1,
});
const rules = ref({
  pc_num: [{ required: true, message: "请输入电脑编号", trigger: "blur" }],
  pc_name: [{ required: true, message: "请输入电脑名称", trigger: "blur" }],
  shop_id: [{ required: true, message: "请选择供应商", trigger: "blur" }],
  set_meal_id: [{ required: true, message: "请选择套餐", trigger: "blur" }],
  rent_start: [{ required: true, message: "请选择起租日期", trigger: "blur" }],
  rent_duration: [
    { required: true, message: "请输入租赁天数", trigger: "blur" },
  ],
  // is_expire: [{ required: true, message: "请选择是否到期", trigger: "blur" }],
  // is_off_shelf: [
  //   { required: true, message: "请选择是否下架", trigger: "blur" },
  // ],
});

const page = ref(1);
const total = ref(0);
const pageSize = ref(20);
const tableData = ref([]);
let spanArr = [];
const searchInfo = ref({});
const computerNum = ref("");
const shopOptions = ref();
const setMealOptions = ref();
// const defaultTime = ref(new Date(2000, 1, 1, 12, 0, 0));
// const path = ref(import.meta.env.VITE_BASE_API);
// const userStore = useUserStore();

const shortcuts = [
  {
    text: "今日",
    value: new Date(),
  },
  {
    text: "昨日",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
];
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

// 计算租机到期时间
const calculateRentDuration = async (scope) => {
  scope.rent_end = new Date(
    Date.parse(scope.rent_start) +
      1 * 24 * 60 * 60 * 1000 * parseInt(scope.rent_duration)
  );
};

// const getSpanArr = (data) => {
//   spanArr = [];
//   var pos = 0;
//   for (var i = 0; i < data.length; i++) {
//     if (i === 0) {
//       spanArr.push(1);
//       pos = 0;
//     } else {
//       if (data[i].pc_code === data[i - 1].pc_code) {
//         spanArr[pos] += 1;
//         spanArr.push(0);
//       } else {
//         spanArr.push(1);
//         pos = i;
//       }
//     }
//   }
//   // console.log(spanArr);
// };

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};
const onReset = () => {
  searchInfo.value = {};
};
const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

const handleExcelRentExport = async () => {
  var fileName = "";
  if (searchInfo.value.new_date == null) {
    let dt = new Date(Date.parse(new Date()) - 1 * 24 * 60 * 60 * 1000);
    var y = dt.getFullYear();
    var mt = (dt.getMonth() + 1).toString().padStart(2, "0");
    var day = dt.getDate().toString().padStart(2, "0");
    var timeStr = y + "-" + mt + "-" + day;
    fileName = timeStr + "-租机台账.xlsx";
  } else {
    fileName = searchInfo.value.new_date + "-租机台账.xlsx";
  }
  exportRentLedgerListExcel(
    { page: page.value, pageSize: pageSize.value, ...searchInfo.value },
    fileName
  );
};

// 排序
const sortChange = ({ prop, order }) => {
  if (prop) {
    if (prop === "id") {
      prop = "id";
    }
    searchInfo.value.orderKey = toSQLLine(prop);
    searchInfo.value.desc = order === "descending";
  }
  getTableData();
};

// 搜索
const onSubmit = () => {
  page.value = 1;
  pageSize.value = 20;

  if (typeof searchInfo.value.set_meal_id != "undefined") {
    searchInfo.value.set_meal_id = Number(searchInfo.value.set_meal_id);
  }
  // if (typeof searchInfo.value.is_expire != "undefined") {
  //   searchInfo.value.is_expire = Number(searchInfo.value.is_expire);
  // }
  // if (typeof searchInfo.value.is_off_shelf != "undefined") {
  //   searchInfo.value.is_off_shelf = Number(searchInfo.value.is_off_shelf);
  // }
  // console.log(searchInfo);

  getTableData();
};

// 查询
const getTableData = async () => {
  const table = await getRentComputerLedgerList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value,
  });
  if (table.code === 0) {
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
    // getSpanArr(table.data.list);
    getComputerNum();
    getSelectList();
  }
};

//获取下拉框list
const getSelectList = async () => {
  //listRentComputerShopList
  const rentComputerShop = await listRentComputerShopList({
    page: 1,
    pageSize: 999,
  });
  let rentComputerShopList = [];
  const data = rentComputerShop.data.list;
  data.forEach((e) => {
    rentComputerShopList.push({ value: e.id, label: e.name });
  });
  shopOptions.value = rentComputerShopList;
  //listRentSetMealList
  const setMealShop = await listRentSetMealList({
    page: 1,
    pageSize: 999,
  });
  let setMealList = [];
  const data2 = setMealShop.data.list;
  data2.forEach((e) => {
    var priceStr = "";
    if (e.price_type == 0) {
      priceStr = "天卡(" + e.rent_price + "元)";
    } else if (e.price_type == 1) {
      priceStr = "周卡(" + e.rent_price + "元)";
    } else {
      priceStr = "月卡(" + e.rent_price + "元)";
    }
    setMealList.push({
      value: e.id,
      label: e.shop_name + "-" + e.name + "-" + priceStr,
    });
  });
  setMealOptions.value = setMealList;
};

// 查询
const getComputerNum = async () => {
  const table = await getRentComputerLedgerNum({ ...searchInfo.value });
  if (table.code === 0) {
    // console.log(table.data);
    computerNum.value = table.data;
  }
};
getTableData();

// 批量操作
const handleSelectionChange = (val) => {
  apis.value = val;
};

const dialogFormVisible = ref(false);
// 弹窗相关
const menuForm = ref(null);
const checkFlag = ref(false);
const initForm = () => {
  checkFlag.value = false;
  menuForm.value.resetFields();
  form.value = {
    id: 0,
    coding: "",
    describe: "",
    parent_id: "",
  };
};
const menuOption = ref([
  {
    id: "0",
    title: "根编号",
  },
]);
const setOptions = () => {
  menuOption.value = [
    {
      id: "0",
      title: "根目录",
    },
  ];
  setMenuOptions(tableData.value, menuOption.value, false);
};
const setMenuOptions = (menuData, optionsData, disabled) => {
  menuData &&
    menuData.forEach((item) => {
      if (item.children && item.children.length) {
        const option = {
          ID: String(item.id),
          disabled: disabled || item.id === form.value.id,
          children: [],
        };
        setMenuOptions(
          item.children,
          option.children,
          disabled || item.id === form.value.id
        );
        optionsData.push(option);
      } else {
        const option = {
          ID: String(item.id),
          disabled: disabled || item.id === form.value.id,
        };
        optionsData.push(option);
      }
    });
};

const loadExcel = (res) => {
  if (res.code === 0) {
    ElMessage({
      type: "success",
      message: res.msg,
    });
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
      showClose: true,
    });
  }
  getTableData();
};

// 添加菜单方法，id为 0则为添加根菜单
const isEdit = ref(false);
const dialogTitle = ref("新增租机");
const addMenu = async (id) => {
  dialogTitle.value = "新增租机";
  form.value.parent_id = String(id);
  isEdit.value = false;
  setOptions();
  dialogFormVisible.value = true;
  getSelectList();
};
// 修改菜单方法
const editMenu = async (id) => {
  dialogTitle.value = "编辑租机";
  const res = await getRentComputerById({ id });
  form.value = res.data;
  if (form.value.is_off_shelf == 1) {
    form.value.is_off_shelf = true;
  } else {
    form.value.is_off_shelf = false;
  }
  isEdit.value = true;
  setOptions();
  dialogFormVisible.value = true;
  getSelectList();
};

const closeDialog = () => {
  initForm();
  dialogFormVisible.value = false;
};
// 批量删除菜单
const deletesMenu = async () => {
  ElMessageBox.confirm("确定批量删除所选吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const ids = apis.value.map((item) => item.id);
      // console.log(ids);
      const res = await deleteRentComputerByIds({ ids });
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        getTableData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
// 删除菜单
const deleteMenu = async (id) => {
  ElMessageBox.confirm("确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(id);

      const res = await deleteRentComputerById({ id });
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        getTableData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
// const enterDialog = async () => {
//   //   console.log(form.value);
//   menuForm.value.validate(async (valid) => {
//     if (valid) {
//       let res;
//       form.value.id = Number(form.value.id);
//       form.value.shop_id = Number(form.value.shop_id);
//       form.value.set_meal_id = Number(form.value.set_meal_id);
//       form.value.rent_duration = Number(form.value.rent_duration);
//       form.value.rent_start = formatDate(form.value.rent_start);
//       form.value.rent_end = formatDate(form.value.rent_end);
//       form.value.is_expire = Number(form.value.is_expire);
//       if (form.value.is_off_shelf == true) {
//         form.value.is_off_shelf = 1;
//       } else {
//         form.value.is_off_shelf = 0;
//       }
//       if (isEdit.value) {
//         res = await editRentComputer(form.value);
//       } else {
//         // res = await addRentComputer(form.value);
//       }
//       if (res.code === 0) {
//         ElMessage({
//           type: "success",
//           message: isEdit.value ? "编辑成功" : "添加成功!",
//         });
//         getTableData();
//       } else {
//         ElMessage({
//           type: "error",
//           message: res.message,
//         });
//       }
//       initForm();
//       dialogFormVisible.value = false;
//     }
//   });
// };
</script>

<style scoped lang="scss">
.button-box {
  padding: 10px 20px;
  .el-button {
    float: right;
  }
}
.warning {
  color: #dc143c;
}
</style>
