<!--
 * @Author: 倚楼听风雨 18408246387@163.com
 * @Date: 2022-11-16 17:16:17
 * @LastEditors: 倚楼听风雨 18408246387@163.com
 * @LastEditTime: 2023-03-30 16:20:57
 * @FilePath: \log-server-web\src\view\rentComputer\rent_computer.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="是否到期">
            <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-option label="一周内到期" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用人">
            <el-select v-model="searchInfo.director_name" size="small">
              <el-option
                v-for="item in directorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否下架">
            <el-select v-model="searchInfo.is_off_shelf" size="small">
              <el-option label="否" value="0" />
              <el-option label="是" value="1" />
            </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-form-item>
        </el-form>
      </div>
      <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="addMenu('0')"
          >新增</el-button
        >
        <el-button
          class="excel-btn"
          size="small"
          type="success"
          icon="download"
          @click="downloadExcelTemplate()"
          >下载模板</el-button
        >
        <el-upload
          style="margin-left: 1%"
          class="excel-btn"
          :action="`${path}/rentComputer/importExcel`"
          :headers="{ 'x-token': userStore.token }"
          :on-success="loadExcel"
          :show-file-list="false"
        >
          <el-button size="small" type="primary" icon="upload">导入</el-button>
        </el-upload>
        <el-button
          icon="delete"
          size="small"
          type="danger"
          :disabled="!apis.length"
          style="margin-left: 10px"
          @click="deletesMenu()"
          >删除</el-button
        >
        <el-button
          icon="money"
          size="small"
          type="success"
          :disabled="!apis.length"
          style="margin-left: 10px"
          @click="switchRenews()"
          >批量续费</el-button
        >
      </div>
    </div>
    <div class="row center">
      <el-tag size="large">电脑数量 : {{ computerNum }} </el-tag>
      <el-tag
        size="large"
        type="danger"
        hit
        effect="dark"
        style="margin-left: 20px"
        v-if="tagExpire"
        >有租机即将到期，请注意续费!!!</el-tag
      >
    </div>
    <div class="gva-table-box">
      <!-- <el-scrollbar height="550px"> -->
      <el-table
        height="500px"
        :data="tableData"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        border
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          align="left"
          label="供应商"
          min-width="70"
          prop="shop_name"
        />
        <!-- <el-table-column
            align="left"
            label="套餐"
            min-width="100"
            prop="set_meal_name"
          /> -->
        <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 + "元)"
            }}</span>
            <span v-else-if="scope.row.price_type == 1">{{
              scope.row.set_meal_name + "-周卡(" + scope.row.rent_price + "元)"
            }}</span>
            <span v-else>{{
              scope.row.set_meal_name + "-月卡(" + scope.row.rent_price + "元)"
            }}</span>
          </template>
        </el-table-column>
        <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"
        />
        <el-table-column
          align="left"
          label="到期时间"
          min-width="150"
          prop="rent_end"
        />
        <el-table-column
          align="left"
          label="租期"
          min-width="50"
          prop="rent_duration"
        />
        <el-table-column
          align="left"
          label="使用人"
          min-width="80"
          prop="director_name"
        />
        <el-table-column
          align="center"
          label="是否到期"
          min-width="100"
          prop="is_expire"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.is_expire == 3"
              size="small"
              type="warning"
              plain
              >即将到期</el-button
            >
            <el-button
              v-else-if="scope.row.is_expire == 2"
              size="small"
              type="danger"
              plain
              >明日到期</el-button
            >
            <el-button
              v-else-if="scope.row.is_expire == 1"
              size="small"
              type="info"
              plain
              >到期未续</el-button
            >
            <el-button v-else size="small" type="success" plain
              >在租期中</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="是否下架"
          min-width="100"
          prop="is_off_shelf"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.is_off_shelf == 1"
              size="small"
              type="warning"
              plain
              >是</el-button
            >
            <el-button v-else size="small" type="success" plain>否</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="TD号"
          min-width="100"
          prop="todesk_id"
        />
        <el-table-column
          align="left"
          label="TD密码"
          min-width="100"
          prop="todesk_password"
        />
        <el-table-column
          align="left"
          label="向日葵号"
          min-width="100"
          prop="sunflower_id"
        />
        <el-table-column
          align="left"
          label="向日葵密码"
          min-width="100"
          prop="sunflower_password"
        />
        <el-table-column
          align="left"
          label="最近一次修改日志"
          min-width="250"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-row>
              <el-col :span="20">
                <span
                  style="
                    display: block;
                    max-width: 15em;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  >{{ scope.row.remark }}</span
                >
              </el-col>
              <el-col :span="4">
                <el-button
                  size="small"
                  type="warning"
                  link
                  icon="tickets"
                  @click="switchLog(scope.row)"
                  >more</el-button
                >
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="更新时间"
          min-width="150"
          prop="update_time"
        />
        <el-table-column align="left" fixed="right" label="操作" width="430">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              icon="link"
              @click="linkTd(scope.row)"
              >TD连接</el-button
            >
            <el-button
              size="small"
              type="primary"
              link
              icon="edit"
              @click="switchRenew(scope.row)"
              >续费</el-button
            >
            <el-button
              v-if="scope.row.is_expire != 1"
              size="small"
              type="primary"
              link
              icon="edit"
              @click="switchRentingOut(scope.row)"
              >退租</el-button
            >
            <el-button
              v-if="scope.row.is_expire != 1"
              size="small"
              type="primary"
              link
              icon="edit"
              @click="switchReplaceNum(scope.row)"
              >换编号</el-button
            >
            <el-button
              v-if="scope.row.is_off_shelf == 0"
              size="small"
              type="primary"
              link
              icon="edit"
              @click="offShelf(scope.row)"
              >下架</el-button
            >
            <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>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
      <el-form
        v-if="dialogFormVisible"
        ref="menuForm"
        :inline="true"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="85px"
      >
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="电脑编号" prop="pc_num">
              <el-input v-model="form.pc_num" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电脑名称" prop="pc_name">
              <el-input v-model="form.pc_name" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="shop_id">
              <el-select v-model="form.shop_id">
                <el-option
                  v-for="item in shopOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="套餐名" prop="set_meal_id">
              <el-select v-model="form.set_meal_id">
                <el-option
                  v-for="item in setMealOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用人" prop="director_name">
              <el-select v-model="form.director_name" size="small">
                <el-option
                  v-for="item in directorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="Todesk号" prop="todesk_id">
              <el-input v-model="form.todesk_id" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="Todesk密码" prop="todesk_password">
              <el-input v-model="form.todesk_password" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="向日葵号" prop="sunflower_id">
              <el-input v-model="form.sunflower_id" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="向日葵密码" prop="sunflower_password">
              <el-input v-model="form.sunflower_password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="起租时间" prop="rent_start">
              <el-date-picker
                v-model="form.rent_start"
                type="datetime"
                placeholder="起租时间"
                :default-time="defaultTime"
                @change="calculateRentDuration(form)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租赁天数" prop="rent_duration">
              <el-input
                v-model="form.rent_duration"
                @change="calculateRentDuration(form)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到期时间" prop="rent_end">
              <el-date-picker
                v-model="form.rent_end"
                type="datetime"
                placeholder="到期时间"
                :default-time="defaultTime"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="是否到期" prop="is_expire">
              <el-radio-group v-model="form.is_expire">
                <el-radio :label="0" size="large">在租期中</el-radio>
                <el-radio :label="1" size="large">到期未续</el-radio>
                <el-radio :label="2" size="large">明日到期</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="是否下架" prop="is_off_shelf">
              <el-switch v-model="form.is_off_shelf" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row :gutter="10">
          <el-col :span="20">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="4"
                style="width: 500px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeDialog">取 消</el-button>
          <el-button size="small" type="primary" @click="enterDialog"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!--日志-->
    <el-dialog v-model="visible_log" title="操作日志">
      <el-table :data="logData">
        <el-table-column property="create_time" label="操作时间" width="150" />
        <el-table-column property="pc_num" label="租机编号" width="80" />
        <el-table-column property="log" label="日志" />
      </el-table>
    </el-dialog>
    <!--租机续费-->
    <el-dialog title="租机续费" v-model="visible_renew">
      <el-form :model="renewForm" size="default" label-width="100px">
        <el-row>
          <el-form-item label="警告:" prop="">
            <el-col :span="24">
              <p style="color: red; font-size: larger">请勿随意操作！！！</p>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="租机编号" prop="pc_num">
            <el-col :span="12">
              <el-input
                v-model="renewForm.pc_num"
                placeholder="租机编号"
                :disabled="true"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="续费时间" prop="rent_renew">
            <el-col>
              <el-date-picker
                v-model="renewForm.rent_renew"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                :style="{ width: '100%' }"
                placeholder="请选择日期"
                clearable
                @change="calculateRenewDay(renewForm)"
              ></el-date-picker>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="续费天数" prop="">
            <el-col :span="24">
              <el-tag :key="renewForm.day" type="warning" effect="light">
                {{ renewForm.day }}
              </el-tag>
            </el-col>
          </el-form-item>
        </el-row>
        <el-divider />
        <el-form-item>
          <el-button size="small" @click="visible_renew = false"
            >取消</el-button
          >
          <el-button type="primary" size="small" @click="renew(renewForm)"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 批量续费 -->
    <el-dialog title="批量续费" v-model="visible_renews">
      <p style="color: red; font-size: larger">严重警告:请勿随意操作！！！</p>
      <span style="font-size: larger">续费天数：</span>
      <el-input
        v-model="renewsDay"
        size="small"
        style="width: 30%"
        placeholder="天数"
      ></el-input>
      <el-button
        type="primary"
        style="margin-left: 20px"
        size="small"
        @click="calculateRenewEnd()"
        >计算</el-button
      >
      <p style="font-size: larger">续费明细如下,请认真核对后再提交:</p>
      <el-table size="small" height="400px" :data="renewDatas" border>
        <el-table-column type="index" width="55" />
        <el-table-column
          align="left"
          label="编号"
          min-width="70"
          prop="pc_num"
        />
        <el-table-column
          align="left"
          label="当前到期时间"
          min-width="100"
          prop="rent_end"
        />
        <el-table-column
          align="left"
          label="续费后到期时间"
          min-width="100"
          prop="rent_end_new"
        />
      </el-table>
      <el-divider />
      <el-button size="small" @click="visible_renews = false">取消</el-button>
      <el-button type="primary" size="small" @click="renewByBatch()"
        >提交</el-button
      >
    </el-dialog>
    <!--退租-->
    <el-dialog title="租机退租" v-model="visible_rentingOut">
      <el-form
        ref="elForm"
        :model="rentingOutForm"
        size="medium"
        label-width="100px"
      >
        <el-row>
          <el-form-item label="警告:" prop="">
            <el-col :span="24">
              <p style="color: red; font-size: larger">请勿随意操作！！！</p>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="租机编号" prop="pc_num">
            <el-col :span="12">
              <el-input
                v-model="rentingOutForm.pc_num"
                placeholder="租机编号"
                :disabled="true"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="退租时间" prop="rent_end">
            <el-col>
              <el-date-picker
                v-model="rentingOutForm.rent_end"
                format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                :style="{ width: '100%' }"
                placeholder="请选择日期"
                clearable
                @change="calculateRentDay(rentingOutForm)"
              ></el-date-picker>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="剩余天数" prop="">
            <el-col :span="24">
              <el-tag :key="rentingOutForm.day" type="warning" effect="light">
                {{ rentingOutForm.day }}
              </el-tag>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row
          ><el-col :span="12" style="margin-left: 30px"
            ><el-button size="small" @click="addCardMsg()"
              >匀时间</el-button
            ></el-col
          ></el-row
        >
        <el-row>
          <div class="container-scrollbar">
            <el-scrollbar max-height="200px">
              <el-row
                :gutter="24"
                v-for="(item, index) in cardList"
                :key="index"
              >
                <el-col :span="10">
                  <el-form-item label="租机编号">
                    <el-input v-model="item.pc_num"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="增加天数">
                    <el-input v-model="item.add_day"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2" v-if="cardList.length !== 1">
                  <el-button
                    size="mini"
                    circle
                    icon="delete"
                    @click="deleteCardMsg(index)"
                  ></el-button>
                </el-col>
              </el-row>
            </el-scrollbar>
          </div>
        </el-row>
        <el-divider />
        <el-form-item>
          <el-button size="small" @click="visible_rentingOut = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="rentingOut(rentingOutForm)"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--租机编号更换-->
    <el-dialog title="租机编号更换" v-model="visible_replaceNum">
      <el-form
        ref="elForm"
        :model="replaceNumForm"
        size="medium"
        label-width="100px"
      >
        <el-row>
          <el-form-item label="警告:" prop="">
            <el-col :span="24">
              <p style="color: red; font-size: larger">
                请勿随意更换，会影响租机续费
              </p>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="供应商:" prop="shop_name">
            <el-col :span="24">
              <p>
                <span style="color: red; font-size: larger">{{
                  replaceNumForm.shop_name
                }}</span
                >, 只可更改为同一供应商的编号
              </p>
            </el-col>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="原租机编号" prop="pc_num_old">
            <el-col :span="24">
              <el-input
                v-model="replaceNumForm.pc_num_old"
                placeholder="原租机编号"
                :disabled="true"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="更换编号" prop="pc_num_new">
            <el-col :span="24">
              <el-input
                v-model="replaceNumForm.pc_num_new"
                placeholder="更换编号"
              ></el-input>
            </el-col>
          </el-form-item>
        </el-row>
        <el-divider />
        <el-form-item>
          <el-button size="small" @click="visible_replaceNum = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="replaceNum(replaceNumForm)"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

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

