<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%;">
            <h1 style="margin-bottom: 10px;font-size: 30px;display: flex;justify-content: center;align-items: center;">
              油机非当天动态密钥生成</h1>
          </div>
          <div v-if="state.msgDisplay" style="width: 100%;">
            <h1 style="margin-bottom: 10px;color: #81B337;font-size: 20px;">密码申请成功</h1>
          </div>
          <div style="width: 100%;margin-top:20px">
            <el-form :inline="true" @submit.stop.prevent style="width: 60%;">
              <el-form-item label="申请备注" style="width: 40%;">
                <el-input v-model="state.filter.info" style="width: 100%;" placeholder="请输入申请备注"
                  @keyup.enter="onQuery" />
              </el-form-item>
              <el-form-item label="密钥使用日期" style="width: 45%;">
                <el-date-picker 
                  v-model="state.filter.useDate" 
                  type="date" 
                  style="width: 100%;" 
                  placeholder="请选择日期" 
                  value-format="yyyy/MM/DD" 
                />             
               </el-form-item>
            </el-form>
          </div>
          <div v-if="state.pwdDisplay" style="width: 100%;">
            <el-form :inline="true" @submit.stop.prevent style="width: 60%;">
              <el-form-item label="FTP密码" style="width: 82%;">
                <el-input disabled v-model="state.pwd" style="width: 100%;" placeholder="FTP密码"
                  @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>
          <div v-if="state.timeDisplay" style="width: 100%;">
            <el-form :inline="true" @submit.stop.prevent style="width: 60%;">
              <el-form-item label="过期时间" style="width: 100%;">
                {{ state.filter.expirationTime }}
              </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: 10px;margin-bottom: 10px;width: 264px;height: 42px;" type="primary"
                  @click="onQuery">申请油机FTP密码</el-button>
              </div>
            </el-row>
          </el-row>
        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24">
        <el-card 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="pageState.pageInput.currentPage"
              v-model:page-size="pageState.pageInput.pageSize" :total="state.total" :page-sizes="[10, 15, 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 { FuelingFtpAPI } from '/@/api/admin/deviceAuthorization/fuelingFTPApi'
import { FuelFtpPswRecordDto } from '/@/api/admin/deviceAuthorization/fuelingFTPDto'
import Clipboard from 'clipboard'
import type { pageInput } from "/@/api/admin/shareDto/shareDto";
import { AuthApi } from '/@/api/admin/Auth'
import { useDynamicPageSize } from "/@/composables/useDynamicPageSize";

// 使用组合式函数获取分页状态
const pageState = useDynamicPageSize(10, 15);

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
/**FTP申请页面对象 */
const state = reactive({
  time: '',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  filter: {
    /**申请备注 */
    info: "",
    /**过期时间 */
    expirationTime: '',
    /**使用日期*/
    useDate: '',
    /**申请日期*/
    applyDate: '',
    /**申请人*/
    name: ''
  },
  /**分页标识 */
  pageInput: {
    CurrentPage: 1,
    PageSize: 10,
  } as pageInput,
  /**分页总数 */
  total: 0,
  /**表格信息 */
  tableModel: [] as FuelFtpPswRecordDto,
  /**动态表头 */
  dynamicColumns: [
    { prop: 'applyDate', label: '申请日期' },
    { prop: 'name', label: '申请人' },
    { prop: 'info', label: '备注' },
    { prop: 'useDate', label: '密钥使用日期' },
    { prop: 'expirationTime', label: '密钥过期时间' }
  ],
  /**FTP密码 */
  pwd: "",
  pwdDisplay: false,
  timeDisplay: false,
  btnDisplay: true,
  msgDisplay: false
})

/**初始化 */
const init = async () => {
  state.filter.info = ''
  state.filter.name = ''
  state.filter.applyDate = ''
  state.filter.expirationTime = ''
  state.filter.useDate = ''
  state.pwd = ''
  state.btnDisplay = true
  state.msgDisplay = false
  state.pwdDisplay = false
  state.timeDisplay = false
  const res: any = await new FuelingFtpAPI().getFtpDate({ ...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(() => {
  // 初始化分页大小
state.pageInput.PageSize = pageState.pageInput.pageSize;
  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.useDate === '') {
    ElMessage.error('请选择密钥使用日期')
  }
  else if (state.filter.info === '') {
    ElMessage.error('请输入申请备注')
  }
  else {
    const res = await new FuelingFtpAPI().getFtpPwdofDate({ dt: state.filter.useDate }).catch()
    state.pwd = res.data
    state.msgDisplay = true
    state.pwdDisplay = true
    state.timeDisplay = 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
    state.filter.expirationTime = state.filter.useDate + ' 23:59:59'
    const name: any = await new AuthApi().getUserProfile()
    state.filter.name = name.data.name
    await new FuelingFtpAPI().insertFtpDate(state.filter)
    const data: any = await new FuelingFtpAPI().getFtpDate({ ...state.pageInput, filter: state.filter }).catch(() => {
      state.loading = false
    })
    state.total = data.data.total
    state.tableModel = data.data.list
  }
}
/**将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>