<template>
  <div class="layout-pd">
    <el-row>
      <!--操作-->
      <el-col :xs="24">
        <el-card class="mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <div style="width: 100%;display: flex;justify-content: center;align-items: center;">
            <h1 style="margin-bottom: 10px;font-size: 30px;">油机授权码申请</h1>
          </div>
          <div v-if="state.msgDisplay" style="width: 100%;display: flex;justify-content: center;align-items: center;">
            <h1 style="margin-bottom: 10px;color: #81B337;font-size: 20px;">授权码申请成功</h1>
          </div>
          <div style="width: 100%;">
            <el-form :inline="true" @submit.stop.prevent style="width: 30%;display: inline-block;">
              <el-form-item label="油站名称" style="width: 100%;">
                <el-input v-model="state.filter.station" style="width: 100%;" placeholder="请输入油站名称"
                  @keyup.enter="onQuery" />
              </el-form-item>
            </el-form>
            <el-form :inline="true" @submit.stop.prevent style="width: 30%;display: inline-block;margin-left:20vh">
              <el-form-item label="油机id" style="width: 100%;">
                <el-input v-model="state.filter.dispenserID" style="width: 100%;" placeholder="请输入油机id"
                  @keyup.enter="onQuery" />
              </el-form-item>
            </el-form>
          </div>

          <div v-if="state.pwdDisplay" style="width: 100%;">
            <el-form :inline="true" @submit.stop.prevent style="width: 20%;">
              <el-form-item label="油机授权码" style="width: 82%;">
                <el-input disabled v-model="state.pwd" style="width: 100%;" placeholder="油机授权码"
                  @keyup.enter="onQuery" />
              </el-form-item>
              <el-form-item>
                <el-button id="copyBtn" :data-clipboard-text="state.pwd" type="primary" @click="onCopy()">复制</el-button>
              </el-form-item>
            </el-form>
          </div>

          <hr>

          <!-- 按钮  -->
          <el-row justify="space-between" class="submit-button">
            <el-row>
            </el-row>
            <el-row>
              <div v-if="state.btnDisplay" style="display: flex;justify-content: center;align-items: center;">
                <el-button style="margin-top: 0px;margin-bottom: 10px;width: 264px;height: 42px;" type="primary"
                  @click="onQuery">申请油机授权码</el-button>
              </div>
            </el-row>
          </el-row>


        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24">
        <el-card style="height: 50vh" class="my-fill mt8" shadow="hover">
          <el-table ref="multipleTableRef" v-loading="state.loading" stripe :data="state.tableModel" row-key="id"
            style="width: 100%">
            <el-table-column type="index" label="记录" width="60" />
            <el-table-column v-for="column in state.dynamicColumns" :key="column.prop" :prop="column.prop"
              :label="column.label" />
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination v-model:currentPage="state.pageInput.CurrentPage"
              v-model:page-size="state.pageInput.PageSize" :total="state.total" :page-sizes="[10, 20, 50, 100]" small
              background @size-change="onSizeChange" @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

</template>

<script setup lang="ts" name="authorize/fuelingsdk">
import { onMounted, reactive, ref, watch, onBeforeMount } from "vue";
import eventBus from "/@/utils/mitt";
import { ElMessage, ElTable } from 'element-plus'
import { DispenserAuthCodeApi } from '/@/api/admin/deviceAuthorization/dispenserAuthCodeApi'
import { FuelAuthCodeRecordDto } from '/@/api/admin/deviceAuthorization/dispenserAuthCodeDto'
import Clipboard from 'clipboard'
import type { pageInput } from "/@/api/admin/shareDto/shareDto";
import { AuthApi } from '/@/api/admin/Auth'

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
/**FTP申请页面对象 */
const state = reactive({
  time: '',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  filter: {
    /**油站名称 */
    station: '',
    /**申请日期*/
    applyDate: '',
    /**油机id */
    dispenserID: '',
    /**申请人*/
    name: '',
    /**授权码类型*/
    type: ''
  },
  /**分页标识 */
  pageInput: {
    CurrentPage: 1,
    PageSize: 10,
  } as pageInput,
  /**分页总数 */
  total: 0,
  /**表格信息 */
  tableModel: [] as FuelAuthCodeRecordDto,
  /**动态表头 */
  dynamicColumns: [
    { prop: 'applyDate', label: '申请日期' },
    { prop: 'station', label: '油站名称' },
    { prop: 'dispenserID', label: '油机id' },
    { prop: 'name', label: '申请人' },
    { prop: 'type', label: '授权类型' }
  ],
  /**授权码 */
  pwd: "",
  pwdDisplay: false,
  btnDisplay: true,
  msgDisplay: false
})

