<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%;display: flex;justify-content: center;align-items: center;">
            <el-form :inline="true" @submit.stop.prevent style="width: 60%;">
              <el-form-item label="申请备注" style="width: 100%;">
                <el-input v-model="state.filter.info" style="width: 100%;" placeholder="请输入申请备注" @keyup.enter="onQuery" />
              </el-form-item>
            </el-form>
          </div>
          <div v-if="state.pwdDisplay" style="width: 100%;display: flex;justify-content: center;align-items: center;">
            <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%;display: flex;justify-content: center;align-items: center;">
            <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>
          <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-card>
      </el-col>
      <!--表格-->
      <el-col  :xs="24" >
        <el-card style="height: 70vh" 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 { 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'

const multipleTableRef=ref<InstanceType<typeof ElTable>>()
/**FTP申请页面对象 */
const state = reactive({
  time:'',
  /**加载显示 */
  loading: false,
  /**条件查询模块 */
  filter: {
    /**申请备注 */
    info: "",
    /**过期时间 */
    expirationTime: '',
    /**申请日期*/
    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: '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.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(() => {
  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.info===''){
    ElMessage.error('请输入申请备注')
  }else{
    const res=await new FuelingFtpAPI().getFtpPwd().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=date.getFullYear()+'-'+month+'-'+day+' 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;
}
</style>
