<template>
  <section class="k-publish-page">
    <el-dialog :model-value="props.publishVisible" align-center class="kf-publish-dialog" :close-on-click-modal="false" @open="openForPublish"
      @close="closeForPublish">
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <span :id="titleId" :class="titleClass">{{ $t('Release') }}</span>
        </div>
      </template>
      <section class="kf-publish-body">
        <div class="kf-publish-body-bottom" v-if="isSel === 'web'">
          <k-input type="text" :readonly="true" :autoWrap="false" :value="linkForm.publishLink" icon="iconfont icon-fuzhi" width="100%"></k-input>

          <k-button :name="$t('NewWindowOpensWebSite')" :label="$t('ViewScenes')" @clickHandle="doViewPage"></k-button>

          <k-switch :label="$t('Duration')" :options="dateOpstions" :key="5" v-model:value="state.timeoutType" @clickHandle="selTimeout">
          </k-switch>

          <div class="pub-date-picker" v-if="state.timeoutType === $t('Custom')">
            <label :for="$t('DateSelection')">{{ $t('DateSelection') }}</label>
            <el-date-picker v-model="timeout" type="date" @change="datePickerChange" :placeholder="$t('PleaseSelectADate')" size="default" />
          </div>

          <k-select :label="$t('PageFillMode')" :list="fillOptions" v-model:value="state.linkForm.overflowPolicy" :style="{ 'margin-bottom': '20px' }"></k-select>

          <k-input :label="$t('SystemName')" type="text" :readonly="false" :autoWrap="false" v-model:value="linkForm.sysTittle" width="49%"></k-input>

          <k-switch :label="$t('AreYouAlreadyLoggedIn')" :key="1" v-model:value="state.linkForm.usePasswordFlag"></k-switch>

          <k-select :label="$t('UserGroup')" v-if="state.linkForm.usePasswordFlag" v-model:value="state.linkForm.password" :list="getUserList()"></k-select>

          <k-switch :label="$t('ReleaseStatus')" :options="[
              { label: $t('Online'), value: 0 },
              { label: $t('Offline2'), value: 1 },
            ]" :key="5" v-model:value="state.linkForm.accessFlag">
          </k-switch>
          <k-button :name="$t('UpdatingOfThePublicWebSite')" :label="$t('SynchronizeChanges')" @clickHandle="updatePubWebLink"></k-button>
        </div>

        <div class="kf-publish-body-bottom" v-else>
          <k-input :label="$t('Name')" type="text" :autoWrap="false" width="49%"></k-input>
          <k-select></k-select>
          <k-switch :label="$t('Visibility')" :options="[
              { label: $t('All2'), value: 1 },
              { label: $t('Private'), value: 0 },
            ]" :key="5" :value.sync="isUpdateLink">
          </k-switch>
          <div :style="{ height: '50px' }"></div>
          <k-button :name="$t('UpdatingOfThePublicWebSite')" :label="$t('SynchronizeChanges')" @clickHandle="updatePubWebLink"></k-button>
        </div>
      </section>
    </el-dialog>
  </section>
</template>

<script setup>
import kButton from "./kButton.vue";
import kInput from "./kInput.vue";
import kSwitch from "./kSwitch.vue";
import kSelect from "./kSelect.vue";
import { onMounted, reactive, toRaw, toRefs, watch } from "vue";
import projectService from "@/service/project";
import pageModel from "../ui/model/page";
import userModel from "../ui/model/user";
import { ElMessage } from "element-plus";

const state = reactive({
  tabs: [
    { name: Kf.t('WebAddress'), value: "web", active: true },
    // { name: "库", value: "lib", active: false },
  ],
  isSel: "web",
  isUpdateLink: false,
  dateOpstions: [],
  timeout: "",
  timeoutType: "",
  fillOptions: [
    { label: Kf.t('Auto'), value: "auto" },
    { label: Kf.t('WidthFill'), value: "fullwidth" },
    { label: Kf.t('HeightFill'), value: "fullheight" },
    { label: Kf.t('ScaleFill'), value: "scale" },
  ],
  userList: [],
  linkForm: {
    publishLink: "",
    timeout: null,
    accessFlag: 0,
    projectUuid: null,
    pageUuid: null,
    overflowPolicy: "auto",
    token: localStorage.getItem("KC_TOKEN"),
    device: "pc",
    loginUserId: JSON.parse(localStorage.getItem("KC_USER")).userId,
    usePasswordFlag: 0, // 是否登录
    password: "", // 选取的用户组名
    sysTittle: "", // 发布系统名称
  },
});
const {
  tabs,
  isSel,
  timeout,
  dateOpstions,
  timeoutType,
  fillOptions,
  linkForm,
  userList,
} = toRefs(state);
const props = defineProps({
  publishVisible: {
    type: Boolean,
    default: () => false,
  },
});