<script setup>
import {
  getRentComputerList,
  getRentComputerNum,
  listRentComputerShopList,
  listRentSetMealList,
  getRentComputerById,
  addRentComputer,
  editRentComputer,
  deleteRentComputerById,
  deleteRentComputerByIds,
  renewRentComputer,
  renewRentComputerByBatch,
  replaceNumRentComputer,
  rentingOutRentComputer,
  offShelfRentComputer,
  queryRentComputerLogByPcNum,
} from "@/api/rentComputer";
import { getDirectorList } from "@/api/responsiblePerson";
import { useUserStore } from "@/pinia/modules/user";
import { toSQLLine } from "@/utils/stringFun";
import { ref } from "vue";
import { ElMessage, ElMessageBox, ElLoading } 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,
  director_name: "ALL",
});
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([]);
const renewDatas = ref([]);
const logData = ref([]);
const loading = ref(false);
const searchInfo = ref({
  is_expire: -1,
  is_off_shelf: -1,
  director_name: "ALL",
});
const computerNum = ref("");
const tagExpire = ref(false);
const shopOptions = ref();
const directorOptions = 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 visible_renew = ref(false);
const visible_renews = ref(false);
const visible_rentingOut = ref(false);
const visible_replaceNum = ref(false);
const visible_log = ref(false);
const rent_end = ref("");
const renewForm = ref({
  pc_num: "",
  pc_id: 0,
  day: 0,
  rent_renew: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
});
const renewsDay = ref(0);
const rentingOutForm = ref({
  pc_num: "",
  pc_id: 0,
  day: 0,
  rent_end: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
  addList: [],
});
const replaceNumForm = ref({
  pc_num_old: "",
  pc_num_new: "",
  shop_id: 0,
  shop_name: "",
});
let cardList = ref([]);

