<script>
import {dispatchList} from '@/api/pda';
import {getExpressRecordParams} from '@/api/prescription/prescriptionAudit';
import {sf_express_print} from '@/tools/print.tool';
import dayjs from 'dayjs';

let TAG;

export default {
  name: 'ScanPanel',
  data() {
    return {
      loading: false,
      keyword: '',
      logs: [],
    };
  },
  methods: {
    async open() {
      this.nonsupport();
    },
    async close() {
      if (TAG) window.cancelAnimationFrame(TAG);
      this.logs = [];
      this.loading = false;
    },
    async search() {
      if (this.loading) return;
      this.loading = true;
      const keyword = this.keyword.trim();
      try {

        let result = await dispatchList({pageNum: 1, pageSize: 1, orderNo: keyword});
        if (result.code !== 200) throw {message: result.msg};

        let data = result.rows[0];
        if (!data) throw {message: `未查询到数据`};
        if (data.expressExecutor !== '顺丰') throw {message: `无法打印，配送方式不是顺丰`};

        result = await getExpressRecordParams({prescriptionCoreId: data.id});
        if (result.code !== 200) throw {message: result.msg};

        data = result.data;
        await sf_express_print(data);
        this.$message.success(`发送打印任务成功`);
        this.logs.push({
          time: dayjs().format('HH:mm:ss'),
          state: 'success', keyword,
          icon: 'el-icon-check', color: 'green',
          message: `发送打印任务成功`,
        });
      } catch (error) {
        this.$message.error(error.message);
        this.logs.push({
          time: dayjs().format('HH:mm:ss'),
          state: 'danger', keyword,
          icon: 'el-icon-close', color: 'red',
          message: error.message,
        });
      }
      this.$refs.input.focus();
      this.$refs.main.scrollTop = 0;
      this.keyword = '';
      this.loading = false;
    },


    nonsupport() {
      if (TAG) window.cancelAnimationFrame(TAG);
      TAG = window.requestAnimationFrame(() => {
        this.$refs.input.focus();
        this.nonsupport();
      });
    },
  },
};
</script>

<template>
  <div class="wrapper">
    <div class="header">
      <el-input ref="input" style="width: 80%;" v-model="keyword" placeholder="请输入或使用扫码枪操作" clearable
                size="small" :disabled="loading"
                @keyup.enter.native="search"/>
    </div>
    <div class="main" ref="main">
      <el-timeline reverse>
        <el-timeline-item
          v-for="(log, index) in logs"
          :key="index"
          :icon="log.icon"
          :color="log.color"
          size="large" :type="log.state"
          :timestamp="log.time" placement="top">
          [{{ log.keyword }}] {{ log.message }}
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<style scoped lang="scss">
.wrapper {
  display: flex;
  flex-direction: column;
  height: 60vmin;
}

.header {
  flex: none;
  text-align: center;
}

.main {
  flex: auto;
  padding-top: 24px;
  overflow-y: auto;
}
</style>