const emits = defineEmits(["update:publishVisible"]);
onMounted(() => {
  userList.value = getUserList();
  getDatetime();
});

// tab选择
const tabChange = (tab) => {
  console.log(tab);
  isSel.value = tab.value;
};

// 更新公共网址按钮事件
const updatePubWebLink = () => {
  requestPublishWebLink("update");
};

// 发布接口请求
const requestPublishWebLink = (type) => {
  const currPage = structuredClone(pageModel.getHomePage());
  let { projectId, uuid, version } = currPage;
  let exportUrl = formatUrl();
  if (projectId != null && uuid != null) {
    state.linkForm.projectUuid = projectId;
    state.linkForm.pageUuid = uuid;
    state.linkForm.version = version;
  }
  state.linkForm.publishLink = "presenter/" + projectId + "/" + uuid + "/sd0";
  projectService.addShareList(state.linkForm).then((result) => {
    // console.log(result, "发布请求返回结果");
    let eUrl = formatUrl();
    for (let key in state.linkForm) {
      state.linkForm[key] = result[key];
    }
    if (result["shortLink"]) {
      state.linkForm.publishLink = eUrl + result.shortLink + "/ui";
    }
    state.isUpdateLink = false;
    type === "update"
      ? ElMessage.success(Kf.t('UpdateSuccessful'))
      : ElMessage.success(Kf.t('PostedSuccessfully'));
  });
};
// 新窗口打开
const doViewPage = () => {
  if (!linkForm.value.publishLink && linkForm.value.publishLink == "") {
    ElMessage.warning(Kf.t('PleaseCheckThatTheReleaseLinkIsCorrect'));
    return;
  }
  emits("update:publishVisible", false);
  try {
    window.open(
      linkForm.value.publishLink,
      "newwindow",
      "width=" +
      (window.screen.availWidth + 500) +
      ",height=" +
      (window.screen.availHeight - 50) +
      ",top=0,left=0,fullscreen=1,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no"
    );
  } catch (error) {
    ElMessage.warning(Kf.t('FailedToOpenPostPage'));
  }
};
const formatUrl = () => {
  let exportUrl = window.location.href;
  let index = exportUrl.indexOf("#/");
  if (index !== -1) {
    exportUrl = exportUrl.substring(0, index + 2);
    return exportUrl;
  }
};
// 日历选择
const datePickerChange = (value) => {
  // console.log(value.toJSON());
  linkForm.value.timeout = value.toJSON();
};

// 有效期选择
const selTimeout = (param) => {
  timeoutType.value = param.value;
  linkForm.value.timeout = param.value1;
};
// user list登录权限组选择
const getUserList = () => {
  let list = [];
  for (let i = 0; i < userModel.userList.value.length; i++) {
    let user = userModel.userList.value[i],
      li = {};
    if (!user.category) {
      li = { label: Kf.t('NoGrouping'), value:Kf.t('NoGrouping') };
    } else {
      li = { label: user.category, value: user.category };
    }
    if (!list.some((it) => it.label === li.label)) {
      list.push(li);
    }
  }
  return list;
};
// 格式化有效期options
const getDatetime = () => {
  state.dateOpstions = [
    { label: Kf.t('D1'), value1: formData({ day: 1 }), value: Kf.t('1Day') },
    { label: Kf.t('D7'), value1: formData({ day: 7 }), value: Kf.t('7Days') },
    { label: Kf.t('D30'), value1: formData({ month: 1 }), value: Kf.t('30Days')},
    { label: Kf.t('Permanent'), value1: "", value: Kf.t('Permanent'),icon:'icon-yongjiu'},
    { label: Kf.t('Custom'), value1: Kf.t('Custom'), value:Kf.t('Custom'),icon:'icon-riqi' },
  ];
  linkForm.value.timeout = state.dateOpstions[1].value1;
};
// 格式化时间
const formData = (date = { day: 0, month: 0 }) => {
  let dateTime = new Date();
  if (date.day && date.day !== 0) {
    return new Date(
      new Date().setDate(dateTime.getDate() + date.day)
    ).toJSON();
  } else if (date.month && date.month !== 0) {
    return new Date(new Date().setMonth(dateTime.getMonth() + 1)).toJSON();
  }
};

