<script setup lang="ts">
import { getOnlineUserData } from '@/pages/User/OnlineUser/online-user.server';
import { IconRemind } from '@computing/opendesign-icons';
import { traduction } from '@/utils/language';
import { cutStr, getBytes, showElMessage } from '@/utils/utils';
import { computed, nextTick, reactive, ref } from 'vue';
import useStore from '@/stores';
import { addWorknote, delWorknote, editWorknote, getWorknoteData } from './worknote.server';

import Dialog from '@/components/Dialog/Dialog.vue';
import NoDataAvailable from '@/components/NoDataAvailable/NoDataAvailable.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import WorknoteItem from './components/WorknoteItem.vue';

const globalStoreService = new GlobalStoreService();
const successMsg = traduction('COMMON_SUCCESS');
const errorMsg = traduction('COMMON_FAILED');

const extraSize = ref(0);
const MAX_TEXTAREA_LENGTH = 255;
const dialog = ref();
const store = useStore();
const systemLock = computed(() => {
  return store.state.glob.systemLocked;
});
let drawerShow = ref(false);
let isEdit = ref(false);
let checkItem: any = reactive({});
let sessionData: any = {};
let oldDetails = ref('');
// 请求数据完成结果
let reqRes = {
  log: false,
  session: false,
};
let delTitle = traduction('COMMON_DELETE') + ' ' + traduction('COMMON_MAINTANCE_NOTE');
const dialogConfig = reactive({
  title: delTitle,
  content: traduction('COMMON_ASK_OK'),
});

const hintsDialog = ref();
const hintsDialogConfig = reactive({
  title: traduction('COMMON_INFORMATION'),
  content: traduction('WORK_NOTE_CONFIRM_CONTENT_NOMORE_DATA'),
  cancelButton: {
    hide: true,
  },
});

let leftShowData: any[] = reactive([]);
let rightShowData: any[] = reactive([]);

// 点击添加工作记录
function add() {
  if (systemLock.value) {
    return;
  }

  const num = leftShowData.length + rightShowData.length;
  if (num >= 20) {
    hintsDialog.value.show();
    return;
  }

  isEdit.value = false;
  Object.assign(checkItem, {
    user: sessionData.UserName,
    ip: sessionData.IPAddress,
    details: '',
  });
  oldDetails.value = '';
  drawerShow.value = true;
  extraSize.value = 0;
}

// 点击编辑
function edit(item: any) {
  if (systemLock.value) {
    return;
  }
  isEdit.value = true;
  Object.assign(checkItem, item);
  oldDetails.value = item.details;
  drawerShow.value = true;
  extraSize.value = getBytes(item.details);
}

// 确认编辑 / 添加
function sureEdit() {
  let params = {};
  // 编辑
  if (isEdit.value) {
    params = {
      ID: checkItem.id,
      Content: checkItem.details,
    };
    editWorknote(params)
      .then(() => {
        showElMessage('success', successMsg);
        drawerShow.value = false;
        getData();
      })
      .catch((err: any) => {
        showElMessage('error', errorMsg);
        drawerShow.value = false;
      });
  } else {
    // 添加
    params = { Content: checkItem.details };
    addWorknote(params)
      .then(() => {
        showElMessage('success', successMsg);
        drawerShow.value = false;
        getData();
      })
      .catch((err: any) => {
        showElMessage('error', errorMsg);
        drawerShow.value = false;
      });
  }
}

// 点击删除按钮
function del(item: any) {
  if (systemLock.value) {
    return;
  }
  Object.assign(checkItem, item);
  dialogConfig.title = delTitle + item.id;
  dialog.value.show();
}

// 确认删除 / 点击取消
function sureDel(flag: boolean) {
  if (flag) {
    delWorknote(checkItem.id)
      .then((data: any) => {
        if (data['@Message.ExtendedInfo']) {
          showElMessage('error', errorMsg);
        } else {
          showElMessage('success', successMsg);
          dialog.value.hide();
          getData();
        }
      })
      .catch((err: any) => {
        reqRes.log = true;
        changeLoading();
        showElMessage('error', errorMsg);
      });
  } else {
    dialog.value.hide();
  }
}

// 修改全局加载状态
function changeLoading() {
  if (reqRes.log && reqRes.session) {
    globalStoreService.setValue('isLoading', false);
  }
}

