<template>
  <div class="page justify-around">
    <div class="addbtn">
      <el-button type="primary" @click="dialogVisible = true"><el-icon><i-ep-plus /></el-icon> 新增</el-button>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%; height: 90%"
      size="large"
      align="center"
      border
    >
      <el-table-column
        prop="name"
        :label="$t('businessMangage.name')"
        align="center"
      />

      <el-table-column
        prop="address"
        :label="$t('businessMangage.address')"
        align="center"
      />

      <el-table-column
        prop="status"
        :label="$t('businessMangage.status')"
        align="center"
      >
        <template #default="scope">
          <span
            :style="1 * scope.row.status ? 'color: #ff0000' : 'color: #36db43'"
            >{{ getStatus(scope.row.status) }}</span
          >
        </template>
      </el-table-column>

      <el-table-column
        prop="code"
        :label="$t('businessMangage.code')"
        align="center"
      />

      <el-table-column
        prop="createTime"
        :label="$t('businessMangage.createTime')"
        align="center"
      >
        <template #default="scope">
          {{ getDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="时长（秒）"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.remainingTimes }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        :label="$t('keyMangage.operations')"
        width="400"
        align="center"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="showDetail(scope.row.id)"
            >查看密钥</el-button>
            <el-button link type="primary" size="small" @click="setTime(scope.row.id)">设置时长</el-button>
        </template>
      </el-table-column>
    </el-table>
     <el-dialog
      v-model="dialogVisible"
      :title="$t('businessMangage.addNew')"
      width="35%"
      :before-close="handleClose"
    >
      <div class="formData">
        <el-form
          ref="ruleForm"
          label-position="left"
          label-width="120px"
          :model="formData"
          :rules="rules"
        >
          <el-form-item :label="$t('businessMangage.name') + '：'" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="$t('businessMangage.nameInputText')"
            />
          </el-form-item>

          <el-form-item
            :label="$t('businessMangage.address') + '：'"
            prop="address"
          >
            <el-input
              v-model="formData.address"
              :placeholder="$t('businessMangage.addressInputText')"
            />
          </el-form-item>

          <el-form-item :label="$t('businessMangage.code') + '：'" prop="code">
            <el-input
              v-model="formData.code"
              :placeholder="$t('businessMangage.codeInputText')"
            />
          </el-form-item>

          <el-form-item
            :label="$t('businessMangage.accessMethod') + '：'"
            prop="type"
          >
            <el-select
              v-model="formData.type"
              :placeholder="$t('businessMangage.typeInputText')"
              clearable
              disabled
            >
              <el-option
                v-for="(item, index) in accessMethods"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{
            $t("businessMangage.cancel")
          }}</el-button>
          <el-button type="primary" @click="addNew(ruleForm)">
            {{ $t("businessMangage.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 50, 100]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<!-- videoType==1为竖,==2为横 -->
<script setup>
//#region  导入
import { businessListApi, addBusinessApi, setRemainingTimes, saveMallUserInfo } from '@/apis/apiManage.js'

import { useI18n } from "vue-i18n";

import dayjs from "dayjs";

import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const { locale } = useI18n();
const lanChange = ref(locale);

const tableData = ref([]);

const dialogVisible = ref(false);

const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);

const getStatus = (val) => {
  return val * 1 ? "锁定" : "正常";
};

const getDate = (val) => {
  return dayjs(val).format("YYYY-MM-DD");
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getListData(pageNum.value, pageSize.value);
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  getListData(pageNum.value, pageSize.value);
};

const getListData = async (PageNum, PageSize) => {
  try {
    const res = await businessListApi(PageNum, PageSize, 2);
    console.log(res, "res");
    tableData.value = res.data.list;
    total.value = res.data.total * 1;
  } catch (error) {
    console.log(error, "err");
  }
};

const formData = ref({
  name: "",
  address: "",
  code: "",
  type: 2,
});

const rules = {
  name: [
    {
      required: true,
      message: "Please input name",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "Please input address",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "Please input code",
      trigger: "blur",
    },
  ],
  type: [
    {
      required: true,
      message: "Please select access methods",
      trigger: "blur",
    },
  ],
};

const accessMethods = ref([
  {
    label: "api接入",
    value: 1,
  },
  {
    label: "私有化接入",
    value: 2,
  },
]);

const handleClose = () => {
  dialogVisible.value = false;
  setTimeout(() => {
    formData.value = {
      name: "",
      address: "",
      code: "",
      type: 1,
    };
  }, 500);
};

const ruleForm = ref();

const addNew = async (refForm) => {
  if (!refForm) return;
  await refForm.validate(async (valid, fields) => {
    if (valid) {
      const data = formData.value;
      try {
        const res = await addBusinessApi(data);
        console.log(res, "res");
        if (res.code == 200) {
          ElMessage.success("添加成功！");
          dialogVisible.value = false;
        }
        getListData(1, 10);
        pageNum.value = 1;
        pageSize.value = 10;
      } catch (error) {
        console.log(error, "err");
        ElMessage.error(error.message);
      }
    } else {
      ElMessage.error("请完善信息！");
    }
  });
};

// 查看时长
const showDetail = (id) => {
  router.push({
    path: "/businessCheck",
    query: {
      id,
    },
  });
}

// 设置时长
const setTime = (id) => {
  ElMessageBox.prompt('请输入时长（秒）', '设置时长', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    inputPattern: /^[0-9]*$/,
    inputErrorMessage: '请输入数字',
    beforeClose: async (action, instance, done) => {
        if (action == "confirm") {//点击确认请求接口
            let res = await setRemainingTimes({ id: id, times: instance.inputValue })
            if (res.code === 200) {
                // 通过监测关闭
                ElMessage.success('设置成功')
                done();
            } else {
                ElMessage.error(res.message)
            }
        } else {
            //点击取消关闭
            done();
        }
    }
  })
}

onMounted(() => {
  getListData(1, 10);
});
</script>

<style lang="scss" scoped>
.page {
  height: calc(100vh - 80px);
  // height: calc(100vh - 80px);
  background-color: #ffffff;
  border-radius: 30px 0 0 0;
  overflow: hidden;
  padding: 10vh;
  .addbtn {
    margin-bottom: 2vh;
  }
  .formData {
    padding: 5vh 3vh;
  }

  .pagination {
    position: fixed;
    left: 55%;
    bottom: 8vh;
    transform: translateX(-50%);
    border-radius: 5px;
    padding: 10px 20px;
    z-index: 99;
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      background-color: #b8b8b873;
    }
  }
}
</style>