/**初始化 */
const init = async () => {
  state.filter.applyDate = ''
  state.filter.station = ''
  state.filter.dispenserID = ''
  state.filter.name = ''
  state.filter.type = ''
  state.pwd = ''
  state.btnDisplay = true
  state.msgDisplay = false
  state.pwdDisplay = false
  const res: any = await new DispenserAuthCodeApi().getDispenserAuthCodeRecord({ ...state.pageInput, filter: state.filter }).catch(() => {
    state.loading = false


  })
  //console.log(res.data.list)
  state.total = res.data.total
  state.tableModel = res.data.list
}

onMounted(() => {
  init()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    init()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshView')
})

/**
 * 监听时间变换

  watch(() => state.time, (newVal ) => {
    if(newVal.length === 0){
      return
    }
    state.filter.expirationTime = newVal?.[0].toString()
  })
 */


/**复制FTP密码 */
const onCopy = () => {
  const clipboard = new Clipboard('#copyBtn')
  clipboard.on('success', () => {
    ElMessage.success('复制成功')
    clipboard.destroy()
  })
  clipboard.on('error', () => {
    ElMessage.error('复制失败')
    clipboard.destroy()
  })
}
/**申请FTP密码 */
const onQuery = async () => {
  if (state.filter.station == '' || state.filter.dispenserID == '') {
    ElMessage.error('请输入油站名称和油机id')
  } else {

    const res = await new DispenserAuthCodeApi().getDispenserAuthCode({ dispenserID: state.filter.dispenserID }).catch()

    if (res.data.result == true) {
      state.pwd = res.data.authcode
      state.msgDisplay = true
      state.pwdDisplay = true
      state.btnDisplay = false
      const date = new Date()
      let month = padZero(date.getMonth() + 1)
      let day = padZero(date.getDate())
      let hour = padZero(date.getHours())
      let minute = padZero(date.getMinutes())
      let second = padZero(date.getSeconds())
      state.filter.applyDate = date.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      const name: any = await new AuthApi().getUserProfile()
      state.filter.name = name.data.name

      var buf = state.filter.dispenserID;
      var funthousand, funhundred, fundecade, funbit, funcode;
      funthousand = (buf.charCodeAt(16 - 4) - 0x30 - 0x11) * 1000;
      funhundred = (buf.charCodeAt(16 - 3) - 0x30 - 0x11) * 100;
      fundecade = (buf.charCodeAt(16 - 2) - 0x30 - 0x11) * 10;
      funbit = (buf.charCodeAt(16 - 1) - 0x30 - 0x11) * 1;
      funcode = funthousand + funhundred + fundecade + funbit;

      /*
            const buf = Buffer.from(state.filter.dispenserID, 'ascii');
      
       
      
            ElMessage.error(buf[0].toString())
      
            for (let i = 0; i < 16; i++)
            {
              buf[i]=  (buf[i] - 0x11);
            }
      
            ElMessage.error(buf.toString());
            //ElMessage.error(strb)
      
            var funthousand, funhundred, fundecade, funbit, funcode;
            funthousand = (buf[16 - 4] - 0x30) * 1000;
            funhundred = (buf[16 - 3] - 0x30) * 100;
            fundecade = (buf[16 - 2] - 0x30) * 10;
            funbit = (buf[16 - 1] - 0x30) * 1;
            funcode = funthousand + funhundred + fundecade + funbit;
      
            ElMessage.error(funcode.toString());
      */
      state.filter.type = funcode.toString();

      await new DispenserAuthCodeApi().InsertDispenserAuthCode(state.filter)
      const data: any = await new DispenserAuthCodeApi().getDispenserAuthCodeRecord({ ...state.pageInput, filter: state.filter }).catch(() => {
        state.loading = false
      })
      state.total = data.data.total
      state.tableModel = data.data.list
    }
    else {
      ElMessage.error(res.data.message)
    }

  }
}


/**将Filter对象成.的连接方式
const flattenObject = (obj, parentKey = '') => {
  const result = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const newKey = parentKey ? `${parentKey}.${key}` : key;
      if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
        const flattened = flattenObject(obj[key], newKey);
        Object.assign(result, flattened);
      } else {
        result[newKey] = obj[key];
      }
    }
  }

  return result;
}*/


/**页条数变化*/
const onSizeChange = () => {
  init()
}

/**页数变化*/
const onCurrentChange = () => {
  init()
}
const padZero = (num: any) => {
  return num < 10 ? '0' + num : num
}
</script>

<style scoped lang="scss">
.my-el-link {
  font-size: 12px;
}

.el-form .el-col.mb20 {
  margin: 0 !important;
}

.el-input,
.el-select {
  width: 240px;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
  // 字体大小14，4个字符，12px右间距
  width: 14*4px+12px;
  justify-content: start;
}

/* 数据表头 设置灰色样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #F6F6F6;
}
</style>