// 获取工作记录数据
function getData() {
  reqRes.log = false;
  leftShowData.splice(0);
  rightShowData.splice(0);
  globalStoreService.setValue('isLoading', true);
  getWorknoteData()
    .then((data: any) => {
      data.List.reverse();
      data.List.forEach((item: any, index: number) => {
        const option = {
          id: item.ID,
          user: item.UserName,
          ip: item.IPAddress,
          time: item.Time,
          details: item.Content,
          showTooltip: false,
        };

        if (index % 2 === 0) {
          leftShowData.push(option);
        } else {
          rightShowData.push(option);
        }
      });
      reqRes.log = true;
      changeLoading();
    })
    .catch((err: any) => {
      reqRes.log = true;
      changeLoading();
    });
}

function detailsChange(value: string): void {
  const size = getBytes(value);
  if (size > MAX_TEXTAREA_LENGTH) {
    nextTick(() => {
      checkItem.details = cutStr(value, MAX_TEXTAREA_LENGTH);
      extraSize.value = getBytes(checkItem.details);
    });
  } else {
    extraSize.value = size;
  }
}

// 获取session数据
function getSessions() {
  reqRes.session = false;
  globalStoreService.setValue('isLoading', true);
  getOnlineUserData()
    .then((data: any) => {
      const members = data.Members;
      sessionData = members.find((item: any) => item.MySession);
      reqRes.session = true;
      changeLoading();
    })
    .catch((err: any) => {
      reqRes.session = true;
      changeLoading();
    });
}

getData();
getSessions();

// 点击提示20条数据弹窗中的确认按钮
function hintsClose(flag: boolean) {
  hintsDialog.value.hide();
}
</script>

<template>
  <div id="workNote" class="work-note">
    <div class="content">
      <div>
        <el-button id="addWorkNoteBtn" :disabled="systemLock" type="primary" @click="add">
          {{ $t('WORKNOTE_ADD') }}
        </el-button>
      </div>
      <div class="desc">
        <el-icon>
          <IconRemind />
        </el-icon>
        {{ $t('WORK_NOTE_WARNING') }}
      </div>

      <div class="data-list">
        <div v-for="(item, index) in leftShowData" :key="item.id" class="row">
          <!-- 左右两个部分最终高度以最高的为准，height：100%没有效果，所以设置两个辅助div作为背景色，展现出相同高度 -->
          <!-- 辅助div绝对定位，z-index为1，会将内容掩盖，所以css里面有设置默认定位元素(item-box)的z-index为2，就实现内容在背景上面了 -->
          <div class="left-bg bg"></div>
          <div v-if="rightShowData[index]" class="right-bg bg"></div>

          <WorknoteItem
            class="left-item item-box"
            :data="item"
            :lock="systemLock"
            @edit="edit(item)"
            @del="del(item)"
          ></WorknoteItem>

          <WorknoteItem
            v-if="rightShowData[index]"
            class="item-box"
            :data="rightShowData[index]"
            :lock="systemLock"
            @edit="edit(rightShowData[index])"
            @del="del(rightShowData[index])"
          ></WorknoteItem>
        </div>
      </div>

      <!-- 暂无数据 如果左边都没有数据，右边更不会有，所以这里只判断leftShowData -->
      <NoDataAvailable v-if="!leftShowData.length" />
    </div>

    <!-- 点击删除的弹窗 -->
    <Dialog ref="dialog" :config="dialogConfig" @close="sureDel" />

    <!-- 点击添加提示20条数据的弹窗 -->
    <Dialog ref="hintsDialog" :config="hintsDialogConfig" @close="hintsClose" />

    <!-- 点击编辑 或者 添加的抽屉 -->
    <div v-if="drawerShow" v-reqKeepAlive.drawer>
      <el-drawer v-model="drawerShow" :close-on-click-modal="false" :show-close="false">
        <template #title>
          {{ isEdit ? $t('WORKNOTE_EDIT') : $t('WORKNOTE_ADD') }}
        </template>
        <template #default>
          <div class="content-footer">
            <div class="content">
              <div class="left">
                <div class="label">{{ $t('COMMON_USERNAME') }}</div>
                <div class="label">{{ $t('COMMON_IPADRESS') }}</div>
                <div class="label textarea-label">{{ $t('ONLINE_CONTENT_INFO') }}</div>
              </div>

              <div class="right">
                <div id="userValue" class="value">{{ checkItem.user }}</div>
                <div id="ipValue" class="value">{{ checkItem.ip }}</div>
                <el-input
                  :id="isEdit ? 'editWorkNoteTextarea' : 'addWorkNoteTextarea'"
                  v-model="checkItem.details"
                  :rows="3"
                  :disabled="systemLock"
                  :placeholder="$t('WORK_NOTE_DETAIL_PLACEHOLDER')"
                  type="textarea"
                  @input="detailsChange"
                />
                <div class="extra-size-box">
                  <span class="current-num">{{ extraSize }}</span>
                  <span class="line">/</span>
                  <span class="total">{{ MAX_TEXTAREA_LENGTH }}</span>
                </div>
              </div>
            </div>

            <div class="footer">
              <el-button
                :id="isEdit ? 'editNoteBtn' : 'addNoteBtn'"
                :disabled="!checkItem.details || oldDetails === checkItem.details || systemLock"
                type="primary"
                @click="sureEdit"
              >
                {{ $t('COMMON_SAVE') }}
              </el-button>
              <el-button id="cancelNoteBtn" @click="drawerShow = false">
                {{ $t('COMMON_CANCEL') }}
              </el-button>
            </div>
          </div>
        </template>
      </el-drawer>
    </div>
  </div>