// 计算租机到期时间
const calculateRentDuration = async (scope) => {
  scope.rent_end = new Date(
    Date.parse(scope.rent_start) +
      1 * 24 * 60 * 60 * 1000 * parseInt(scope.rent_duration)
  );
};
// 计算退租剩余时间
function calculateRentDay(scope) {
  if (Date.parse(rent_end.value) < Date.parse(scope.rent_end)) {
    scope.rent_end = rent_end.value;
    ElMessage.error("退租时间不能大于到期时间");
  }
  scope.day = Math.ceil(
    parseInt(
      (Date.parse(rent_end.value) - Date.parse(scope.rent_end)) /
        (24 * 60 * 60 * 1000) +
        ""
    )
  );
  // console.log(scope.day);
}
// 计算续费时间
function calculateRenewDay(scope) {
  if (Date.parse(rent_end.value) >= Date.parse(scope.rent_renew)) {
    scope.rent_renew = rent_end.value;
    ElMessage.error("续费时间不能小于到期时间");
    visible_renew.value = false;
  }
  scope.day = Math.ceil(
    parseInt(
      (Date.parse(scope.rent_renew) - Date.parse(rent_end.value)) /
        (24 * 60 * 60 * 1000) +
        ""
    )
  );
}
// 查询日志
async function switchLog(rowData) {
  const loadingLog = ElLoading.service({
    lock: true,
    text: "查询日志中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let logForm = {
    pc_num: rowData.pc_num,
    shop_id: Number(rowData.shop_id),
    // set_meal_id: Number(rowData.set_meal_id),
  };
  // console.log(logForm);
  const data = await queryRentComputerLogByPcNum(logForm);
  if (data.code == 0) {
    visible_log.value = true;
    loadingLog.close();
    // ElMessage.success(data.msg);
    logData.value = data.data.list;
  } else {
    ElMessage.error(data.msg);
  }
}
// 拉起续费弹窗
async function switchRenew(rowData) {
  // console.log(rowData);
  renewForm.value.pc_num = rowData.pc_num;
  renewForm.value.pc_id = rowData.id;
  renewForm.value.rent_renew = rowData.rent_end;
  renewForm.value.day = 0;
  rent_end.value = rowData.rent_end;
  // console.log(renewForm);
  if (visible_renew.value == false) {
    visible_renew.value = true;
  }
}
// 续费
async function renew(rowData) {
  let doForm = {
    pc_num: rowData.pc_num,
    pc_id: rowData.pc_id,
    rent_renew: dayjs(new Date(rowData.rent_renew)).format(
      "YYYY-MM-DD HH:mm:ss"
    ),
    day: rowData.day,
  };
  // renewRentComputer
  const data = await renewRentComputer(doForm);
  if (data.code == 0) {
    visible_renew.value = false;
    ElMessage.success(data.msg);
    getTableData();
  } else {
    ElMessage.error(data.msg);
  }
}
// 拉起批量续费弹窗
async function switchRenews(rowData) {
  renewDatas.value = [];
  if (visible_renews.value == false) {
    visible_renews.value = true;
  }
  calculateRenewEnd();
}
// 计算批量续费到期时间
function calculateRenewEnd() {
  renewDatas.value = [];
  //
  apis.value.map((item) => {
    // console.log(item);
    let temp = {
      pc_id: item.id,
      pc_num: item.pc_num,
      rent_end: item.rent_end,
      rent_end_new: dayjs(new Date(item.rent_end))
        .add(renewsDay.value, "day")
        .format("YYYY-MM-DD HH:mm:ss"),
    };
    renewDatas.value.push(temp);
  });
}
// 批量续费
const renewByBatch = async () => {
  const loadingByBatch = ElLoading.service({
    lock: true,
    text: "批量续费中,请勿操作界面...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let rentMessage = [];
  renewDatas.value.map((item) => {
    let temp = {
      pc_num: item.pc_num,
      pc_id: item.pc_id,
      rent_renew: item.rent_end_new,
      day: Number(renewsDay.value),
    };
    rentMessage.push(temp);
  });
  let xxxx = {
    rent_message: rentMessage,
  };

  const data = await renewRentComputerByBatch(xxxx);
  if (data.code == 0) {
    visible_renews.value = false;
    loadingByBatch.close();
    ElMessage.success(data.msg);
    getTableData();
  } else {
    ElMessage.error(data.msg);
  }
};

// 拉起退租弹窗
async function switchRentingOut(rowData) {
  cardList.value = [];
  rentingOutForm.value.pc_num = rowData.pc_num;
  rentingOutForm.value.pc_id = rowData.id;
  rentingOutForm.value.rent_end = dayjs(new Date(rowData.rent_end)).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  rentingOutForm.value.day = 0;
  rent_end.value = rowData.rent_end;
  if (visible_rentingOut.value == false) {
    visible_rentingOut.value = true;
  }
}
function addCardMsg() {
  let hasFlag = false;
  for (let i = 0; i < cardList.value.length; i++) {
    if (
      cardList.value[i].pc_num == "" ||
      cardList.value[i].add_day == undefined
    ) {
      hasFlag = true;
      break;
    }
  }
  if (hasFlag == true) {
    ElMessage.error("有未填写项");
  } else {
    cardList.value.push({
      pc_id: "",
      add_day: null,
    });
  }
}
function deleteCardMsg(index) {
  cardList.value.splice(index, 1);
}
// 退租
async function rentingOut(rowData) {
  var numDay = 0;
  let AddList = [];
  cardList.value.forEach((e) => {
    numDay += e.add_day;
    let temp = {
      pc_num: e.pc_num,
      add_day: Number(e.add_day),
    };
    AddList.push(temp);
  });
  if (numDay != rowData.day) {
    ElMessage.error("匀时间天数错误！！！");
    return;
  }
  let doForm = {
    pc_id: rowData.pc_id,
    rent_end: dayjs(new Date(rowData.rent_end)).format("YYYY-MM-DD HH:mm:ss"),
    add_list: AddList,
  };

  const data = await rentingOutRentComputer(doForm);
  // console.log(data)
  if (data.code == 0) {
    visible_rentingOut.value = false;
    ElMessage.success(data.msg);
    getTableData();
  } else {
    // ElMessage.error(data.msg);
  }
}
// 拉起换编号弹窗
async function switchReplaceNum(rowData) {
  replaceNumForm.value.pc_num_old = rowData.pc_num;
  replaceNumForm.value.shop_id = rowData.shop_id;
  replaceNumForm.value.shop_name = rowData.shop_name;
  if (visible_replaceNum.value == false) {
    visible_replaceNum.value = true;
  }
}
// 换编
async function replaceNum(rowData) {
  let doForm = {
    pc_num_old: rowData.pc_num_old,
    pc_num_new: rowData.pc_num_new,
    shop_id: rowData.shop_id,
  };
  const data = await replaceNumRentComputer(doForm);
  // console.log(data)
  if (data.code == 0) {
    visible_replaceNum.value = false;
    ElMessage.success(data.msg);
    getTableData();
  } else {
    // ElMessage.error(data.msg);
  }
}
const downloadExcelTemplate = () => {
  downloadTemplate("RentComputerTemplate.xlsx");
};

// 删除/下架
async function offShelf(rowData) {
  let message = "确定要下架编号为" + rowData.pc_num + "的租机吗?";
  if (rowData.is_expire != 1) {
    message = "机器未到期,确定强制下架编号为" + rowData.pc_num + "的租机吗?";
  }
  let doForm = {
    id: rowData.id,
    pc_num: rowData.pc_num,
  };
  // console.log(doForm);
  ElMessageBox.confirm(message, "租机下架", {
    dangerouslyUseHTMLString: true,
    type: "warning",
  })
    .then(async () => {
      const data = await offShelfRentComputer(doForm);
      if (data.code == 0) {
        ElMessage.success(data.msg);
        getTableData();
      } else {
        ElMessage.error(data.msg);
      }
    })
    .catch(() => null);
}

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

// 排序
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 () => {
  loading.value = true;
  const table = await getRentComputerList({
    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;
    getComputerNum();
    getSelectList();
  }
  await getIsExpireData();
  loading.value = false;
};
// 查询是否有到期
const getIsExpireData = async () => {
  loading.value = true;
  tagExpire.value = false;
  const table = await getRentComputerList({
    page: 1,
    pageSize: 999,
    ...searchInfo.value,
  });
  // console.log(table.data.list)
  if (table.code === 0 && table.data.list != null) {
    for (const item of table.data.list) {
      if (item.is_expire >= 2) {
        ElMessageBox.alert("有租机即将到期，请注意续费!!!", "警告", {
          confirmButtonText: "好的",
          type: "warning",
          callback: (action) => {
            tagExpire.value = true;
          },
        });
        break;
      }
    }
  }
};

//获取下拉框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 directorRes = await getDirectorList();
  let directorList = [
    { value: "ALL", label: "所有机器" },
    // { value: "", label: "备用" },
  ];
  const data3 = directorRes.data.list;
  data3.forEach((e) => {
    directorList.push({ value: e.name, label: e.name });
  });
  directorOptions.value = directorList;
};

// 查询
const getComputerNum = async () => {
  const table = await getRentComputerNum({ ...searchInfo.value });
  if (table.code === 0) {
    // console.log(table.data);
    computerNum.value = table.data;
  }
};
//拉起TD连接
const linkTd = async (row) => {
  let todesk_id = row.todesk_id;
  let todesk_password = row.todesk_password;
  todesk_id = todesk_id.replace(/\s*/g, "");
  todesk_password = todesk_password.replace(/\s*/g, "");
  // console.log(todesk_id);
  // console.log(todesk_password);
  if (todesk_id == "" || todesk_password == "") {
    ElMessage({
      type: "error",
      message: "todesk账号密码不完整!",
    });
  } else {
    window.location.href =
      "ToDesk://connect&" + todesk_id + "&" + todesk_password;
  }
};
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;
  // console.log(form.value);
  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>
