<template>
  <div class="agreement">
    <div class="container">
      <el-row :gutter="20" class="mb-5">
        <el-col :span="24">
          <el-card shadow="never">
            <div class="d-flex flex-wrap align-center justify-space-around font-style">
              <div class="flexLi my-2 d-flex flex-nowrap align-center d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-tongjifenxi font-size-40 color-03A9F4"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-03A9F4">总收入</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="0" class="color-03A9F4"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">元</span>
                  </div>
                </div>
              </div>
              <div class="flexLi my-2 d-flex flex-nowrap align-center  d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-yewuguanli font-size-40 color-03A9F4"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-03A9F4">合同数</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="contractStatus.total" class="color-03A9F4"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">个</span>
                  </div>
                </div>
              </div>
              <div class="flexLi my-2 d-flex flex-nowrap  align-center d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-pingzhengguanli font-size-40 color-03A9F4"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-03A9F4">已签约</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="contractStatus.signed" class="color-03A9F4"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">人</span>
                  </div>
                </div>
              </div>
              <div class="flexLi my-2 d-flex flex-nowrap align-center  d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-wuyedangan font-size-40 color-ff9900"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-ff9900">已到期</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="contractStatus.expired" class="color-ff9900"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">间</span>
                  </div>
                </div>
              </div>
              <div class="flexLi my-2 d-flex flex-nowrap align-center  d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-pingzhengguanli font-size-40 color-F56C6C"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-F56C6C">已欠费</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="contractStatus.arrears" class="color-F56C6C"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">间</span>
                  </div>
                </div>
              </div>
              <div class="flexLi my-2 d-flex flex-nowrap align-center  d-inlie-block text-center hand-type">
                <div class="mr-2">
                  <i class="iconfont httpicon-bianji font-size-40 color-03A9F4"></i>
                </div>
                <div>
                  <div class="color-00000073 font-size-16 font-weight-700 color-03A9F4">待签约</div>
                  <div class="font-size-24 mt-2">
                    <NumberGrow :value="contractStatus.toBeSigned" class="color-03A9F4"></NumberGrow><span
                      class="font-size-16 color-00000073 ml-1">人</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-input v-model="search.name" size="small" placeholder="租客名称" :clearable="true"
        class="handle-input width150 mb-1">
      </el-input>
      <el-input v-model="search.phone" size="small" placeholder="租客电话" :clearable="true"
        class="handle-input width150 mb-1">
      </el-input>
      <el-input v-model="search.roomName" size="small" placeholder="房间名称" :clearable="true"
        class="handle-input width150 mb-1">
      </el-input>
      <el-cascader size="small" :options="roomList" collapse-tags @change="checkNodeSearch" :props="{ multiple: true }"
        :clearable="true" class="width150" placeholder="请选择房间"></el-cascader>
      <el-select v-model="search.status" size="small" placeholder="签约状态" class="handle-select width150 mb-1"
        :clearable="true">
        <el-option key="1" label="待签约" value="0"></el-option>
        <el-option key="2" label="已签约" value="1"></el-option>
        <el-option key="3" label="已欠费" value="2"></el-option>
        <el-option key="4" label="已退租" value="3"></el-option>
        <el-option key="5" label="已到期" value="5"></el-option>
      </el-select>
      <div class="d-inlie-block">
        <el-input v-model="search.minRent" size="small" type="number" placeholder="最低租金" :clearable="true"
          class="handle-input mb-1 width150">
        </el-input> -
        <el-input v-model="search.maxRent" size="small" type="number" placeholder="最高租金" :clearable="true"
          class="handle-input mb-1 width150">
        </el-input>
      </div>
      <div class="d-inlie-block">
        <el-date-picker v-model="search.signingTime" size="small" type="datetime" class="width150 mb-1"
          placeholder="选择开始日期" align="right" :picker-options="pickerOptions">
        </el-date-picker> -
        <el-date-picker v-model="search.contractTime" size="small" type="datetime" class="width150 mb-1"
          placeholder="选择结束日期" align="right" :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button type="danger" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        @click="syncContractStatusMethods">同步合约状态</el-button>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        @click="restSearch">重置</el-button>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        @click="signContract">签约</el-button>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        @click="batchLeaseCancellationMethods">批量退租</el-button>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small" class=" mb-1 mx-1"
        @click="batchDeleteMethods">批量删除</el-button>
      <el-button type="primary" style="background: #FA8E00; border: none;" size="small"
        class=" mb-1 mx-1">导出合同</el-button>
      <el-table :data="tableList" border stripe class="table mt-2" ref="multipleTable"
        @selection-change="handleSelectionChange" header-cell-class-name="table-header" height="650px" empty-text="无">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="number" label="合同编号" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="phone" label="电话" align="center"></el-table-column>
        <el-table-column prop="sex" label="性别" align="center">
          <template #default="scope">
            {{ scope.row.sex === 1 ? '男' : scope.row.sex === 2 ? '女' : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="房间" align="center"></el-table-column>
        <el-table-column label="租期" align="center">

          <template #default="scope">
            {{ scope.row.signingTime }}<br /> 至 <br />{{ scope.row.contractTime }}
          </template>
        </el-table-column>
        <el-table-column prop="monthRent" label="租金/¥" align="center"></el-table-column>
        <el-table-column label="合约状态" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 0 ? '' : scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : scope.row.status === 3 ? 'warning' : scope.row.status === 4 ? 'info' : ''">
              {{
                scope.row.status === 0 ? '待签约' : scope.row.status === 1 ? '已签约' : scope.row.status === 2 ? '已欠费' :
                  scope.row.status === 3 ? '已退租' : scope.row.status === 4 ? '已删除' : scope.row.status === 5 ? '已到期' : '未知'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期" align="center"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" size="mini" style="width: 100px;" maxlength="20" class="width-100-px"
              @blur="confirmRemark(scope.$index, scope.row)" v-if="modifyIndex === scope.$index">
            </el-input>
            <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top" v-else>
              <span>{{ scope.row.remark }}</span>
            </el-tooltip>
            <i class="el-icon-edit red hand-type" @click.stop="setRemark(scope.$index, scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="text" @click="changebatchRenewalShow(scope.$index, scope.row)">续租</el-button>
            <el-button type="text" class="red" @click="rentOutOperation(scope.$index, scope.row)"
              :disabled="scope.row.status > 2 ? true : false">退租</el-button>
            <el-button type="text" @click="deleteAgreement(scope.$index, scope.row)">删除</el-button>
            <el-button type="text" class="red">冻结用户权限</el-button>
            <el-button type="text" @click="exportHtmlWord(scope.$index, scope.row)">预览合同</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-sizes="[10, 30, 100, 200]" :page-size="pageSize" :layout="paginationConfig" :total="pageTotal">
      </el-pagination>
    </div>
    <el-dialog title="预览合同" :visible.sync="dialogVisibleExport" width="60%" :before-close="handleCloseExport">
      <div style="overflow-y: auto;height: 500px;">
        <contractTemplate id="question_doc" :data="exportRow"></contractTemplate>
      </div>
      <el-button type="primary" size="mini" class="mt-2" @click="exportWord">导出</el-button>
    </el-dialog>
    <el-dialog title="签约" :visible.sync="dialogVisible" width="80%" :before-close="handleClose">
      <div>
        <el-collapse accordion v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <span class="font-weight-600 font-size-18">填写签约人信息</span><i
                class="header-icon el-icon-user-solid font-size-20 ml-2"></i>
            </template>
            <div v-for="(item, index) in form.tenant" :key="index">
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width50 text-center"><b class="color-red">*</b>姓名</span>
                  <!--                  <el-input :clearable="true"-->
                  <!--                            placeholder="请输入姓名"-->
                  <!--                            v-model="form.tenant[index].name" class="width200">-->
                  <!--                  </el-input>-->
                  <el-autocomplete v-model="form.tenant[index].name" class="widthThree" :maxlength="8"
                    :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelectPerson(index, $event)"
                    clearable>
                    <template slot-scope="{ item }">
                      <div class="name">{{ item.name }}->{{ item.phone }}</div>
                    </template>
                  </el-autocomplete>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width50 text-center"><b class="color-red">*</b>手机号</span>
                  <el-input :clearable="true" placeholder="请输入电话号码" v-model="form.tenant[index].phone" class="width200">
                    <el-button slot="append" icon="el-icon-right" @click.stop="searchPeople(index)"></el-button>
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width100 text-center mr-1"><b class="color-red">*</b>证件类型</span>
                  <el-select v-model="form.tenant[index].cardType" placeholder="请选择证件类型" class="width200"
                    :clearable="true">
                    <el-option v-for="item in IdCardOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width50 text-center"><b class="color-red">*</b>证件号</span>
                  <el-input :clearable="true" placeholder="请输入证件号" v-model="form.tenant[index].number" class="width200">
                    <el-button slot="append" icon="el-icon-right" @click.stop="searchPeople(index)"></el-button>
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width50 text-center">性别</span>
                  <el-select v-model="form.tenant[index].sex" placeholder="请选择性别" class="width200" :clearable="true">
                    <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width50 text-center">籍贯</span>
                  <el-input :clearable="true" placeholder="请输入籍贯" v-model="form.tenant[index].place" class="width200">
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width100 text-center mr-1">通讯地址</span>
                  <el-input :clearable="true" placeholder="请输入通讯地址" v-model="form.tenant[index].address" class="width200">
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width100 text-center mr-1">租户类别</span>
                  <el-select v-model="form.tenant[index].tenantType" placeholder="请选择租户类别" class="width200"
                    :clearable="true">
                    <el-option v-for="item in tenantOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width100 text-center mr-1">补贴标准</span>
                  <el-select v-model="form.tenant[index].subsidy" placeholder="请选择补贴标准" class="width200"
                    :clearable="true">
                    <el-option v-for="item in subsidyOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <el-divider content-position="left" v-if="(index + 1) !== form.tenant.length"><i
                  class="el-icon-arrow-down"></i> 添加同住人{{ index + 1 }}信息 <i class="el-icon-arrow-down"></i></el-divider>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2" v-if="(index + 1) === form.tenant.length">
                <el-button type="primary" @click="addCohabitant">添加同住人</el-button>
                <el-button type="primary" @click="deleteCohabitant(index)" v-if="index !== 0">删除同住人</el-button>
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <span class="font-weight-600 font-size-18">查找房源信息</span><i
                class="header-icon el-icon-search font-size-20 ml-2"></i>
            </template>
            <div>
              <el-cascader :options="roomList" size="small" :props="{ checkStrictly: true }" v-model="form.roomName"
                @change="checkNode" :clearable="true" placeholder="请选择房源" class="mb-2"></el-cascader>
              <el-input v-model="form.roomNameSearch" size="small" placeholder="房间名称" :clearable="true"
                class="handle-input mb-2 width200"></el-input>
              <el-button type="primary" size="small" class="mr10" icon="el-icon-search" @click="searchRoom">搜索</el-button>
              <el-table :data="tableDataRom" style="width: 100%" max-height="400px">
                <el-table-column align="center" prop="path" label="房屋地址信息"></el-table-column>
                <el-table-column label="月租金" align="center">
                </el-table-column>
                <el-table-column label="房屋结构信息" align="center">
                  <el-table-column prop="name" align="center" label="房间名称" width="120">
                  </el-table-column>
                  <el-table-column prop="type" align="center" label="房间状态" width="120">
                  </el-table-column>
                  <el-table-column prop="layoutText" align="center" label="房间户型" width="120">
                  </el-table-column>
                  <el-table-column prop="acreage" align="center" label="面积" width="120">
                  </el-table-column>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="medium" class="el-icon-upload2"
                      @click="selectRoom(scope.$index, scope.row)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <span class="font-weight-600 font-size-18">填写合约信息</span><i
                class="header-icon el-icon-edit-outline font-size-20 ml-2"></i>
            </template>
            <div>
              <div class="split-Line" v-if="form.roomName">
                <el-divider><i class="el-icon-arrow-down"></i> 所选房间 <i class="el-icon-arrow-down"></i></el-divider>
                <div class="d-flex mb-2">
                  <div class="mr-4 "><span class="color-666">地址：</span><span class="font-weight-600">{{ form.roomName
                  }}</span></div>
                  <div class="mr-4"><span class="color-666">套内房间数量：</span><span class="font-weight-600">{{ form.roomNum
                  }}</span></div>
                  <div class="mr-4"><span class="color-666">月租金：</span><span class="font-weight-600">{{ form.roomNum
                  }}</span></div>
                  <div class="mr-4"><span class="color-666">面积：</span><span class="font-weight-600">{{ form.acreage
                  }}</span></div>
                  <div class="mr-4"><span class="color-666">户型：</span><span class="font-weight-600">{{
                    form.layout === 0 ? '单间' : form.layout === 1 ? '一室一厅' : form.layout === 2 ? '两室一厅' : '三室一厅'
                  }}</span></div>
                </div>
              </div>
              <div class="split-Line" v-if="form.tenant.length">
                <el-divider><i class="el-icon-arrow-down"></i> 签约人 <i class="el-icon-arrow-down"></i></el-divider>
                <div class="d-flex mb-2" v-for="(item, index) in form.tenant" :key="index"
                  v-if="item.phone && item.number">
                  <div class="mr-4"><span class="color-666">{{ index + 1 }}、姓名：</span><span class="font-weight-600">{{
                    item.name }}</span></div>
                  <div class="mr-4"><span class="color-666">证件类型：</span><span class="font-weight-600">{{ item.cardType ==
                    1 ? '身份证' : item.cardType == 2 ? '护照' : '其他' }}</span></div>
                  <div class="mr-4"><span class="color-666">证件号：</span><span class="font-weight-600">{{ item.number
                  }}</span></div>
                  <div class="mr-4"><span class="color-666">电话号码：</span><span class="font-weight-600">{{ item.phone
                  }}</span></div>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>租金</span>
                  <el-input :clearable="true" onkeyup="value=value.replace(/\D/g,'')" placeholder="请输入每月租金"
                    v-model="form.rent" class="width200">
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>支付方式</span>
                  <el-select v-model="form.pay" placeholder="请选择支付方式" class="width200" :clearable="true">
                    <el-option v-for="item in payOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>房屋合同编号</span>
                  <el-input :clearable="true" placeholder="请输入房屋合同编号" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"
                    v-model="form.id" class="width200">
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>合同签约时间</span>
                  <el-date-picker v-model="form.signingTime" :clearable="true" type="datetime" placeholder="请选择签约时间">
                  </el-date-picker>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>合同有效时间</span>
                  <el-date-picker v-model="form.contractTime" :clearable="true" type="datetime" placeholder="请选择有效时间">
                  </el-date-picker>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>缴费日期</span>
                  <el-date-picker v-model="form.dueDate" :clearable="true" type="date" placeholder="选择缴费日期">
                  </el-date-picker>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1">合同备注</span>
                  <el-input :clearable="true" type="textarea" :rows="1" placeholder="请输入备注" v-model="form.remark"
                    class="width200">
                  </el-input>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1">是否发送动态临时密码</span>
                  <el-radio-group v-model="sendTemporaryPasswordStatus" size="mini">
                    <el-radio-button label="是"></el-radio-button>
                    <el-radio-button label="否"></el-radio-button>
                  </el-radio-group>
                </div>
              </div>
              <div class="demo-input-suffix d-inlie-block mr-2 mb-2">
                <div class="d-flex align-center">
                  <span class="width120 text-center mr-1"><b class="color-red">*</b>录入开锁授权</span>
                  <el-select v-model="documentType" placeholder="请选择凭证类型" class="width200" :clearable="true">
                    <el-option v-for="item in payOptionsOne" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <el-form>
                <el-form-item label="指纹" v-if="documentType == 11">
                  <el-radio-group v-model="voucher.fingerprintAlias" size="small">
                    <!-- @change="fingerprintAliasMethod" -->
                    <el-radio-button label="左手大拇指"></el-radio-button>
                    <el-radio-button label="左手食指"></el-radio-button>
                    <el-radio-button label="右手大拇指"></el-radio-button>
                    <el-radio-button label="右手食指"></el-radio-button>
                  </el-radio-group>
                  <el-button type="primary" @click="addfir" size="small">GX1000-zh采集指纹</el-button>
                  <el-button type="primary" @click="getFingerData" size="small">LWJ采集指纹</el-button>
                  <iframe src="static/equipment/mafp_serial/index.html" frameborder="0" style="width: 100%; height: 350px"
                    id="iframeBox"></iframe>
                </el-form-item>
                <el-form-item label="身份证" v-if="documentType == 12" prop="idcard">
                  <el-input placeholder="请输入内容" v-model.trim="voucher.idcard" class="widthRem5" size="middle"
                    :clearable="true" @change="avoidRepetition($event, 12)">
                    <el-button slot="append" @click.native="addNfc">GX1000-zh采集卡</el-button>
                  </el-input>
                </el-form-item>
                <el-form-item label="NFC卡号" v-if="documentType == 13" prop="nfc">
                  <el-input placeholder="请输入内容" v-model.trim="voucher.nfc" class="widthRem5" size="middle"
                    :clearable="true" @change="avoidRepetition($event, 13)">
                    <el-button slot="append" @click.native="addNfc">GX1000-zh采集卡</el-button>
                  </el-input>
                  <el-switch v-model="regularCard" active-text="是否是常开卡" active-color="#13ce66" inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
                <el-form-item label="密码" v-if="documentType == 14" prop="password">
                  <el-input v-model.trim="voucher.password" type="number" size="middle" class="widthRem5" maxlength="6"
                    :clearable="true" @change="avoidRepetition($event, 14)" show-password>
                  </el-input>
                </el-form-item>
                <el-form-item label="时效密码" v-if="documentType == 15" prop="password">
                  <el-input v-model.trim="voucher.limitpassword" type="number" size="middle" class="widthRem5"
                    maxlength="6" :clearable="true" @change="avoidRepetition($event, 15)" show-password>
                  </el-input>
                </el-form-item>
                <!-- 凭证有效期 -->
                <el-form-item label="开始时间" v-if="documentType != '' ? true : false">
                  <el-date-picker v-model="value2[0]" size="small" :picker-options="pickerOptionsBegin" type="datetime"
                    placeholder="选择开始日期时间" default-time="00:00:00">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" v-if="documentType != '' ? true : false">
                  <el-date-picker v-model="value2[1]" size="small" :picker-options="pickerOptionsEnd" type="datetime"
                    placeholder="选择结束日期时间" default-time="00:00:00">
                  </el-date-picker>
                </el-form-item>
              </el-form>
              <el-button type="primary" size="small" @click="savevoucher"
                v-if="documentType != '' ? true : false">保存</el-button>
              <el-table :data="savevoucherlist" class="table" style="width: 100%;margin-top: 10px;"
                header-cell-class-name="table-header">
                <el-table-column prop="name" label="租客名称"></el-table-column>
                <el-table-column label="凭证名称">
                  <template #default="scope">
                    <span v-if="scope.row.type == 11">指纹{{ scope.$index + 1 }}</span>
                    <span v-if="scope.row.type == 12">身份证{{ scope.$index + 1 }}</span>
                    <span v-if="scope.row.type == 13">NFC{{ scope.$index + 1 }}</span>
                    <span v-if="scope.row.type == 14">密码{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="凭证类型">
                  <template #default="scope">
                    <span v-if="scope.row.type == 11">指纹</span>
                    <span v-if="scope.row.type == 12">身份证</span>
                    <span v-if="scope.row.type == 13">NFC</span>
                    <span v-if="scope.row.type == 14">密码</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="400" align="center" class-name="tablebutton">
                  <template #default="scope">
                    <el-button type="text" class="red" @click="deletefun(scope.$index, scope.row)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="signAContract">签 约</el-button>
      </span>
    </el-dialog>
    <el-dialog title="续租" :visible.sync="batchRenewalShow" width="30%">
      <el-form ref="batchRenewalFrom" :model="batchRenewalFrom" label-width="80px" class="temporary">
        <el-form-item label="开始时间">
          <el-date-picker v-model="batchRenewalFrom.startTime" :picker-options="pickerOptionsBegin" size="small"
            type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="batchRenewalFrom.endTime" :picker-options="pickerOptionsBegin" size="small"
            type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="batchRenewalShow = false" type="primary">取消</el-button>
          <el-button size="small" @click="batchRenewalMethods" type="primary">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <zw ref="myChild"></zw>
    <getFinger ref="myGetFinger"></getFinger>
  </div>
</template>

<script>
import zw from "./zw.vue"
import getFinger from "./getFinger.vue"
import { httpGet, httpPost } from "../api";
import { smallToBig, uniqueArray1, ztreeToElementTree, dec2hex, group, ztreeToElementTree2 } from "../utils";
import utils from "../utils/util";
import IdentityCodeValid from "../utils/verification";
import RequestSet from "../api/allFun";
import ICINLocker from "../utils/equipment";
import moment from "moment";
import NumberGrow from "../components/visualizcomponent/NumberGrow.vue";
import contractTemplate from "../components/contractTemplate/contractTemplate.vue";

import { saveAs } from 'file-saver';
import htmlDocx from 'html-docx-js/dist/html-docx';
export default {
  name: "agreement",
  data() {
    return {
      // 续租信息
      batchmessage: {},
      batchRenewalFrom: {
        startTime: new Date(),
        endTime: ''
      },
      batchRenewalShow: false,
      savevoucherlist: [],
      checkInListing: [],
      enterpriselist: [],
      voucherlist: [],
      total1: 0,
      allAboutDevice: [],
      regularCard: false,
      maxDateTime: '',
      minDateTime: '',
      value2: ['', ''],
      pickerOptionsBegin: {
        disabledDate: time => {
          // time为形参，实参就是自动获取到的beginTime元素可以选的值
          let maxDateTimeOne = new Date(this.maxDateTime).getTime()
          let minDateTimeOne = new Date(this.minDateTime).getTime()
          return time.getTime() > maxDateTimeOne || time.getTime() < minDateTimeOne
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let maxDateTimeOne = new Date(this.value2[0]).getTime()
          return time.getTime() < maxDateTimeOne; /*今天及之前*/
        }
      },
      roomtable1: [],
      drawerRow: {},
      localFingerprint: {},
      documentType: '',  // 签约的录入凭证类型
      voucher: {
        nfc: "",  // NFC
        idcard: "",  // 身份证
        password: "123456",  // 密码
        fingerprintAlias: "", // 指纹
        limitpassword: '', // 时效密码
      }, // 凭证录入
      roomlistZNodes: [],
      contractStatus: {
        total: 0,
        signed: 0,
        expired: 0,
        arrears: 0,
        toBeSigned: 0
      },
      WhetherToGreatAnAccount: true,
      dialogVisibleExport: false,
      exportRow: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      sendTemporaryPasswordStatus: '否',
      multipleSelection: [],
      modifyIndex: '',
      updateDialogStatus: false,
      updateAgreementRow: {},
      activeNames: '1',
      payOptions: [
        { label: '现金', value: 1 },
        { label: '刷卡', value: 2 },
        { label: '支付宝', value: 3 },
        { label: '微信', value: 4 },
      ],
      payOptionsOne: [
        { label: '指纹', value: 11 },
        { label: '身份证', value: 12 },
        { label: 'NFC', value: 13 },
        { label: '密码', value: 14 },
        { label: '时效密码', value: 15 },
      ],
      roomList: [],
      tableDataRom: [],
      subsidyOptions: [
        { label: '一次性补贴', value: 1 },
        { label: '按月补贴', value: 2 },
        { label: '一次性补贴+按月基本补贴', value: 3 }
      ],
      tenantOptions: [
        { label: '中国大陆', value: 1 },
        { label: '港澳台同胞', value: 2 },
        { label: '国际友人', value: 3 },
      ],
      IdCardOptions: [
        { label: '身份证', value: 1 },
        { label: '护照', value: 2 }
      ],
      sexOptions: [
        { label: '男', value: 1 },
        { label: '女', value: 2 }
      ],
      tableList: [],
      search: {
        name: '',
        phone: '',
        status: '',
        signingTime: '',
        contractTime: '',
        roomName: '',
        minRent: '',
        maxRent: '',
        siteIds: ''
      },
      form: {
        tenant: [
          {
            id: '',
            name: '',
            phone: '',
            number: '',
            cardType: 1,
            sex: '',
            place: '',
            address: '',
            tenantType: '',
            subsidy: '',
            userTelephone: '',
            userPassword: '',
            userId: '',
            keyId: ''
          }
        ],
        manufactureId: '',
        rent: '',
        pay: '',
        id: '',
        signingTime: '',
        contractTime: '',
        dueDate: '',
        remark: '',
        roomId: '',
        roomName: '',
        deviceNum: '',
        imei: '',
        roomNum: '',
        roomNameSearch: '',
        acreage: '',
        layout: ''
      },
      enterpriseListOption: [],
      dialogVisible: false,
      checkNodeId: '',
      pageNum: 1,
      pageSize: 10,
      pageTotal: 0,
      leasesId: '',
      paginationConfig: 'total, sizes, prev, pager, next, jumper'
    }
  },
  components: {
    NumberGrow, contractTemplate, zw, getFinger
  },
  created() {
    this.getAboutDevice()
    if (this.$route.params.status) {
      this.search.status = this.$route.params.status
    }
    this.getLeasesList()
    this.getLeasesStatus()
    this.getEnterprise()
    this.getAboutRoom()
    if (document.documentElement.clientWidth < 1080) {
      this.paginationConfig = 'total, prev, pager, next'
    } else {
      this.paginationConfig = 'total, sizes, prev, pager, next, jumper'
    }
  },
  mounted() {
    document.addEventListener('keydown', this.keyDown)
    this.getAllTree()
  },
  methods: {
    // 续租
    batchRenewalMethods() {
      this.$confirm('此操作将延长入住时间, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.batchRenewalFrom.endTime == '' || this.batchRenewalFrom.startTime == '') {
          return this.$message.error('请选择时间范围')
        }
        if (this.batchRenewalFrom.startTime > this.batchRenewalFrom.endTime) {
          return this.$message.error('开始时间不得大于结束时间')
        }
        // 获取该设备信息
        let lockdata = {
          pageNum: 1,
          pageSize: 10,
          q: JSON.stringify({ roomIds: [this.batchmessage.siteId], lockType: 1 })
        }
        httpPost(lockdata, this.$api.getDeviceItems).then(res => {
          console.log(res);
          if (res.success) {
            var lockmessage = res.data.list[0]  // 房间信息
            lockmessage.cardId = this.batchmessage.cardId
            if (lockmessage.manufactureId == 101) {
              var userTelephone = this.batchmessage.phone.substring(this.batchmessage.phone.length - 6, this.batchmessage.phone.length);
              var userPassword = this.batchmessage.phone.substring(this.batchmessage.phone.length - 6, this.batchmessage.phone.length);
              var endTime = new Date(this.batchRenewalFrom.endTime).getTime()
              var startTime = new Date(this.batchRenewalFrom.startTime).getTime()
              var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
              var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
              var data = {
                deviceNum: lockmessage.deviceNum,
                imei: lockmessage.imei,
                userTelephone: userTelephone,
                userPassword: userPassword,
                password: userPassword,
                operateMode: 2,
                order: 6202,
                passwordStartTime: passwordStartTime,
                passwordEndTime: passwordEndTime,
                cardName: this.batchmessage.name,
                roomName: lockmessage.roomName
              }
              ICINLocker.LDAddUser(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data
                .password,
                passwordStartTime, passwordEndTime, data.operateMode, data.order, data.cardName,
                data
                  .roomName, false, (callback) => {
                    console.log(callback);
                    if (callback.success) {
                      var data = {
                        pageNum: 0,
                        pageSize: 0,
                        orderBy: "create_at desc",
                        q: {
                          cardId: this.batchmessage.cardId,
                          deviceNum: lockmessage.deviceNum,
                          types: "0,1,2,3,4",
                          inStatus: "0,1"
                        },
                      };
                      var unbind = {
                        id: this.batchmessage.cardId,
                        startTime: this.batchRenewalFrom.startTime,
                        endTime: this.batchRenewalFrom.endTime
                      };
                      // 重新绑定房间
                      httpPost(unbind, this.$api.setTenant).then((res) => {
                        console.log(res);
                        // 续约
                        let data = {
                          cardId: this.batchmessage.cardId,
                          signingTime: this.batchRenewalFrom.startTime,
                          cutoffTime: this.batchRenewalFrom.endTime,
                          status: 1
                        }
                        httpPost(data, this.$api.postrenewal).then(res1 => {
                          console.log(123123, res1);
                          if (res1.success) {
                            this.getLeasesList()
                          }
                        })
                      })
                      // 修改凭证
                      httpGet(data, this.$api.getCertificates).then((res) => {
                        let data = utils.zlib_unzip(res.data)
                        data.map(lt => {
                          utils.modifyPutCarfid(lockmessage, lt, startTime, endTime)
                        })
                      })
                      this.batchRenewalShow = false
                    } else {
                      this.$message.error("修改失败")
                    }
                  })
            } else if (lockmessage.manufactureId == 201 || lockmessage.manufactureId == 221) {
              var endTime = new Date(this.batchRenewalFrom.endTime).getTime()
              var startTime = new Date(this.batchRenewalFrom.startTime).getTime()
              var unbind = [{
                cardId: this.batchmessage.cardId,
                siteId: lockmessage.roomId,
              }];
              httpPost(unbind, this.$api.unbindCard).then((res) => {
                var data1 = [{
                  cardId: this.batchmessage.cardId,
                  siteId: lockmessage.roomId,
                  startTime: this.batchRenewalFrom.startTime,
                  endTime: this.batchRenewalFrom.endTime
                }];
                httpPost(data1, this.$api.bindCard).then((res) => {
                  console.log(res);
                });
              })
              var data = {
                pageNum: 0,
                pageSize: 0,
                orderBy: "create_at desc",
                q: {
                  cardId: this.batchmessage.cardId,
                  deviceNum: lockmessage.deviceNum,
                  types: "0,1,2,3,4",
                  inStatus: "0,1"
                },
              };
              httpGet(data, this.$api.getCertificates).then((res) => {
                console.log(res);
                let data = utils.zlib_unzip(res.data)
                console.log(data);
                data.map(lt => {
                  utils.modifyPutCarfidzg(lockmessage, lt, startTime, endTime)
                })
              })
              this.batchRenewalShow = false
            } else {
              this.$message.error("暂未发现对应设备")
            }
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    // 开启续组界面
    changebatchRenewalShow(index, row) {
      this.batchRenewalShow = true
      this.batchmessage = row
    },

    // 查询和房间相关的设备
    getAboutDevice() {
      let data = {
        orderBy: "create_time desc",
        pageNum: 0,
        pageSize: 0,
        q: JSON.stringify({
          name: '',
          number: '',
          cardId: ''
        })
      }
      let data1 = []
      httpPost(data, this.$api.getlistNum).then((res) => {
        console.log("123", res);
        if (res.success) {
          res.data.list.map(li => {
            data1.push(li.id)
          })
          let data2 = {
            cardIds: data1
          }
          httpPost(data2, this.$api.onlyTenant).then((res1) => {
            // this.$store.commit("getAboutRoom", res.data.list);
            // this.getlist();
            console.log(res1);
            let data3 = []
            if (res1.success) {
              res1.data.list.map(li => {
                data3.push(li.roomId)
              })
              let data4 = {
                ids: data3
              }
              httpPost(data4, this.$api.onlySiteDevice).then((res) => {
                console.log(res);
                this.AboutDevice = res.data.list;
                this.$store.commit("getAboutDevice", res.data.list);
              });
            }
          });
        }
      })
    },
    getEnterprise() {
      httpGet("", this.$api.getEnterprise).then((res) => {
        res.data.list.map(li => {
          li['pid'] = li.parentId
          li['label'] = li.name
          li['value'] = li.id
        })
        var array = utils.uniqueArray(res.data.list, "id");
        var roomlistZNodes = ztreeToElementTree2(array, []);
        this.enterpriseListOption = roomlistZNodes
        this.enterpriselist = res.data.list
      });
    },
    // 采集卡
    addNfc() {
      var _this = this
      this.$refs.myChild.cardFun(0x8010, function (data) {
        if (data.status == 0) {
          console.log(data)
          _this.setVoucherNfc(data)
        } else {
          _this.$message.error("读卡错误，请检查读卡器是否正常！")
        }
      })
    },
    setVoucherNfc(data) {
      if (data.cardType == 50) {
        var nfc = ""
        var str = data.cardNo.substr(0, 8)
        var arr4 = group(str, 2).reverse();
        arr4.map((li) => {
          nfc += li;
        });
        this.voucher.nfc = nfc.toUpperCase()
        console.log(this.voucher.nfc)
      } else if (data.cardType == 36) {
        this.voucher.idcard = data.cardNo.toUpperCase()
      }
    },
    // 凭证避免重复
    avoidRepetition(e, type) {
      var person = this.drawerRow
      if (type == 12) {
        this.roomtable1.map(li => {
          var content = JSON.parse(li.content)
          if (li.cardId == person.id && content.password == e && li.type == 12) {
            this.$message.error("该身份证已存在")
            this.voucher.idcard = ''
          }
        })
      } else if (type == 13) {
        this.roomtable1.map(li => {
          var content = JSON.parse(li.content)
          if (li.cardId == person.id && content.password == e && li.type == 13) {
            this.$message.error("该NFC已存在")
            this.voucher.nfc = ''
          }
        })
      } else if (type == 14) {
        this.roomtable1.map(li => {
          var content = JSON.parse(li.content)
          if (li.cardId == person.id && content.password == e && li.type == 14) {
            this.$message.error("该密码已存在")
            this.voucher.password = ''
          }
        })
      } else if (type = 14) {

      }
    },
    // 采集指纹
    addfir() {
      let _this = this
      this.$refs.myChild.addFingerprintFun(0x8014, function (data) {
        localStorage.setItem('fingerprint', data)
        _this.localFingerprint = data
      })
    },
    async getFingerData() {
      let _this = this
      await this.$refs.myGetFinger.DetectFinger()
      await this.$refs.myGetFinger.getFingerData('', function (data) {
        console.log(data)
        localStorage.setItem('fingerprint', data.template)
        _this.localFingerprint = data.template
      })
    },

    checkNodeSearch(e) {
      let selectRow = []
      console.log(e)
      e.map(li => {
        selectRow.push(...li)
      })
      console.log(selectRow)
      this.search.siteIds = JSON.stringify(selectRow)
      // this.bindSelectedList = selectRow
    },
    // 导出合同
    exportHtmlWord(index, row) {
      row.signingTime = moment(row.signingTime).format('YYYY-MM-DD')
      row.contractTime = moment(row.contractTime).format('YYYY-MM-DD')
      row['upperCase'] = smallToBig(row.rent)
      this.exportRow = row
      this.dialogVisibleExport = true
    },
    exportWord() {
      let arr = document.querySelector('#question_doc')  //获取dom
      let html = arr.innerHTML; //获取html的内容
      let htmlStr = `
      <!DOCTYPE html>
      <html lang="en">
        <body style="font-family:方正仿宋_GBK;mso-ascii-font-family:'Times New Roman';">
          ${html}
        </body>
      </html>`;  //把获取到的html放入到原生的html中
      saveAs(
        htmlDocx.asBlob(htmlStr, { orientation: 'landscape' }),
        '房屋租赁合同.doc'
      );  // 导出为word
    },
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        if (this.$route.name == 'Login') {
          this.handleSearch();
        }
      }
    },
    // 选择搜索人员
    handleSelectPerson(index, item) {
      let personInfo = JSON.parse(item.info)
      this.form.tenant[index].id = item.id
      this.form.tenant[index].phone = item.phone
      this.form.tenant[index].number = item.number
      this.form.tenant[index].sex = item.sex
      this.form.tenant[index].name = item.name
      this.form.tenant[index].userTelephone = personInfo.userTelephone
      this.form.tenant[index].userPassword = personInfo.userPassword
      this.form.tenant[index].userId = personInfo.userId
      this.form.tenant[index].keyId = personInfo.keyId
      this.getcertificate()
    },
    // 获取人员
    querySearchAsync(queryString, cb) {
      let q = {
        name: queryString,
      };
      let data = {
        pageSize: 10,
        pageNum: 1,
        q: JSON.stringify(q),
      };
      let personInfo = [];
      this.loading = true;
      httpPost(data, this.$api.getlistNum).then((res) => {
        personInfo = res.data.list;
        let restaurants = res.data.list;
        let results = queryString ?
          restaurants.filter(this.createFilter(queryString)) :
          restaurants;
        cb(results);
      });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.name.indexOf(queryString) === 0;
      };
    },
    // 同步合约状态
    syncContractStatusMethods() {
      httpGet('', '/v1/leases/auto/UpdatePayment').then(res2 => {

      })
      httpGet('', this.$api.getAutoRetreat).then(res => {
        if (res.success) {
          this.$message.success('同步成功')
          this.getLeasesList()
          this.getLeasesStatus()
        } else {
          this.$message.error('同步失败')
        }
      })
    },
    // 确认修改备注
    confirmRemark(index, row) {
      let list = [
        {
          id: row.id,
          remark: row.remark
        }
      ]
      httpPost(list, this.$api.postUpdateLeases).then(res => {
        if (res.success) {
          this.$message.success('更新成功')
          this.modifyIndex = ''
          this.getLeasesList()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 修改备注
    setRemark(index, row) {
      if (this.modifyIndex === '') {
        this.modifyIndex = index
      } else {
        this.modifyIndex = ''
      }
    },
    // 确认是否有重复人员签约合同
    async setLeasesMethods(cardId, callback) {
      let QData = utils.validObject({
        phone: cardId,
      })
      let data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderBy: "create_time desc",
        q: JSON.stringify(QData)
      }
      if (data.q == '{}') {
        delete data.q
      }
      httpPost(data, this.$api.postLeasesList).then(res => {
        if (res.success) {
          let list = []
          res.data.list.map(li => {
            if (li.status == 1 || li.status == 2) {
              list.push(li)
            }
          })
          if (list.length > 0) {
            callback(false)
          } else {
            callback(true)
          }
        } else {
          callback(false)
        }
      })
    },
    // 获取合同列表
    getLeasesList() {
      let QData = utils.validObject({
        phone: this.search.phone,
        name: this.search.name,
        status: this.search.status,
        signingTime: this.search.signingTime,
        contractTime: this.search.contractTime,
        siteIds: this.search.siteIds
      })
      let data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderBy: "create_time desc",
        q: JSON.stringify(QData)
      }
      if (data.q == '{}') {
        delete data.q
      }
      httpPost(data, this.$api.postLeasesList).then(res => {
        if (res.success) {
          res.data.list.map(li => {
            li.signingTime = moment(li.signingTime).format('YYYY-MM-DD HH:mm:ss')
            li.contractTime = moment(li.contractTime).format('YYYY-MM-DD HH:mm:ss')
            li.createTime = moment(li.createTime).format('YYYY-MM-DD HH:mm:ss')
            // li.monthRent = JSON.parse(li.expand).rent || 0
          })
          this.tableList = res.data.list
          this.pageTotal = res.data.total
          this.contractStatus.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 获取合约状态统计
    getLeasesStatus() {
      httpGet('', this.$api.getLeasesStatusstatistics).then(res => {
        if (res.success) {
          let list = res.data
          let contractStatus = {
            total: 0,
            signed: 0,
            expired: 0,
            arrears: 0,
            toBeSigned: 0
          }
          list.map(li => {
            if (li.value === 0) {
              li.lable = '待签约'
              contractStatus.toBeSigned += li.total
            } else if (li.value === 1) {
              li.lable = '已签约'
              contractStatus.signed += li.total
            } else if (li.value === 2) {
              li.lable = '已欠费'
              contractStatus.arrears += li.total
            } else if (li.value === 3) {
              li.lable = '已退租'
              contractStatus.expired += li.total
            }
          })
          this.contractStatus = contractStatus
        }
      })
    },
    // 删除合约
    deleteAgreement(index, row) {
      this.$confirm("是否先进行删除操作？", "提示", {
        type: "warning",
      }).then(() => {
        let data = {
          ids: [row.id]
        }
        httpPost(data, this.$api.postDeleteLeases).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getLeasesList()
            this.getLeasesStatus()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    // 更新合约内容
    updateAgreement(index, row) {
      this.updateAgreementRow = row
      this.updateDialogStatus = true
    },
    // 签约
    async signAContract() {
      let info = JSON.parse(localStorage.getItem('info'))
      let formData = this.form
      await this.setLeasesMethods(formData.tenant[0].phone, (callback) => {
        console.log(this, callback)
        if (callback) {
          if (formData.pay === '') {
            this.$message.error('请选择支付方式')
          } else if (formData.id === '') {
            this.$message.error('请输入合同编号')
          } else if (formData.dueDate === '') {
            this.$message.error('请选择缴费时间')
          } else if (formData.signingTime === '') {
            this.$message.error('请选择签约时间')
          } else if (formData.contractTime === '') {
            this.$message.error('请选择有效期')
          } else if (formData.tenant[0].phone === '' || formData.tenant[0].name === '') {
            this.$message.error('请选择人员')
          } else if (formData.deviceNum === '' || formData.roomName === '') {
            this.$message.error('请选择房间')
          } else if (this.documentType === '') {
            this.$message.error('请选择录入凭证类型')
          } else if (this.value2[0] == '' || this.value2[1] == '') {
            this.$message.error("请选择开始结束时间")
          } else {
            // 获取所有人员
            // var q = {
            // };
            // var data = {
            //   pageNum: 0,
            //   pageSize: 0,
            //   orderBy: "create_time desc",
            //   q: JSON.stringify(q),
            // };
            // httpPost(data, this.$api.getlistNum).then((res1) => {
            //   console.log(res1)
            //   if (res1.success) {
            //     let sum = 0
            //     res1.data.list.map(li => {
            //       if (li.phone != this.form.tenant[0].phone) {
            //         sum += 1
            //       }
            //     })
            //     if (sum == res1.data.total) {
            //       this.saveEdit()
            //     }
            //   }
            // });

            let dueDate = formData.dueDate.getDate()
            console.log(dueDate)
            let leasesData = {
              papersType: formData.tenant[0].cardType,
              place: formData.tenant[0].place,
              number: formData.id,
              sex: formData.tenant[0].sex,
              phone: formData.tenant[0].phone,
              name: formData.tenant[0].name,
              mailing: formData.tenant[0].address,
              leasesType: formData.tenant[0].tenantType,
              subsidyStandards: formData.tenant[0].subsidy,
              payStandards: formData.pay,
              signingTime: formData.signingTime,
              contractTime: formData.contractTime,
              cutoffTime: formData.contractTime,
              dueDate: formData.dueDate,
              remark: formData.remark,
              enterpriseId: info.enterpriseId,
              siteId: formData.roomId,
              cardId: formData.tenant[0].id,
              address: formData.roomName,
              status: 1,
              monthRent: formData.rent,
              expand: JSON.stringify({
                rent: formData.rent,
                dueDay: dueDate - 5,
              })//扩展属性
            }
            httpPost(leasesData, this.$api.postAddLeases).then(res => {
              if (res.success) {
                this.$message.success('签约成功')
                let data3 = {
                  code: "zg/getEmergence",
                  data: {
                    lockerId: this.form.deviceNum,
                  },
                };
                httpPost(data3, this.$api.sendCommand).then((res4) => {
                  let sendSData = {
                    name: formData.tenant[0].name,
                    address: formData.roomName,
                    number: formData.id,
                    date: dueDate,
                    total: formData.rent,
                    phone: formData.tenant[0].phone,
                    enterpriseId: info.enterpriseId,
                    password: res4.data.data
                  }
                  httpPost(sendSData, this.$api.sendSigningNotice).then(res => {
                    if (res.success) {
                      this.$message.success("通知成功")
                      // let data = {
                      //   orderBy: "create_time desc",
                      //   pageNum: 0,
                      //   pageSize: 0,
                      //   q: JSON.stringify({})
                      // }
                      // httpPost(data, this.$api.getlistNum).then(res => {
                      //   let sum = 0;
                      //   res.data.list.map(li => {
                      //     if (li.phone != this.form.tenant[0].phone) {
                      //       sum += 1
                      //     }
                      //   })
                      //   if (sum == res.data.total) {
                      //     this.saveEdit()
                      //   }
                      // })
                    } else {
                      this.$message.error("通知失败")
                    }
                  })
                })
                this.getLeasesList()
                this.getLeasesStatus()
                this.leasesId = res.data
                formData.tenant.map(async (li, index) => {
                  if (li.id === '') {
                    // return
                    console.log(1206)
                    await this.addPeopleMethods(li, index)
                  } else {
                    console.log(1209)
                    // return
                    await this.bindCheckIn(li, index)
                  }
                })
                this.dialogVisible = false
              } else {
                this.$message.error(res.message)
                this.dialogVisible = false
              }
            })
          }
        } else {
          this.$message.error('该人员已有合约，请重新选择')
        }
      })
    },
    getcheckInList() {
      var data = {
        ids: [this.form.tenant[0].id]
      }
      httpPost(data, this.$api.getTenant).then(res => {
        if (res.code == 200) {
          this.checkInListing = res.data
        } else {
          this.checkInListing = []
        }
      })
    },
    // 绑定房间
    bindsave() {
      console.log('绑定房间')
      var fjid = [];
      var _this = this
      var time1 = moment(this.form.signingTime).valueOf() / 1000
      var time2 = moment(this.form.contractTime).valueOf() / 1000
      if (time1 == '' || time2 == '') {
        this.$message.error("请选择开始结束时间")
        return false;
      }
      if (time1 > time2) {
        this.$message.error('开始时间不能大于结束时间')
        return false
      }
      var str = {
        cardId: this.form.tenant[0].id,
        siteId: this.form.roomId,
        startTime: time1,
        endTime: time2
      };
      fjid = [str];
      if (this.form.manufactureId == 201 || this.form.manufactureId == 221) {
        var data = {
          lockerId: this.form.deviceNum,
          imei: this.form.imei,
          lockerUserId: this.form.tenant[0].userPassword,
          keyId: this.form.tenant[0].userPassword,
          role: 0,
          action: 1,
          order: 6226,
          cardName: this.form.tenant[0].name,
          roomName: this.form.roomName
        };
        ICINLocker.addUserToLock(data.lockerId, data.imei, data
          .lockerUserId, data.role, data.action, data.order, data.cardName, data
          .roomName, (
            callback) => {
          console.log("12", callback)
          if (callback.success) {
            var locakUserdata = {
              deviceNum: this.form.deviceNum,
              imei: this.form.imei,
              cardId: this.form.tenant[0].id,
              content: JSON.stringify(
                data
              ), //operateMode:NFC-10、把人员添加到凭证-1
              type: 26,
              serial: callback.data.serialNumber,
              startTime: time1,
              endTime: time2,
            }
            utils.sendLockUser(locakUserdata, (callbackLOCK) => {
              console.log(callbackLOCK)
              if (callbackLOCK.success) {
                // 录入凭证
                this.savevoucherlist.map(li => {
                  this.bindsave1(li)
                })
              }
            })

          } else {
            this.$message.error(callback.msg);
            if (callback.code == 201016) {
              httpPost(fjid, this.$api.bindCard).then((res) => {
                if (res.success) {
                  this.getcheckInList()
                  this.getAboutRoom();
                  this.$message.success("用户门锁已存在")
                } else {
                  this.$message.error("添加失败")
                }
              });
            }
          }
        })
        httpPost(fjid, this.$api.bindCard).then((res) => {
          console.log(res)
          if (res.success) {
            this.getAboutRoom();
            this.getcheckInList()
          } else {
            this.$message.error("添加失败")
          }
        });
      } else if (this.form.manufactureId == 101) {
        var userstr = {
          imei: this.form.imei,
          deviceNum: this.form.deviceNum,
          userTelephone: this.form.tenant[0].userTelephone,
          userPassword: this.form.tenant[0].userPassword,
          password: this.form.tenant[0].userPassword,
          operateMode: 26,
          order: 6226,
          passwordStartTime: this.moment(this.value2[0]).format(
            "YYYYMMDDHHmmss"),
          passwordEndTime: this.moment(this.value2[1]).format("YYYYMMDDHHmmss"),
          is: false,
          cardName: this.form.tenant[0].name,
          roomName: this.form.roomName
        };
        ICINLocker.LDAddUser(userstr.deviceNum, userstr.imei, userstr.userTelephone,
          userstr.userPassword, userstr.password, userstr.passwordStartTime,
          userstr.passwordEndTime, userstr.operateMode, userstr.order, userstr
          .cardName, userstr.roomName, false, (callback) => {
            if (callback.success) {
              console.log(_this.value2)
              var locakUserdata = {
                deviceNum: this.form.deviceNum,
                imei: this.form.imei,
                cardId: this.form.tenant[0].id,
                content: JSON.stringify(
                  userstr
                ), //operateMode:NFC-10、把人员添加到凭证-1
                type: 26,
                serial: callback.data.serialNumber,
                startTime: time1,
                endTime: time2,
              }
              utils.sendLockUser(locakUserdata, (callbackLOCK) => {

              })
              httpPost(fjid, this.$api.bindCard).then((res) => {
                if (res.success) {
                  this.getAboutRoom();
                  this.getcheckInList()
                } else {
                  this.$message.error("添加失败")
                }
              });
            } else {
              this.$message.error(callback.msg);
            }
          })
      } else if (this.form.manufactureId == 1201) {
        httpPost(fjid, this.$api.bindCard).then((res) => {
          if (res.success) {
            this.getAboutRoom();
            this.getcheckInList()
          } else {
            this.$message.error("添加失败")
          }
        });
      }

    },
    // 查询和人员相关的房间
    getAboutRoom() {
      let data = {
        orderBy: "create_time desc",
        pageNum: 0,
        pageSize: 0,
        q: JSON.stringify({
          name: '',
          number: '',
          cardId: ''
        })
      }
      let data1 = []
      httpPost(data, this.$api.getlistNum).then((res) => {
        console.log("123", res);
        if (res.success) {
          res.data.list.map(li => {
            data1.push(li.id)
          })
          let data2 = {
            cardIds: data1
          }
          httpPost(data2, this.$api.onlyTenant).then((res1) => {
            this.$store.commit("getAboutRoom", res.data.list);
          });
        }
      })
    },
    // 添加人员
    saveEdit() {
      const info = localStorage.getItem('info')
      // 添加人员的凭证保存
      let phone = this.form.tenant[0].phone
      let infostr = {
        userTelephone: phone,
        userPassword: phone.substring(phone.length - 6, phone.length),
        userId: phone.substring(phone.length - 6, phone.length),
        keyId: phone.substring(phone.length - 6, phone.length)
      };
      var data = {
        cardId: "",
        cardState: 1,
        info: JSON.stringify(infostr),
        name: this.form.tenant[0].name,
        number: this.form.tenant[0].number,
        phone: this.form.tenant[0].phone,
        sex: parseInt(this.form.tenant[0].sex),
        enterpriseId: info.enterpriseId,
        type: info.type,
      };
      RequestSet.addPeople(data, (callback) => {
        console.log(callback)
        if (callback.success) {
          // 绑定房间
          // this.bindsave()
          let dataprise = []
          this.checkEnterpriseNode.map(li => {
            var obj = {
              itemId: callback.data,
              orderId: li.value,
            }
            dataprise.push(obj)
          })
          if (dataprise.length > 0) {
            httpPost(dataprise, this.$api.personBindEnterprise).then(res => {

            })
          }
          let ids = {
            ids: [callback.data]
          }
          httpPost(ids, this.$api.createkeyCard).then(res => {

          })
          let data = {
            orderBy: "create_time desc",
            pageNum: 0,
            pageSize: 0,
            q: JSON.stringify({
              name: '',
              number: '',
              cardId: ''
            })
          }
          let data1 = []
          httpPost(data, this.$api.getlistNum).then((res) => {
            console.log("123", res);
            if (res.success) {
              res.data.list.map(li => {
                data1.push(li.id)
              })
              let data2 = {
                cardIds: data1
              }
              httpPost(data2, this.$api.onlyTenant).then((res1) => {
                this.$store.commit("getAboutRoom", res.data.list);
              });
            }
          })
        } else {
        }
      })
      if (this.WhetherToGreatAnAccount) {
        const info = localStorage.getItem('info')
        var enterpriseName = info.enterpriseId
        if (enterpriseName) {
          var addform = {
            username: this.form.tenant[0].number,
            phone: this.form.tenant[0].phone,
            password: this.form.tenant[0].phone.substring(this.form.tenant[0].phone.length - 6, this.form.tenant[0].phone.length),
            userType: 3,
            identity: 3,
            tenantId: this.$store.state.tenantId,
            enterpriseName: enterpriseName.name,
            enterpriseId: info.enterpriseId
          }
          httpPost(addform, this.$api.addUser).then((res3) => {
            console.log(res3)
            if (res3.success) {
              this.$message.success("创建账号成功")
              // 绑定房间
              this.bindsave()
            } else {
              this.$message.error("创建账号失败")
            }
          })
        } else {
          this.$message.error("请选择所属部门")
        }

      }

    },
    // 绑定入住
    bindCheckIn(li, index) {
      if (this.form.manufactureId === 201 || this.form.manufactureId === 221) {
        ICINLocker.addUserToLock(this.form.deviceNum, this.form.imei, li.userPassword, '0', '1', '6226', li.name, this.form.roomName, (callback) => {
          if (callback.success) {
            let data = [{
              cardId: li.id,
              siteId: this.form.roomId,
              startTime: this.form.signingTime,
              endTime: this.form.contractTime
            }]
            httpPost(data, this.$api.bindCard).then(async (res1) => {
              if (res1.success) {
                await this.savevoucherlist.map(li => {
                  this.bindsave1(li)
                })
              }
            })
            let userStr = {
              lockerId: this.form.deviceNum,
              imei: this.form.imei,
              lockerUserId: li.userPassword,
              keyId: li.userPassword,
              userTelephone: li.userTelephone,
              userPassword: li.userPassword,
              role: 0,
              action: 1,
              order: 6226,
              cardName: li.name,
              roomName: this.form.roomName
            };
            let lockUserData = {
              deviceNum: this.form.deviceNum,
              imei: this.form.imei,
              cardId: li.id,
              content: JSON.stringify(
                userStr
              ),
              type: 26,
              serial: callback.data.serialNumber,
              startTime: this.form.signingTime.getTime() / 1000,
              endTime: this.form.contractTime.getTime() / 1000,
            }
            utils.sendLockUser(lockUserData, (callbackLOCK) => {
              // if (callbackLOCK.success) {
              //   this.saveEdit()
              // }
            })
          } else {
            this.$message.error(callback.msg)
          }
        })
      } else if (this.form.manufactureId === 101) {
        let passWordStartTime = moment(this.form.signingTime).format("YYYYMMDDHHmmss")
        let passWordEndTime = moment(this.form.contractTime).format("YYYYMMDDHHmmss")
        ICINLocker.LDAddUser(this.form.deviceNum, this.form.imei, li.userTelephone,
          li.userPassword, li.userPassword, passWordStartTime, passWordEndTime, 26, 6226, li.name, this.form.roomName, false, (callback) => {
            if (callback.success) {
              let data = [{
                cardId: li.id,
                siteId: this.form.roomId,
                startTime: this.form.signingTime,
                endTime: this.form.contractTime
              }]
              httpPost(data, this.$api.bindCard).then((res1) => {

              })
              let userStr = {
                lockerId: this.form.deviceNum,
                imei: this.form.imei,
                lockerUserId: li.userPassword,
                keyId: li.userPassword,
                userTelephone: li.userTelephone,
                userPassword: li.userPassword,
                role: 0,
                action: 1,
                order: 6226,
                cardName: li.name,
                roomName: this.form.roomName
              };
              let lockUserData = {
                deviceNum: this.form.deviceNum,
                imei: this.form.imei,
                cardId: li.id,
                content: JSON.stringify(
                  userStr
                ),
                type: 26,
                serial: callback.data.serialNumber,
                startTime: this.form.signingTime.getTime() / 1000,
                endTime: this.form.contractTime.getTime() / 1000,
              }
              utils.sendLockUser(lockUserData, (callbackLOCK) => {
                // if (callbackLOCK.success) {
                //   this.saveEdit()
                // }
              })
            } else {
              this.$message.error(callback.msg)
            }
          })
      }
    },
    // 添加新人员
    async addPeopleMethods(item, index) {
      console.log("测试")
      let info = JSON.parse(localStorage.getItem('info'))
      let infoStr = {
        userTelephone: item.phone,
        userPassword: item.phone.substring(item.phone.length - 6, item.phone.length),
        userId: item.phone.substring(item.phone.length - 6, item.phone.length),
        keyId: item.phone.substring(item.phone.length - 6, item.phone.length)
      };
      let data = {
        cardId: '',
        cardState: 1,
        info: JSON.stringify(infoStr),
        name: item.name,
        number: item.number,
        phone: item.phone,
        sex: parseInt(item.sex),
        enterpriseId: info.enterpriseId,
        type: 0,
      };
      RequestSet.addPeople(data, (callback) => {
        if (callback.success) {
          let leasesData = [
            {
              id: this.leasesId,
              cardId: callback.data
            }
          ]
          setTimeout(() => {
            httpPost(leasesData, this.$api.postUpdateLeases).then(res => { })
          }, 1000)
          let ids = {
            ids: [callback.data]
          }
          this.form.tenant[index].id = callback.data //新增人员id加入数据源
          this.form.tenant[index].userTelephone = infoStr.userTelephone
          this.form.tenant[index].userPassword = infoStr.userPassword
          this.form.tenant[index].userId = infoStr.userId
          this.form.tenant[index].keyId = infoStr.keyId
          httpPost(ids, this.$api.createkeyCard).then(res => {
          })
          this.bindCheckIn(this.form.tenant[index], index)
        } else {
          this.$message.error("123", callback.message)
        }
      })
    },
    // 删除同住人
    deleteCohabitant(index) {
      this.form.tenant.splice(index, 1)
    },
    // 添加同住人
    addCohabitant() {
      let sourceData = {
        id: '',
        name: '',
        phone: '',
        number: '',
        cardType: 1,
        sex: '',
        place: '',
        address: '',
        tenantType: '',
        subsidy: '',
        userTelephone: '',
        userPassword: '',
        userId: '',
        keyId: ''
      }
      this.form.tenant.push(sourceData)
    },
    // 选择房间
    async selectRoom(index, row) {
      let repeatStatus = utils.isRepeat(this.form.tenant)
      if (repeatStatus) {
        this.$message.warning('同住人员有重复的表单信息，请填写正确表单信息')
        this.activeNames = '1'
      } else {
        let dataList = this.form.tenant
        let resultStatus = true
        for (let i = 0; i < dataList.length; i++) {
          if (dataList[i].number === '' || dataList[i].phone === '' || dataList[i].name === '' || dataList[i].cardType === '') {
            resultStatus = false
          }
        }
        if (!resultStatus) {
          this.$message.warning('请正确填写签约人表单信息')
          this.activeNames = '1'
        } else {
          this.form.roomName = row.path
          this.form.roomId = row.id
          this.form.acreage = row.acreage
          this.form.layout = row.layout
          await this.getDeviceInfo()
        }
      }
    },
    // 获取房间对应设备信息
    getDeviceInfo() {
      let q = {
        roomIds: [this.form.roomId]
      }
      let data = {
        q: JSON.stringify(q),
        pageNum: 1,
        pageSize: 1,
      };
      httpPost(data, this.$api.getDeviceItems).then((res) => {
        if (res.success) {
          if (res.data.list.length > 0) {
            this.form.deviceNum = res.data.list[0].deviceNum
            this.form.imei = res.data.list[0].imei
            this.form.manufactureId = res.data.list[0].manufactureId
            this.activeNames = '3'
          } else {
            this.form.roomId = ''
            this.form.roomName = ''
            this.form.acreage = ''
            this.form.layout = ''
            this.$message.error('该房间还未绑定设备，请绑定设备后进行入住')
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 搜索房源
    searchRoom() {
      let q = {
        name: this.form.roomNameSearch,
        ancestor: this.checkNodeId,
        isRoom: 1
      };
      let data = {
        q: JSON.stringify(q),
        type: 0,
        pageNum: 1,
        pageSize: 10,
      };
      httpGet(data, this.$api.getSiteList).then(res => {
        if (res.success) {
          res.data.list.list.map(li => {
            let name = utils.findIndexArray(this.roomList, li.id, [])
            let layoutText = li.layout === 0 ? '单间' : li.layout === 1 ? '一室一厅' : li.layout === 2 ? '两室一厅' : '三室一厅'
            let path = ''
            if (name) {
              path = name.join('/')
            }
            li['layoutText'] = layoutText
            li['path'] = path
          })
          this.tableDataRom = res.data.list.list
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 搜索对应人员
    searchPeople(index) {
      if (!utils.verificationPhone(this.form.tenant[index].phone) && this.form.tenant[index].phone.length > 0) {
        this.$message.error('手机格式错误')
      }
      if (IdentityCodeValid(this.form.tenant[index].number)) {
        this.$message.error('身份证号错误')
      }
      let q = {
        number: this.form.tenant[index].number,
        phone: this.form.tenant[index].phone,
      };
      let data = {
        pageNum: 1,
        pageSize: 10,
        orderBy: "create_time desc",
        q: JSON.stringify(q),
      };
      httpPost(data, this.$api.getlistNum).then((res1) => {
        if (res1.success) {
          if (res1.data.list.length > 0) {
            let personInfo = JSON.parse(res1.data.list[0].info)
            this.form.tenant[index].id = res1.data.list[0].id
            this.form.tenant[index].phone = res1.data.list[0].phone
            this.form.tenant[index].number = res1.data.list[0].number
            this.form.tenant[index].sex = res1.data.list[0].sex
            this.form.tenant[index].name = res1.data.list[0].name
            this.form.tenant[index].userTelephone = personInfo.userTelephone
            this.form.tenant[index].userPassword = personInfo.userPassword
            this.form.tenant[index].userId = personInfo.userId
            this.form.tenant[index].keyId = personInfo.keyId
          } else {
            this.form.tenant[index].id = ''
            this.form.tenant[index].phone = ''
            this.form.tenant[index].number = ''
            this.form.tenant[index].sex = ''
            this.form.tenant[index].name = ''
            this.form.tenant[index].userTelephone = ''
            this.form.tenant[index].userPassword = ''
            this.form.tenant[index].userId = ''
            this.form.tenant[index].keyId = ''
            this.$message.error("未找到人员")
          }
        } else {
          this.$message.error(res1.message)
        }
      })
    },
    // 获取房源
    getAllTree() {
      let data = {};
      httpGet(data, this.$api.getTree).then((res) => {
        let userList = [];
        let temp = {},
          arr = [];
        res.data.forEach((item, index) => {
          if (!temp[item.id]) {
            arr.push(item);
            temp[item.id] = true;
          }
        });
        arr.map((li) => {
          if (li.expand) {
            if (JSON.parse(li.expand).type == "0") {
              userList.push(li);
            }
          }
        });
        let list = res.data.sort((pre, cur) => pre.id - cur.id)
        let arrData = uniqueArray1(list, "id")
        this.roomList = ztreeToElementTree(arrData, {});
      });
    },
    // 选择房源
    async checkNode(e) {
      this.checkNodeId = e[e.length - 1]
      let options = this.roomList
      let arr = await this.getId(options, e[e.length - 1])
      let listArr = [arr[0]]
      let obj = this.getNodeId(listArr)
      this.form.roomId = obj
      this.searchRoom()
    },
    getId(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]]
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node;
          }
        }
      }
    },
    getNodeId(list, newNodeId = []) {
      for (let i in list) {
        newNodeId.push(list[i].id)
        if (list[i].children) {
          this.getNodeId(list[i].children, newNodeId);
        }
      }
      return newNodeId;
    },
    getParentId(list, id) {
      for (let i in list) {
        if (list[i].id == id) {
          return [list[i]]
        }
        if (list[i].children) {
          let node = this.getParentId(list[i].children, id);
          if (node !== undefined) {
            return node.concat(list[i])
          }
        }
      }
    },
    // 签约
    signContract() {
      this.dialogVisible = true
      // this.getAllTree()
    },
    // 保存凭证
    savevoucher() {
      if (this.value2[0] == '' || this.value2[1] == '') {
        return this.$message.error('开始时间和结束时间不能为空')
      }
      if (this.value2[0] > this.value2[1]) {
        return this.$message.error('开始时间不能大于结束时间')
      }
      if (this.value2[0] < this.form.signingTime || this.value2[0] > this.form.contractTime) {
        return this.$message.error('开始时间不能超出祖约时间')
      }
      if (this.value2[1] < this.form.signingTime || this.value2[1] > this.form.contractTime) {
        return this.$message.error('结束时间不能超出租约时间')
      }
      if (this.documentType == 11) {
        var fingerprintAlias = ''
        var fingerprint = localStorage.getItem("fingerprint");
        let pzname = '指纹' + this.voucherlist.length + 1
        var name = this.form.tenant[0].name
        if (this.savevoucherlist.length != 0) {
          this.savevoucherlist.map(li => {
            if (li.fingerprintAlias != this.voucher.fingerprintAlias) {
              fingerprintAlias = this.voucher.fingerprintAlias
              let data = {
                fingerprint: fingerprint,
                pzname: pzname,
                name: name,
                fingerprintAlias: fingerprintAlias,
                type: 11,
                passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
                passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
              }
              this.savevoucherlist.push(data)
            } else {
              return this.$message.error('该凭证已保存')
            }
          })
        } else {
          fingerprintAlias = this.voucher.fingerprintAlias
          let data = {
            fingerprint: fingerprint,
            pzname: pzname,
            name: name,
            fingerprintAlias: fingerprintAlias,
            type: 11,
            passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
            passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          this.savevoucherlist.push(data)
        }
      } else if (this.documentType == 12) {
        var password = ''
        if (this.savevoucherlist.length != 0) {
          this.savevoucherlist.map(li => {
            if (li.password != this.voucher.idcard) {
              if (this.voucher.idcard.length == 0) {
                return this.$message.error('请输入身份证号')
              } else if (this.voucher.idcard.length == 16) {
                password = this.voucher.idcard
              } else {
                password = dec2hex(this.voucher.idcard)
              }
              var pzname = '身份证' + this.voucherlist.length + 1
              var name = this.form.tenant[0].name
              let data = {
                pzname: pzname,
                name: name,
                type: 12,
                password: password.toUpperCase(),
                passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
                passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
              }
              this.savevoucherlist.push(data)
            } else {
              return this.$message.error('该凭证已保存')
            }
          })
        } else {
          if (this.voucher.idcard.length == 0) {
            return this.$message.error('请输入身份证号')
          } else if (this.voucher.idcard.length == 16) {
            password = this.voucher.idcard
          } else {
            password = dec2hex(this.voucher.idcard)
          }
          var pzname = '身份证' + this.voucherlist.length + 1
          var name = this.form.tenant[0].name
          let data = {
            pzname: pzname,
            name: name,
            type: 12,
            password: password.toUpperCase(),
            passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
            passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          this.savevoucherlist.push(data)
        }
      } else if (this.documentType == 13) {
        var nfc = ''
        if (this.savevoucherlist.length != 0) {
          this.savevoucherlist.map(li => {
            if (li.password != this.voucher.nfc) {
              if (this.voucher.nfc.length == 0) {
                return this.$message.error('请输入NFC')
              } else if (this.voucher.nfc.length == 8) {
                var nfc = this.voucher.nfc
              } else {
                var array3 = dec2hex(this.voucher.nfc)
                var arr4 = group(array3, 2)
                arr4.map((li) => {
                  nfc += li
                })
              }
              var pzname = 'NFC' + this.savevoucherlist.length + 1
              var name = this.form.tenant[0].name
              let data = {
                pzname: pzname,
                name: name,
                type: 13,
                password: nfc.toUpperCase(),
                passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
                passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
              }
              this.savevoucherlist.push(data)
            } else {
              return this.$message.error('该凭证已存在')
            }
          })
        } else {
          if (this.voucher.nfc.length == 0) {
            return this.$message.error('请输入NFC')
          } else if (this.voucher.nfc.length == 8) {
            var nfc = this.voucher.nfc
          } else {
            var array3 = dec2hex(this.voucher.nfc)
            var arr4 = group(array3, 2)
            arr4.map((li) => {
              nfc += li
            })
          }
          var pzname = 'NFC' + this.savevoucherlist.length + 1
          var name = this.form.tenant[0].name
          let data = {
            pzname: pzname,
            name: name,
            type: 13,
            password: nfc.toUpperCase(),
            passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
            passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          this.savevoucherlist.push(data)
        }
      } else if (this.documentType == 14) {
        if (this.savevoucherlist.length != 0) {
          this.savevoucherlist.map(li => {
            if (li.password != this.voucher.password) {
              if (this.voucher.password.length != 6) {
                return this.$message.error('密码长度为6位')
              } else if (this.voucher.password == 0) {
                return this.$message.error('请输入密码')
              }
              var pzname = '密码' + this.savevoucherlist.length + 1
              var name = this.form.tenant[0].name
              let data = {
                pzname: pzname,
                password: this.voucher.password,
                type: 14,
                name: name,
                passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
                passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
              }
              this.savevoucherlist.push(data)
            } else {
              return this.$message.error('该凭证已存在')
            }
          })
        } else {
          if (this.voucher.password.length != 6) {
            return this.$message.error('密码长度为6位')
          } else if (this.voucher.password == 0) {
            return this.$message.error('请输入密码')
          }
          var pzname = '密码' + this.savevoucherlist.length + 1
          var name = this.form.tenant[0].name
          let data = {
            pzname: pzname,
            password: this.voucher.password,
            type: 14,
            name: name,
            passWordStartTime: moment(this.value2[0]).format('YYYY-MM-DD HH:mm:ss'),
            passWordEndTime: moment(this.value2[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          this.savevoucherlist.push(data)
        }
      } else if (this.documentType == 15) {

      }
    },
    // 删除凭证
    deletefun(index, row) {

      this.savevoucherlist = this.savevoucherlist.filter(li => {
        return li.password != row.password
      })
    },
    // 录入凭证
    bindsave1(li) {
      let str = {};
      let cardName = this.form.tenant[0].name,
        pzname = '';
      let sort = this.getTypeSort(this.roomtable1, li.type)
      if (li.type == 11 && li.fingerprintAlias == '') {
        this.$message.error("请选择指纹别名");
        return false
      }
      if (li.type == 11) {
        var fingerprint = li.fingerprint;
        var indexofstr = fingerprint.indexOf(',')
        if (indexofstr != -1) {
          var array = fingerprint.split(",");
          var num = this.Bytes2Str(array);
          fingerprint = num
        }
        str = {
          username: li.name,
          pzname: li.pzname,
          userTelephone: this.form.tenant[0].userTelephone,
          userPassword: this.form.tenant[0].userPassword,
          keyId: this.form.tenant[0].keyId || '',
          userId: this.form.tenant[0].userId || '',
          fingerprintAlias: li.fingerprintAlias,
          password: "",
          passwordStartTime: li.passWordStartTime,
          passwordEndTime: li.passWordEndTime,
          operateMode: 16,
          order: 6216,
          fingerprint: li.fingerprint,
        };
      } else if (li.type == 12) {
        var arr2 = ''
        if (this.voucher.idcard.length == 16) {
          arr2 = this.voucher.idcard
        } else if (this.voucher.idcard.length == 0) {
          this.$message.error("请输入身份证")
          return false
        } else {
          arr2 = dec2hex(this.voucher.idcard);
        }
        if (pzname == '') {
          pzname = '身份证' + sort
        }
        str = {
          username: li.name,
          pzname: li.pzname,
          userTelephone: this.form.tenant[0].userTelephone,
          userPassword: this.form.tenant[0].userPassword,
          keyId: this.form.tenant[0].keyId || '',
          userId: this.form.tenant[0].userId || '',
          operateMode: 13,
          order: 6213,
          password: li.password, //this.voucher.idcard,
          passwordStartTime: li.passWordStartTime,
          passwordEndTime: li.passWordEndTime,
          is: false,
        };
      } else if (li.type == 13) {
        var nfc = "";
        if (this.voucher.nfc.length == 8) {
          nfc = this.voucher.nfc
        } else if (this.voucher.nfc.length == 0) {
          this.$message.error("请输入NFC")
          return false
        } else {
          var array3 = dec2hex(this.voucher.nfc);
          var arr4 = group(array3, 2)
          arr4.map((li) => {
            nfc += li;
          });
        }
        if (pzname == '') {
          pzname = 'NFC' + sort
        }
        if (this.regularCard) {
          nfc = nfc + 'AA55'
        }
        str = {
          username: li.name,
          pzname: li.pzname,
          operateMode: 10,
          order: 6210,
          userTelephone: this.form.tenant[0].userTelephone,
          userPassword: this.form.tenant[0].userPassword,
          keyId: this.form.tenant[0].keyId || '',
          userId: this.form.tenant[0].userId || '',
          password: li.password, //this.voucher.nfc,
          passwordStartTime: li.passWordStartTime,
          passwordEndTime: li.passWordEndTime,
          is: false
        };
      } else if (li.type == 14) {
        if (this.voucher.password.length != 6) {
          this.$message.error("密码长度为6位")
          return false
        } else if (this.voucher.password.length == 0) {
          this.$message.error("请输入密码")
          return false
        }
        if (pzname == '') {
          pzname = '密码' + sort
        }
        str = {
          username: li.name,
          pzname: li.pzname,
          // imei: this.deviceList[0].imei,
          password: li.password,
          userTelephone: this.form.tenant[0].userTelephone,
          userPassword: this.form.tenant[0].userPassword,
          keyId: this.form.tenant[0].keyId || '',
          userId: this.form.tenant[0].userId || '',
          operateMode: 7,
          order: 6207,
          passwordStartTime: moment(li.passWordStartTime).format('YYYYMMDDHHmmss'),
          passwordEndTime: moment(li.passWordEndTime).format('YYYYMMDDHHmmss'),
          is: false,
        };
      } else if (li.type == 15) {

      }
      var data = {
        cardId: this.form.tenant[0].id,
        content: JSON.stringify(str),
        type: li.type,
        startTime: moment(li.passWordStartTime).format('YYYYMMDDHHmmss'),
        endTime: moment(li.passWordEndTime).format('YYYYMMDDHHmmss')
      };
      httpPost(data, this.$api.addCertificates).then(async (res) => {
        this.$message.success('添加成功')
        // 下发凭证
        await this.savevoucherlist.map(li => {
          this.sendVoucher(li)
        })
      });
    },
    // 选择房源，下发凭证
    sendVoucher(li) {
      console.log(li)
      let phone = this.form.tenant[0].phone
      let infostr = {
        userTelephone: phone,
        userPassword: phone.substring(phone.length - 6, phone.length),
        userId: phone.substring(phone.length - 6, phone.length),
        keyId: phone.substring(phone.length - 6, phone.length)
      };
      var roomAbout = this.$store.state.roomAbout
      var fjid = [];
      var resultArr = this.AboutDevice.filter(
        (_item) => _item.roomId == this.form.roomId
      )[0];
      if (resultArr) {
        if (resultArr.imei) {
          if (resultArr.manufactureId == 201 || resultArr.manufactureId == 221) {
            var room = roomAbout.filter(item => item.roomId == resultArr.roomId)[0]
            resultArr.roomName = room.roomName
            this.putCarfidzg(resultArr, li);
          } else if (resultArr.manufactureId == 101) {
            var room = roomAbout.filter(item => item.roomId == resultArr.roomId)[0]
            resultArr.roomName = room.roomName
            this.putCarfid(resultArr, li);
          } else if (resultArr.manufactureId == 1201) {
            var room = roomAbout.filter(item => item.roomId == resultArr.roomId)[0]
            resultArr.roomName = room.roomName
            this.putCarfidLwj(resultArr, li);
          }
        }
      } else {
        this.$message.error("该房间未绑定门锁")
      }
    },
    // 下发凭证
    putCarfidzg(resultArr, row) {
      var phone = this.form.tenant[0].phone
      var data = {};
      var userTelephone = phone.substring(phone.length - 6, phone.length);
      var userPassword = phone.substring(phone.length - 6, phone.length);
      var startTime = new Date(row.passWordStartTime).getTime() / 1000
      var endTime = new Date(row.passWordEndTime).getTime() / 1000
      var passwordStartTime = new Date(row.passWordStartTime).getTime() / 1000
      var passwordEndTime = new Date(row.passWordEndTime).getTime() / 1000
      // var passwordStartTime = JSON.stringify(row.startTime)
      // var passwordEndTime = JSON.stringify(row.endTime)
      // var sort=this.getTypeSort(this.roomtable1,row.type)
      var pzname = row.pzname || ''
      if (passwordStartTime.length == 13) {
        passwordStartTime = startTime / 1000
      }
      if (passwordEndTime.length == 13) {
        passwordEndTime = endTime / 1000
      }

      if (row.type == 11) {
        // if(pzname==''){
        // 	pzname='指纹'+sort
        // }
        var fpId = new Date();
        var fingerprint1 = row.fingerprint;
        var str = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          fingerprintAlias: row.fingerprintAlias,
          userTelephone: userTelephone,
          userPassword: userPassword,
          password: row.password,
          length: fingerprint1.length / 2,
          fpTimeId: fpId.getTime(),
          operateMode: 16,
          type: 1,
          order: 6216,
          fingerprint: fingerprint1,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: row.pzname,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        var data3 = {
          lockerId: resultArr.deviceNum,
          imei: resultArr.imei,
          order: 6216,
          lockerUserId: phone.substring(phone.length - 6, phone.length),
          keyId: phone.substring(phone.length - 6, phone.length),
          fingerType: 0,
          file: fingerprint1,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName,
          startTime: passwordStartTime,
          endTime: passwordEndTime
        };
        ICINLocker.addFingerPrints(data3.lockerId, data3.imei, data3.lockerUserId, data3.fingerType, data3
          .file, data3.startTime, data3.endTime, data3.cardName, data3.roomName, (callback) => {
            if (callback.success) {
              var data = {
                cardId: this.form.tenant[0].id,
                deviceNum: resultArr.deviceNum,
                imei: resultArr.imei,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: callback.data.serialNumber,
                startTime: startTime,
                endTime: endTime,
                order: 6216
              };
              httpPost(data, this.$api.addCertificates).then((res) => {
                console.log(res)
                // this.getcertificate(); //获取凭证
              });
            } else {
              this.$message.error(callback.msg)
            }
          })
      } else if (row.type == 12) {
        if (row.password.length != 16) {
          this.$message.error("卡格式错误，请重新录入")
          return
        }
        // if(pzname==''){
        // 	pzname='身份证'+sort
        // }
        var str = {
          imei: resultArr.imei,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: row.password,
          operateMode: 13,
          order: 6213,
          type: 2,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: row.pzname,
          is: false,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        var data3 = {
          lockerId: resultArr.deviceNum,
          imei: resultArr.imei,
          lockerUserId: userPassword,
          keyId: userPassword,
          action: 1,
          taskStatus: 1,
          order: 6213,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          cardType: 36,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName,
          cardNo: row.password
        };
        ICINLocker.RfCardRegister(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.taskStatus,
          data3.cardNo, data3.cardType, data3.startTime, data3.endTime, data3.order, data3.cardName, data3.roomName,
          (callback) => {
            if (callback.success) {
              var data = {
                cardId: this.form.tenant[0].id,
                imei: resultArr.imei,
                deviceNum: resultArr.deviceNum,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: callback.data.serialNumber,
                startTime: startTime,
                endTime: endTime,
              };
              httpPost(data, this.$api.addCertificates).then((res) => {
                console.log(res)
                // this.getcertificate(); //获取凭证
              });
            } else {
              this.$message.error(callback.msg)
            }
          })
      } else if (row.type == 13) {
        var password = ""
        if (row.password.length == 8) {
          password = utils.cardFormatConversion(row.password)
          password = password + '00000000'
        } else if (row.password.length == 16) {
          password = row.password
        } else {
          this.$message.error("卡格式错误，请重新录入")
          return
        }
        // if(pzname==''){
        // 	pzname='NFC'+sort
        // }
        var str = {
          imei: resultArr.imei,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: password,
          operateMode: 10,
          type: 3,
          order: 6210,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: row.pzname,
          is: false,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        var data3 = {
          lockerId: resultArr.deviceNum,
          lockerUserId: userPassword,
          keyId: userPassword,
          imei: resultArr.imei,
          action: 1,
          taskStatus: 1,
          order: 6210,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          cardType: 50,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName,
          cardNo: password
        };
        ICINLocker.RfCardRegister(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.taskStatus,
          data3.cardNo, data3.cardType, data3.startTime,
          data3.endTime, data3.order, data3.cardName, data3.roomName, (callback) => {
            if (callback.success) {
              var data = {
                cardId: this.form.tenant[0].id,
                imei: resultArr.imei,
                deviceNum: resultArr.deviceNum,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: callback.data.serialNumber,
                startTime: startTime,
                endTime: endTime,
              };
              httpPost(data, this.$api.addCertificates).then((res) => {
                console.log(res)
                // this.getcertificate(); //获取凭证
              });
            } else {
              this.$message.error(callback.msg)
            }
          })
      } else if (row.type == 14) {
        // if(pzname==''){
        // 	pzname='密码'+sort
        // }
        str = {
          imei: resultArr.imei,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: row.password,
          operateMode: 7,
          order: 6207,
          type: 4,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: row.pzname,
          is: false,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        let data3 = {
          lockerId: resultArr.deviceNum,
          imei: resultArr.imei,
          order: 6207,
          passwordCount: 255,
          lockerUserId: userPassword,
          keyId: userPassword,
          startTime: passwordStartTime,
          endTime: passwordEndTime,
          action: 1,
          password: row.password,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        ICINLocker.addForeverPassword(data3.lockerId, data3.imei, data3.keyId, data3.action, data3.password,
          data3.passwordCount, data3.startTime, data3.endTime, data3.order, data3.cardName, data3
          .roomName, (callback) => {
            console.log(callback)
            if (callback.success) {
              var data = {
                cardId: this.form.tenant[0].id,
                imei: resultArr.imei,
                deviceNum: resultArr.deviceNum,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: callback.data.serialNumber,
                startTime: startTime,
                endTime: endTime
              };
              httpPost(data, this.$api.addCertificates).then((res) => {
                console.log(res)
                // this.getcertificate(); //获取凭证
              });

            } else {
              this.$message.error(callback.msg)
            }
          })

      }
    },
    putCarfidLwj(resultArr, row) {
      var phone = this.form.tenant[0].phone
      var userTelephone = phone.substring(phone.length - 6, phone.length);
      var userPassword = phone.substring(phone.length - 6, phone.length);
      var startTime = new Date(row.passWordStartTime).getTime() / 1000
      var endTime = new Date(row.passWordEndTime).getTime() / 1000
      var passwordStartTime = new Date(row.passWordStartTime).getTime() / 1000
      var passwordEndTime = new Date(row.passWordEndTime).getTime() / 1000
      var pzname = row.pzname || ''
      if (passwordStartTime.length == 13) {
        passwordStartTime = startTime / 1000
      }
      if (passwordEndTime.length == 13) {
        passwordEndTime = endTime / 1000
      }
      if (row.type == 11) {
        var fpId = new Date();
        var fingerprint1 = row.fingerprint;
        var str = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          fingerprintAlias: row.fingerprintAlias,
          userTelephone: userTelephone,
          userPassword: userPassword,
          password: row.password,
          length: fingerprint1.length / 2,
          fpTimeId: fpId.getTime(),
          operateMode: 16,
          type: 1,
          order: 6216,
          fingerprint: fingerprint1,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: (pzname ? pzname : ''),
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        let data = {
          code: "lwj/fpOperate",
          data: {
            lockerId: resultArr.deviceNum,
            lockerUserId: row.userPassword,
            action: 1,
            fpData: fingerprint1,
            startTime: startTime,
            endTime: endTime,
            operateMode: 16,
            order: 6216,
            cardName: row.name + '-' + (pzname ? pzname : ''),
            roomName: resultArr.roomName
          }
        }
        httpPost(data, this.$api.sendCommand).then(res => {
          if (res.success) {
            var data = {
              cardId: this.form.tenant[0].id,
              deviceNum: resultArr.deviceNum,
              imei: resultArr.imei,
              content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
              type: str.type,
              serial: res.data.serialNumber,
              startTime: startTime,
              endTime: endTime,
              order: 6216
            };
            httpPost(data, this.$api.addCertificates).then((res) => {
              console.log(res)
              // this.getcertificate(); //获取凭证
            });
          } else {
            this.$message.error(res.msg)
          }
        })
      } if (row.type == 13) {
        var password = ""
        if (row.password.length == 8) {
          password = utils.cardFormatConversion(row.password)
          password = password + '00000000'
        } else if (row.password.length == 16) {
          password = row.password
        } else {
          this.$message.error("卡格式错误，请重新录入")
          return
        }
        let startTime = new Date(row.passWordStartTime).getTime() / 1000
        let endTime = new Date(row.passWordEndTime).getTime() / 1000
        let data = {
          code: "lwj/cardOperate",
          data: {
            lockerId: resultArr.deviceNum,
            lockerUserId: row.userPassword,
            action: 1,
            cardNo: row.password,
            startTime: startTime,
            endTime: endTime,
            operateMode: 10,
            order: 6210,
            cardName: row.name + '-' + (pzname ? pzname : ''),
            roomName: resultArr.roomName
          }
        }
        let str = {
          imei: resultArr.imei,
          userTelephone: userTelephone,
          cardId: row.cardId,
          userPassword: userPassword,
          password: row.password,
          operateMode: 10,
          order: 6210,
          type: 3,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          pzname: pzname,
          is: false,
          cardName: row.name + '-' + (pzname ? pzname : ''),
          roomName: resultArr.roomName
        };
        httpPost(data, this.$api.sendCommand).then(res => {
          if (res.success) {
            var data = {
              cardId: this.form.tenant[0].id,
              imei: resultArr.imei,
              deviceNum: resultArr.deviceNum,
              content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
              type: str.type,
              serial: res.data.serialNumber,
              startTime: startTime,
              endTime: endTime,
            };
            httpPost(data, this.$api.addCertificates).then((res) => {
              console.log(res)
              // this.getcertificate(); //获取凭证
            });

          } else {
            this.$message.error(callback.msg)
          }
        })

      } else if (row.type == 14) {
        if (row.password == '') {
          this.$message.error('密码不能为空')
        } else {
          let startTime = new Date(row.passWordStartTime).getTime() / 1000
          let endTime = new Date(row.passWordEndTime).getTime() / 1000
          let data = {
            code: "lwj/passwordOperate",
            data: {
              lockerId: resultArr.deviceNum,
              lockerUserId: row.userPassword,
              action: 1,
              password: row.password,
              startTime: startTime,
              endTime: endTime,
              operateMode: 7,
              order: 6207,
              cardName: row.name + '-' + (pzname ? pzname : ''),
              roomName: resultArr.roomName
            }
          }
          let str = {
            imei: resultArr.imei,
            userTelephone: userTelephone,
            cardId: this.form.tenant[0].id,
            userPassword: userPassword,
            password: row.password,
            operateMode: 7,
            order: 6207,
            type: 4,
            passwordStartTime: passwordStartTime,
            passwordEndTime: passwordEndTime,
            pzname: pzname,
            is: false,
            cardName: row.name + '-' + (pzname ? pzname : ''),
            roomName: resultArr.roomName
          };
          httpPost(data, this.$api.sendCommand).then(res => {
            if (res.success) {
              var data = {
                cardId: this.form.tenant[0].id,
                imei: resultArr.imei,
                deviceNum: resultArr.deviceNum,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: res.data.serialNumber,
                startTime: startTime,
                endTime: endTime,
              };
              httpPost(data, this.$api.addCertificates).then((res) => {
                console.log(res)
                // this.getcertificate(); //获取凭证
              });

            } else {
              this.$message.error("123123123", callback.msg)
            }
          })
        }
      }

    },
    // 下发凭证
    putCarfid(resultArr, row) {
      var data = {};
      var phone = this.form.tenant[0].phone
      var userTelephone = phone.substring(phone.length - 6, phone.length);
      var userPassword = phone.substring(phone.length - 6, phone.length);
      var startTime = new Date(row.passWordStartTime).getTime() / 1000
      var endTime = new Date(row.passWordEndTime).getTime() / 1000
      var passwordEndTime = moment(endTime).format("YYYYMMDDHHmmss");
      var passwordStartTime = moment(startTime).format("YYYYMMDDHHmmss");
      // var sort=this.getTypeSort(this.roomtable1,row.type)
      var pzname = row.pzname || ''
      if (row.type == 11) {
        // if(pzname==''){
        // 	pzname='指纹'+sort
        // }
        var fpId = new Date();
        var fingerprint = row.fingerprint;
        // var array = fingerprint.split(",");
        // var num = this.Bytes2Str(array);
        // return
        var str = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          fingerprintAlias: row.fingerprintAlias,
          userTelephone: userTelephone,
          userPassword: userPassword,
          password: row.password,
          length: fingerprint.length / 2,
          fpTimeId: fpId.getTime(),
          operateMode: 16,
          type: 1,
          order: 6216,
          fingerprint: fingerprint,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          cardName: row.name + '-' + pzname,
          roomName: resultArr.roomName,
          pzname: pzname,
          pass: false
        };
        ICINLocker.LDAddFingerPrints(str.deviceNum, str.imei, str.userTelephone, str.userPassword, str
          .password, str.passwordStartTime, str.passwordEndTime, str.operateMode, str.order, str.length,
          str.fpTimeId, str.fingerprint, str.cardName, str.roomName, str.pass, (callback) => {
            if (callback.success) {
              var datafid = {
                deviceNum: resultArr.deviceNum,
                imei: resultArr.imei,
                cardId: this.form.tenant[0].id,
                content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                type: str.type,
                serial: callback.data.serialNumber,
                startTime: startTime / 1000,
                endTime: endTime / 1000,
              };
              httpPost(datafid, this.$api.addCertificates).then((res) => {
                if (res.success) {
                  // this.bindRoomStatus1 = false
                  this.$message.success("下发成功")
                  // this.getcertificate(); //获取凭证
                } else {
                  this.$message.error("下发失败")
                }
              });
            } else {
              this.$message.error(callback.msg)
            }
          })
        return false
      } else if (row.type == 12) {
        // if(pzname==''){
        // 	pzname='身份证'+sort
        // }
        data = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: row.password,
          operateMode: 13,
          order: 6213,
          type: 2,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          is: false,
          cardName: row.name + '-' + pzname,
          roomName: resultArr.roomName,
          pzname: pzname,
        };
      } else if (row.type == 13) {
        // if(pzname==''){
        // 	pzname='NFC'+sort
        // }
        data = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: row.password,
          operateMode: 10,
          order: 6210,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          is: false,
          type: 3,
          cardName: row.name + '-' + pzname,
          roomName: resultArr.roomName,
          pzname: pzname,
        };
      } else if (row.type == 14) {
        // if(pzname==''){
        // 	pzname='密码'+sort
        // }
        data = {
          imei: resultArr.imei,
          deviceNum: resultArr.deviceNum,
          userTelephone: userTelephone,
          cardId: this.form.tenant[0].id,
          userPassword: userPassword,
          password: row.password,
          operateMode: 7,
          order: 6207,
          type: 4,
          passwordStartTime: passwordStartTime,
          passwordEndTime: passwordEndTime,
          is: false,
          cardName: row.name + '-' + pzname,
          roomName: resultArr.roomName,
          pzname: pzname,
          pass: false
        };
      }
      ICINLocker.LDRfCardRegister(data.deviceNum, data.imei, data.userTelephone, data.userPassword, data
        .password, data
        .passwordStartTime, data.passwordEndTime, data.operateMode, data.order, data.cardName, data
        .roomName, data.pass, (
          callback) => {
        if (callback.success) {
          var datafid = {
            deviceNum: resultArr.deviceNum,
            imei: resultArr.imei,
            cardId: this.form.tenant[0].id,
            content: JSON.stringify(data), //operateMode:NFC-10、把人员添加到凭证-1
            type: data.type,
            serial: callback.data.serialNumber,
            startTime: startTime / 1000,
            endTime: endTime / 1000,
          };
          httpPost(datafid, this.$api.addCertificates).then((res) => {
            if (res.success) {
              // this.bindRoomStatus1 = false
              this.$message.success("下发成功")
              // this.getcertificate(); //获取凭证
            } else {
              this.$message.error("下发失败")
            }
          });
        } else {
          this.$message.error(callback.msg)
        }
      })
    },
    // 凭证列表获取
    getcertificate() {
      if (this.form.roomId) {
        var t = {
          roomIds: this.form.roomId,
          lockType: 1
        };
        var data = {
          q: JSON.stringify(t),
        };
        httpPost(data, this.$api.getDeviceItems).then((res) => {
          if (res.success) {
            var data = {
              pageNum: 0,
              pageSize: 0,
              orderBy: "create_at desc",
              q: {
                cardId: this.form.tenant[0].id,
                deviceNum: res.data.list[0].deviceNum,
                imei: this.form.imei,
                status: "0,1,104",
                types: "10,11,12,13,14"
              },
            };
            this.getfilterAcquisition(data)
          } else {
            this.$message.error("获取房间对应门锁信息失败")
          }
        })
      } else {
        var data = {
          pageNum: 0,
          pageSize: 0,
          orderBy: "create_at desc",
          q: {
            cardId: this.form.id,
            deviceNum: this.form.deviceNum,
            imei: this.form.imei,
            // type: this.credentialSearch.type,
            types: "10,11,12,13,14"
          },
        };
        this.getfilterAcquisition(data)
      }
    },
    getfilterAcquisition(data) {
      var dataall = {
        pageNum: 0,
        pageSize: 0,
        orderBy: "create_at desc",
        q: {
          cardId: this.form.tenant[0].id,
          deviceNum: "",
          imei: "",
          status: "",
          types: "0,1,2,3,4"
        },
      }
      httpGet(dataall, this.$api.getCertificates).then((resall) => {
        console.log(resall)
        if (resall.code == 200) {
          var sendOn = utils.zlib_unzip(resall.data)
          var sendstatus = true
          if (resall.data.total == 0) {
            sendstatus = false
          }
          this.voucherlist = sendOn
          this.voucherlist.map(li => {
            li.content = JSON.parse(li.content)
          })
        }
      })
    },
    // 删除凭证
    deletefun1(index, row) {
      var that = this
      this.$confirm("此操作将删除凭证记录，请确认！", "提示", {
        type: "warning",
      }).then(() => {
        let pzid = []
        pzid.push(row.id)
        if (row.type == 11) {
          var pzname = row.content.pzname || ''
          var data6 = {
            pageNum: 1,
            pageSize: 10,
            orderBy: "create_at desc",
            q: JSON.stringify({
              info: {
                pzname: pzname
              },
              cardId: this.form.tenant[0].id,
              inStatus: "0,1,702",
              type: 1
            }),
          };
          httpGet(data6, this.$api.getCertificates).then((res) => {
            let dataOne = utils.zlib_unzip(res.data)
            if (dataOne.length > 0) {
              this.$message.error("请先删除锁上凭证")
            } else {
              var data = {
                ids: pzid,
              };
              httpPost(data, that.$api
                .deleteCertificates).then((
                  res) => {
                  if (res.success) {
                    that.$message.success("删除成功！");
                    that.getcertificate();
                  }
                });
            }
          })
        } else {
          var password = row.content.password
          var data6 = {
            pageNum: 1,
            pageSize: 10,
            orderBy: "create_at desc",
            q: JSON.stringify({
              info: {
                password: password
              },
              cardId: this.form.tenant[0].id,
              inStatus: "0,1,702",
              types: "0,1,2,3,4"
            }),
          };
          httpGet(data6, this.$api.getCertificates).then((res) => {
            let dataOne = utils.zlib_unzip(res.data)
            if (dataOne.length > 0) {
              this.$message.error("请先删除锁上凭证")
            } else {
              var data = {
                ids: pzid,
              };
              httpPost(data, that.$api
                .deleteCertificates).then((
                  res) => {
                  if (res.success) {
                    that.$message.success(
                      "删除成功！");
                    that.getcertificate();
                  }
                });
            }

          })
        }
      })
    },

    Bytes2Str(arrBytes) {
      var str = "";
      for (var i = 0; i < arrBytes.length; i++) {
        var tmp;
        var num = parseInt(arrBytes[i]);
        if (num < 0) {
          //此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
          tmp = (255 + num + 1).toString(16);
        } else {
          tmp = num.toString(16);
        }
        if (tmp.length == 1) {
          tmp = "0" + tmp;
        }
        if (i > 0) {
          str += "" + tmp;
        } else {
          str += tmp;
        }
      }
      return str;
    },

    getTypeSort(data, type) {
      var num = 1
      data.map(li => {
        if (li.type == type) {
          num++
        }
      })
      return num
    },
    // 批量删除
    batchDeleteMethods() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择批量删除合约')
      } else {
        this.$confirm("是否先进行批量删除？", "提示", {
          type: "warning",
        }).then(() => {
          let ids = []
          this.multipleSelection.map(li => {
            ids.push(li.id)
          })
          let list = {
            ids: ids
          }
          httpPost(list, this.$api.postDeleteLeases).then(res => {
            if (res.success) {
              this.$message.success('删除成功')
              this.getLeasesList()
              this.getLeasesStatus()
            } else {
              this.$message.error(res.message)
            }
          })
        })
      }
    },
    // 批量退租
    batchLeaseCancellationMethods() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请选择批量退租合约')
      } else {
        this.$confirm("是否先进行批量退租？", "提示", {
          type: "warning",
        }).then(() => {
          this.rentingMultipleMethods()
        })
      }
    },
    // 退租
    rentOutOperation(index, row) {
      this.multipleSelection = [row]
      this.$confirm("是否先进行退租？", "提示", {
        type: "warning",
      }).then(() => {
        this.rentingMultipleMethods()
      })
    },
    // 退租方法
    rentingMultipleMethods() {
      let _this = this
      this.multipleSelection.map(li => {
        this.getRoomIdDeviceInfo(li.siteId).then(res => {
          console.log(res, res.data.total);
          if (res.data.total > 0) {
            if (res.data.list[0].manufactureId === 201 || res.data.list[0].manufactureId === 221) {
              RequestSet.unbindPeopleAndRooms(li.cardId, res.data.list[0].imei, (callback) => {
                console.log(callback);
                if (callback.success) {
                  let dataOne = utils.zlib_unzip(callback.data)
                  console.log(dataOne);
                  if (dataOne.length > 0) {
                    let lookUserInfo = JSON.parse(dataOne[0].content)
                    console.log(lookUserInfo);
                    let dataLook = {
                      lockerId: dataOne[0].deviceNum,
                      imei: dataOne[0].imei,
                      lockerUserId: lookUserInfo.lockerUserId,
                      keyId: lookUserInfo.keyId,
                      role: 0,
                      action: 2, //1--添加、2--删除、3--修改
                      order: 6203,
                      cardName: lookUserInfo.cardName,
                      roomName: lookUserInfo.roomName
                    }
                    httpPost(dataLook, _this.$api.ZGduserOperation).then(res2 => {
                      console.log(dataLook, res2);
                      if (res2.success) {
                        let dataUnbind = [{
                          siteId: li.siteId,
                          cardId: li.cardId,
                        }]
                        httpPost(dataUnbind, _this.$api.unbindCard).then((res) => {
                          console.log(res);
                          _this.$message.success("退租成功")
                          let refundLeasesData = [
                            {
                              id: li.id,
                              status: 3
                            }
                          ]
                          httpPost(refundLeasesData, _this.$api.postUpdateLeases).then(res => {
                            console.log(res);
                          })
                          _this.getLeasesList()
                          _this.getLeasesStatus()
                        })
                      } else {
                        _this.$message.error(res2.msg)
                      }
                    })
                  }
                } else {
                  _this.$message.error(callback.msg)
                }
              })
            } else if (res.data.list[0].manufactureId === 101) {
              RequestSet.unbindPeopleAndRooms(li.cardId, res.data.list[0].imei, (callback) => {
                if (callback.success) {
                  let dataOne = utils.zlib_unzip(callback.data)
                  let lookUserInfo = JSON.parse(dataOne[0].content)
                  let str = {
                    imei: dataOne[0].imei,
                    deviceNum: dataOne[0].deviceNum,
                    userTelephone: lookUserInfo.userTelephone,
                    userPassword: lookUserInfo.userPassword,
                    operateMode: 3,
                    order: 6203,
                    password: "20210816",
                    cardName: lookUserInfo.cardName,
                    roomName: lookUserInfo.roomName,
                    is: false,
                  };
                  httpPost(str, _this.$api.getDeviceOperateUserInfo).then(
                    (res1) => {
                      if (res1.success) {
                        let dataUnbind = [{
                          siteId: li.siteId,
                          cardId: li.cardId,
                        }]
                        httpPost(dataUnbind, _this.$api.unbindCard).then((res) => {
                          _this.$message.success("退租成功")
                          let refundLeasesData = [
                            {
                              id: li.id,
                              status: 3
                            }
                          ]
                          httpPost(refundLeasesData, _this.$api.postUpdateLeases).then(res => { })
                          _this.getLeasesList()
                          _this.getLeasesStatus()
                        })
                      } else {
                        _this.$message.error(res1.msg)
                      }
                    })
                } else {
                  _this.$message.error(callback.msg)
                }
              })
            }
          } else {
            this.$notify({
              title: '警告',
              message: `该合约房间（${li.address}）没有找到对应房间信息`,
              duration: 0,
              type: 'warning'
            })
            return false;
          }
        })

      })
    },
    // 根据房间id获取设备信息
    getRoomIdDeviceInfo(roomId) {
      let _this = this
      return new Promise(function (resolve, reject) {
        let q = {
          roomIds: [roomId]
        }
        let data = {
          q: JSON.stringify(q),
          pageNum: 1,
          pageSize: 1,
        };
        httpPost(data, _this.$api.getDeviceItems).then((res) => {
          resolve(res)
        })
      })
    },
    // 多选
    handleSelectionChange(value) {
      this.multipleSelection = value;
    },
    // 关闭签约弹窗
    handleClose() {
      this.dialogVisible = false
    },
    handleCloseExport() {
      this.dialogVisibleExport = false
    },
    // 重置搜索
    restSearch() {
      this.search = {
        name: '',
        phone: '',
        status: '',
        signingTime: '',
        contractTime: '',
        siteIds: ''
      }
    },
    // 搜索
    handleSearch() {
      this.getLeasesList()
    },
    // 设置每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.getLeasesList()
    },
    // 跳转页码
    handleCurrentChange(val) {
      this.pageNum = val
      this.getLeasesList()
    }
  }
}
</script>

<style scoped>
.width50 {
  width: 50px;
}

.width120 {
  width: 120px;
}

.width200 {
  width: 200px;
}

.width150 {
  width: 150px;
}

.mr10 {
  margin-right: 10px;
}

.container .el-button+.el-button,
.container .el-checkbox.is-bordered+.el-checkbox.is-bordered {
  margin-left: 0;
}

.widthRem5 {
  /* display: inline-block; */
  width: 5rem;
}
</style>
