<template>
  <div class="app-container">
    <el-row type="flex" justify="space-between" ref="listQueryContainer" class="query-container">
      <el-col>
        <el-form :inline="true" style="flex-wrap: wrap" :model="listQuery" ref="listQuery" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label="编号" prop="number">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model.trim="listQuery.number" maxlength="16" placeholder="请输入编号，年+4位编号" clearable @clear="listQuery.number=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="访客姓名" prop="username">
            <el-input v-model.trim="listQuery.username" maxlength="16" placeholder="请输入访客姓名" clearable @clear="listQuery.username=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="访客手机号" prop="userPhone">
            <el-input v-model.trim="listQuery.userPhone" maxlength="16" placeholder="请输入访客手机号" clearable @clear="listQuery.userPhone=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="访客公司" prop="company">
            <el-input v-model.trim="listQuery.company" maxlength="16" placeholder="请输入访客公司" clearable @clear="listQuery.company=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="是否高风险" prop="highRisk">
            <el-select v-model="listQuery.highRisk" placeholder="请选择" clearable @clear="listQuery.highRisk=undefined" @change="onFilterChange">
              <el-option key="是" label="是" value="true"></el-option>
              <el-option key="否" label="否" value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="listQuery.status" placeholder="请选择" clearable @clear="listQuery.highRisk=undefined" @change="onFilterChange">
              <el-option :key="status.value" :label="status.label" :value="status.value" v-for="status in auditList"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="进入时间范围" prop="entryTimeRange">
            <el-date-picker
                v-model="listQuery.entryTimeRange"
                value-format="timestamp"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="离开时间范围" prop="leaveTimeRange">
            <el-date-picker
                v-model="listQuery.leaveTimeRange"
                value-format="timestamp"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>

          <el-form-item label-width="0">
            <el-button @click="onFilterChange" type="primary">查询</el-button>
            <el-button @click="resetFields" plain type="primary">重置</el-button>
            <el-button @click="onExport" plain type="primary">导出</el-button>
            <el-button @click="showQrCodeIn" type="primary" style="margin-left: 20px;">进入登记二维码</el-button>
            <el-button @click="showQrCodeOut" type="primary">出场核销二维码</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @clear="resetFields" @change="onExpansion"/>
    </el-row>

    <el-table :data="list" border stripe highlight-current-row ref="table" class="mt10" @sort-change="onSortChange" @selection-change="onTableSelectionChange" @row-click="onRowClick">
      <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
      <el-table-column prop="number" label="编号" sortable="custom" align="center" min-width="100px"/>
      <el-table-column prop="username" label="访客姓名" sortable="custom" align="center" min-width="102px"/>
      <el-table-column prop="userPhone" label="访客手机号" sortable="custom" align="center" min-width="116px"/>
      <el-table-column prop="company" label="访客公司" sortable="custom" align="center" min-width="102px"/>
      <el-table-column prop="duration" label="访问时长（小时）" align="center" min-width="96px"/>
      <el-table-column prop="itineraryCode" label="行程码" align="center" min-width="80px">
        <template v-slot="scope">
          <template v-if="scope.row.itineraryCode">
            <el-image style="height: 40px;" :src="scope.row.itineraryCode" contain :preview-src-list="[scope.row.itineraryCode]"></el-image>
          </template>
          <template v-else>未上传</template>
        </template>
      </el-table-column>
      <el-table-column prop="healthCode" label="健康码" align="center" min-width="80px">
        <template v-slot="scope">
          <template v-if="scope.row.healthCode">
            <el-image style="height: 40px;" :src="scope.row.healthCode" contain :preview-src-list="[scope.row.healthCode]"></el-image>
          </template>
          <template v-else>未上传</template>
        </template>
      </el-table-column>
      <el-table-column prop="highRisk" label="是否高风险" align="center" min-width="110px">
        <template v-slot="scope">
          <text-label v-if="scope.row.highRisk" type="danger">是</text-label>
          <text-label v-else type="success">否</text-label>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="事由" align="center" min-width="100px"/>
      <el-table-column prop="information" label="审核资料" align="center" min-width="160px">
        <template v-slot="scope">
          <template v-if="scope.row.information">
            <el-image style="height: 40px; margin: 0 3px" :src="info" contain :preview-src-list="scope.row.information.split(',')" v-for="info in scope.row.information.split(',')" :key="info"></el-image>
          </template>
          <template v-else>未上传</template>
        </template>
      </el-table-column>
      <el-table-column prop="operatingUsername" label="操作用户姓名" sortable="custom" align="center" min-width="130px"/>
      <el-table-column prop="remark" label="出场备注" align="center" min-width="102px"/>

      <el-table-column prop="entryTime" label="进入时间" sortable="custom" align="center" width="160px">
        <template v-slot="scope">{{ scope.row.entryTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column prop="leaveTime" label="离开时间" sortable="custom" align="center" width="160px">
        <template v-slot="scope">{{ scope.row.leaveTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column prop="entryTime" label="申请时间" sortable="custom" align="center" width="160px">
        <template v-slot="scope">{{ scope.row.createTime | dateFormat }}</template>
      </el-table-column>
      <el-table-column prop="backupValid" label="是否备案" align="center" width="78px" fixed="right">
        <template v-slot="scope">
          <text-label v-if="scope.row.backupId && scope.row.backupValid" type="success">已备案</text-label>
          <text-label v-else-if="scope.row.backupId" type="warning">已过期</text-label>
          <text-label v-else type="danger">未备案</text-label>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审核状态" align="center" min-width="78px" fixed="right">
        <template v-slot="scope">
          <text-label v-if="scope.row.status === 1">{{ auditList.find(item => item.value === scope.row.status).label }}</text-label>
          <text-label v-else-if="scope.row.status === 2" type="success">{{ auditList.find(audit => audit.value === scope.row.status).label }}</text-label>
          <text-label v-else-if="scope.row.status === 3" type="danger">{{ auditList.find(audit => audit.value === scope.row.status).label }}</text-label>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="150px" fixed="right">
        <template v-slot="scope">
          <el-link type="primary" icon="el-icon-check" :disabled="scope.row.status!==1" @click="onAudit(scope.row, 2)">通过</el-link>
          <el-link type="primary" icon="el-icon-close" :disabled="scope.row.status!==1" @click="onAudit(scope.row, 3)" class="ml20">拒绝</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :size.sync="listQuery.size" @change="onPageChange"/>

    <el-dialog title="导出" :visible.sync="exportVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
      <el-progress :text-inside="true" :stroke-width="24" :percentage="exportProgress" status="success"></el-progress>
      <el-button slot="footer" @click="onCancelExport">取 消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {downloadImage} from "@/utils/httpUtil";
import {dateFormat} from "@/utils/dateUtil"

export default {
  name: "VisitorAudit",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        number: undefined, // 编号
        username: undefined, // 访客姓名
        userPhone: undefined, // 访客手机号
        company: undefined, // 访客公司
        highRisk: undefined, // 是否高风险
        status: undefined, // 审核状态
        entryTimeRange: [], // 审批、进入时间
        entryTimeStart: undefined,
        entryTimeEnd: undefined,
        leaveTimeRange: [], // 离开时间
        leaveTimeStart: undefined,
        leaveTimeEnd: undefined,
        order: undefined,
        page: 1,
        size: 10
      },
      auditList: [{value: 1, label: '未审核'}, {value: 2, label: '通过'}, {value: 3, label: '拒绝'}],

      list: [], // 结果列表
      total: 0, // 总结果数量

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出

      editing: false, // 表格编辑中

      selectItem: undefined, // 选中的单条记录
      selectIds: undefined, // 选中多条记录的id
    }
  },

  watch: {
    'listQuery.entryTimeRange'(value) {
      if (value) {
        this.listQuery.entryTimeStart = value[0];
        this.listQuery.entryTimeEnd = value[1];
      } else {
        this.listQuery.entryTimeStart = undefined;
        this.listQuery.entryTimeEnd = undefined;
      }
    },
    'listQuery.leaveTimeRange'(value) {
      if (value) {
        this.listQuery.leaveTimeStart = value[0];
        this.listQuery.leaveTimeEnd = value[1];
      } else {
        this.listQuery.leaveTimeStart = undefined;
        this.listQuery.leaveTimeEnd = undefined;
      }
    },
    'listQuery.createTimeRange'(value) {
      if (value) {
        this.listQuery.createTimeStart = value[0];
        this.listQuery.createTimeEnd = value[1];
      } else {
        this.listQuery.createTimeStart = undefined;
        this.listQuery.createTimeEnd = undefined;
      }
    },
  },

  // 页面创建
  created() {
    this.initData();
    this.initEvent();
  },

  // 页面挂载
  mounted() {
    this.initView();
    this.initQuery();
    this.getList();
  },

  // keep-alive 显示界面时调用
  activated() {
    this.$refs["table"].doLayout();
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 初始化数据
    initData() {
    },

    // 初始化事件
    initEvent() {
    },

    // 初始化查询条件
    initQuery() {
      if (this.$store.state.app.paramCache) {
        let query = this.$storage.getData(this.$options.name);
        if (Object.keys(query).length > 0) {
          this.listQuery = query;
          if (query.order) {
            this.$refs.table.sort(query.order.substring(1), query.order.substring(0, 1) === "+" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化视图
    initView() {
      this.$nextTick(() => {
        this.shrinkable = this.$store.state.app.filterShrink && this.$refs['listQuery'].$el.offsetHeight > 51;
      })
    },

    // 展开/收起查询条件
    onExpansion(show) {
      this.$refs['listQueryContainer'].$el.style.height = show ? "auto" : "51px";
    },

    // 表格索引
    indexCompute(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.size;
    },

    // 表单提交
    onSubmit() {
      this.onFilterChange();
    },

    // 表单清除
    resetFields() {
      this.$refs['listQuery'].resetFields();
      this.listQuery.order = undefined;
      this.$refs.table.clearSort();
      this.onFilterChange();
    },

    // 审核
    onAudit(item, status) {
      this.$axios.put("/v1/visitor/audit/update", {id: item.id, status: status}).then(() => {
        this.getList();
        this.$message.success("审批成功");
      });
    },

    // 数据选择
    onTableSelectionChange(val) {
      this.selectIds = val.map(item => item.id);
    },

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.order = "+" + prop;
      } else if (order === "descending") {
        this.listQuery.order = "-" + prop;
      } else {
        this.listQuery.order = undefined;
      }
      this.onFilterChange();
    },

    // 行点击
    onRowClick(row, column, event) {
      this.$refs["table"].setCurrentRow(row);
      if (this.editing) {
        this.$refs["table"].toggleRowSelection(row);
      }
    },

    // 条件改变
    onFilterChange() {
      this.listQuery.page = 1;
      this.$nextTick(this.getList);
    },

    // 页码改变
    onPageChange() {
      this.getList();
    },

    // 加载列表
    getList() {
      // 缓存参数
      if (this.$store.state.app.paramCache) {
        this.$storage.setData(this.$options.name, this.listQuery);
      }

      this.$axios.get("/v1/visitor/audit/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.total;
        this.$refs["table"].doLayout();
      });
    },

    // 进入登记二维码
    showQrCodeIn() {
      let url = encodeURIComponent(`https://www.zwywpt.top/visited/pages/writeoff/register/register`)
      let qrUrl = `https://yun.huaxiyou.cc/internal.qcode.stream?dstUrl=${url}`;
      this.$alert(`<img src="${qrUrl}" style="width:100%; height:100%">`, `进入登记二维码`, {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '下载',
            callback: action => {
              if (action === 'confirm') {
                downloadImage(qrUrl, '进入登记二维码')
              }
            }
          }
      );
    },

    // 出场核销二维码
    showQrCodeOut() {
      let url = encodeURIComponent(`https://www.zwywpt.top/register/pages/writeoff/exitwritoff/exitwritoff`)
      let qrUrl = `https://yun.huaxiyou.cc/internal.qcode.stream?dstUrl=${url}`;
      this.$alert(`<img src="${qrUrl}" style="width:100%; height:100%">`, `出场核销二维码`, {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '下载',
        callback: action => {
          if (action === 'confirm') {
            downloadImage(qrUrl, '出场核销二维码')
          }
        }
      });
    },

    // 导出数据
    onExport() {
      if (this.total > 0) {
        this.exportPagination.page = 1;
        this.exportData = [];
        this.exportVisible = true;
        this.getExportData();
      }
    },

    // 取消导出
    onCancelExport() {
      this.exportVisible = false;
      this.exportCancel = true;
    },

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/v1/visitor/audit/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportPagination.page++;
          this.exportData = this.exportData.concat(data.list);
          this.exportProgress = Math.round(this.exportData.length * 100 / this.total);
          if (this.exportData.length < this.total && data.list.length > 0) {
            this.getExportData();
          } else {
            this.exportVisible = false;

            let tHeader = ["序号",
              "编号",
              "访客姓名",
              "访客手机号",
              "访客公司",
              "访问时长",
              "行程码",
              "健康码",
              "是否高风险",
              "事由",
              "审核资料",
              "操作用户姓名",
              "出场备注",
              "审批、进入时间",
              "离开时间",
              "申请时间",
              "是否备案",

              "审核状态",
            ];
            let filterVal = ["index",
              "number",
              "username",
              "userPhone",
              "company",
              "duration",
              "itineraryCode",
              "healthCode",
              "highRisk",
              "reason",
              "information",
              "operatingUsername",
              "remark",
              "entryTime",
              "leaveTime",
              "createTime",
              "backupValid",
              "status",
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "entryTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "leaveTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "createTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "status") {
                return this.auditList.find(audit => audit.value === value[key]).label;
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '访客审批', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {

}
</style>