// 获取发布 link 的历史数据
const getLinkHistory = () => {
  const currPage = structuredClone(pageModel.currPage.value);
  let exportUrl = formatUrl();
  let { projectId, uuid } = currPage;
  projectService.getShareList(projectId, uuid).then((res) => {
    if (res.length === 0) {
      requestPublishWebLink("init");
    } else {
      state.isUpdateLink = true;
      let result = res[0];
      for (let key in linkForm.value) {
        linkForm.value[key] = result[key];
      }
      state.linkForm.publishLink = exportUrl + result.shortLink + "/ui";
      state.isUpdateLink
        ? Object.assign(linkForm.value, { uuid: result.uuid })
        : "";
    }
  });
};

// dialog open
const openForPublish = () => {
  localStorage.removeItem("projectUser");
  const currPage = structuredClone(pageModel.currPage.value);
  let { projectId } = currPage;
  userModel.loadUsers(projectId);
  linkForm.value.timeout = state.dateOpstions[1].value1;
  getLinkHistory();
};

// dialog close
const closeForPublish = () => {
  emits("update:publishVisible", false);
};
</script>

<style lang="scss">
.k-publish-page {
  .kf-publish-dialog {
    border: 1px solid #333333;
    box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
    border-radius: 5px;
    background: #202020;
    width: 30%;
    overflow-y: overlay;
    .el-dialog__header {
      height: 35px;
      line-height: 35px;
      padding: 0 1rem;

      .my-header {
        i {
          color: #aaa;
        }
      }

      .el-dialog__headerbtn {
        top: 2px;
        height: 35px;
      }

      .el-dialog__title {
        font-size: 13px;
        color: #bbb;
      }
    }

    .el-dialog__body {
      border-top: 0;
      background-color: #202020;
      padding: 0px;
      .el-form-item__label {
        justify-content: flex-start;
        font-size: 13px;
        color: #ddd;
      }
    }
  }

  .kf-publish-dialog {
    font-family: Alibaba PuHuiTi;

    // border-top: 1px solid rgba(255, 255, 255, 1);
    .kf-publish-body {
      display: flex;
      flex-direction: column;
      &-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        flex: 1;
        gap: 1rem;
        padding: 1rem;
      }
      &-bottom {
        width: 100%;
        display: flex;
        flex-direction: column;
        flex: 5;
        gap: 1rem;
        padding: 1rem;
        border-top: 1px solid rgba(255, 255, 255, 0.1);
      }
      .pub-date-picker {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        ::v-deep(.el-input__inner) {
          height: 30px;
          line-height: 30px;
          background-color: transparent;
          border: none;
          box-shadow: 0px 0px 1.5px rgba(165, 165, 165, 0.8);
        }
        .el-input__inner:hover {
          border-color: transparent;
        }
        label {
          font-size: 12px;
          color: #aaaaaa;
        }
        ::v-deep(.el-input) {
          width: 49%;
          font-size: 12px;
          color: #aaaaaa;
          // border: 1px solid #2c2c2c;
          background-color: #282828;
          --el-input-focus-border: #2c2c2c;
          --el-input-focus-border-color: #2c2c2c;
          --el-input-hover-border-color: transparent;
          --el-input-hover-border: transparent;
        }
        .el-input__inner:focus {
          border-color: transparent;
          box-shadow: 0px 0px 1.5px rgba(165, 165, 165, 1);
        }
      }
    }
  }
}
</style>