</template>

<style scoped lang="scss">
.work-note {
  flex: 1;
  overflow: hidden;
  margin-right: 24px;
  padding: 24px;
  font-size: 12px;
  color: var(--o-text-color-secondary);
  border-radius: 4px;
  background-color: var(--o-bg-color-base);
  position: relative;

  .content {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .desc {
      margin: 16px 0;
      padding: 8px 16px;
      color: var(--o-text-color-primary);
      border-radius: 2px;
      background-color: var(--o-color-state-primary-secondary);
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        font-size: 16px;
      }
    }

    .data-list {
      flex: 1;
      overflow: auto;
      .row {
        display: flex;
        justify-content: space-between;
        position: relative;

        .item-box {
          z-index: 2;
          margin-bottom: 16px;
          width: calc(50% - 8px);
          height: 100%;
          background-color: var(--o-bg-color-light);
        }

        .bg {
          position: absolute;
          z-index: 1;
          top: 0;
          left: 0;
          width: calc(50% - 8px);
          height: calc(100% - 16px);
          border-radius: 4px;
          background-color: var(--o-bg-color-light);
        }

        .right-bg {
          left: calc(50% + 8px);
        }
      }

      .row:nth-last-child(1) {
        .log-item {
          margin-bottom: 0;
        }

        .bg {
          height: 100%;
        }
      }
    }
  }

  :deep(.el-overlay) {
    .el-dialog {
      width: 432px;

      .content {
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: 16px;
          font-size: 28px;
        }
      }
    }
  }

  :deep(.el-drawer.rtl) {
    width: 552px !important;
    margin-top: 48px;
    height: calc(100% - 48px);
    border-radius: 4px 4px 0 0;
    .el-drawer__header {
      padding: 24px 24px 22px;
      font-weight: bold;
      color: var(--o-text-color-primary);
      font-size: 16px;
      line-height: 24px;
      margin-bottom: 0;
    }

    .el-drawer__body {
      padding: 0;

      .el-textarea.is-disabled {
        background-color: rgba(235, 237, 243, 1);
      }

      .content-footer {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .content {
          display: flex;
          flex-direction: row;
          padding: 0 24px;

          .left {
            margin-right: 24px;

            .label {
              margin-bottom: 24px;
              color: var(--o-text-color-secondary);
            }

            .textarea-label {
              padding-top: 8px;
            }
          }

          .right {
            flex: 1;
            position: relative;

            .extra-size-box {
              position: absolute;
              top: 124px;
              right: 10px;
              display: flex;
              align-items: center;
              color: #bfc7d7;
              line-height: 16px;

              .line {
                margin: 0 2px;
              }
            }

            .value {
              height: 16px;
              margin-bottom: 24px;
            }
          }
        }

        .footer {
          padding: 8px 24px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
        }
      }
    }
  }
}
</style>
