<template>
  <a-layout class="container">
    <!-- 搜索区域 -->
    <a-space v-show="!showDetail" direction="vertical" :size="16" class="search-section">
      <a-input-search
        v-model:value="conditional"
        placeholder="输入用户名称"
        enter-button="搜索"
        class="search-input"
        @search="inputSearch"
      />
      <a-typography-text v-show="showPager" type="secondary">
        一共为您找到相关结果约 {{ pagination.total }} 个
      </a-typography-text>

      <!-- 用户列表 -->
      <a-list :data-source="users" :grid="{ gutter: 16, column: 1 }">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card class="user-card">
              <a-row :gutter="16" align="middle">
                <a-col :span="2">
                  <a-image
                    :src="getImgUrl(item.imageName)"
                    :preview="false"
                    width="50px"
                    height="50px"
                    class="user-avatar"
                  />
                </a-col>
                <a-col :span="22">
                  <a-typography-link @click="showItem(item)">
                    {{ item.name }}{{ item.organizationName ? `-${item.organizationName}` : '' }}
                  </a-typography-link>
                  <a-typography-paragraph type="secondary">
                    所属公司: {{ item.clientName || '无' }} | 
                    所属部门: {{ item.organizationName || '无' }} |
                    用户编号: {{ item.no || '无' }} |
                    EPC: {{ item.epc || '无' }}
                  </a-typography-paragraph>
                </a-col>
              </a-row>
            </a-card>
          </a-list-item>
        </template>
      </a-list>

      <!-- 分页 -->
      <a-pagination
        v-show="showPager"
        v-model:current="pagination.current_page"
        :total="pagination.total"
        :page-size="pagination.per_page"
        @change="checkDataChangedQueryGridData"
      />
    </a-space>

    <!-- 详情视图 -->
    <div v-if="showDetail" class="detail-container">
      <a-space direction="vertical" :size="16">
        <!-- 操作栏 -->
        <a-space>
          <a-button @click="showDetail = false">
            <template #icon><LeftOutlined /></template>
            返回
          </a-button>
          <a-button @click="showItem(seletedUser)">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
          <a-radio-group v-model:value="USER_SHOW_TYPE" button-style="solid">
            <a-radio-button value="TABLE">表格视图</a-radio-button>
            <a-radio-button value="BOARD">看板视图</a-radio-button>
          </a-radio-group>
        </a-space>

        <!-- 用户详情 -->
        <a-card title="用户详情">
          <a-row :gutter="24">
            <a-col :span="4">
              <a-image
                :src="getImgUrl(seletedUser.imageName)"
                :preview="false"
                class="detail-avatar"
              />
            </a-col>
            <a-col :span="20">
              <a-descriptions :column="2" bordered>
                <a-descriptions-item label="所属公司">{{ seletedUser.clientName }}</a-descriptions-item>
                <a-descriptions-item label="所属部门">{{ seletedUser.organizationName }}</a-descriptions-item>
                <a-descriptions-item label="用户名称">{{ seletedUser.name }}</a-descriptions-item>
                <a-descriptions-item label="用户编号">{{ seletedUser.no }}</a-descriptions-item>
                <a-descriptions-item label="EPC">{{ seletedUser.epc }}</a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>
        </a-card>

        <!-- 数据展示 -->
        <a-card :title="USER_SHOW_TYPE === 'TABLE' ? '历史记录' : '图像看板'">
          <a-table
            v-if="USER_SHOW_TYPE === 'TABLE'"
            :columns="tableColumns"
            :data-source="imageInfos"
            :pagination="pagination2"
            bordered
          >
            <template #bodyCell="{ column, text, index }">
              <template v-if="column.dataIndex === 'index'">
                {{ index + 1 + (pagination2.current_page - 1) * pagination2.per_page }}
              </template>
              <template v-if="column.dataIndex === 'image'">
                <a-image
                  :src="getThumbnailImg(text)"
                  width="192px"
                  height="130px"
                  :preview="{ src: text }"
                />
              </template>
            </template>
          </a-table>

          <a-row v-else :gutter="16">
            <a-col v-for="item in imageInfos" :key="item.imageName" :span="6">
              <a-card hoverable>
                <a-image
                  :src="getThumbnailImg(item.imageName)"
                  :preview="{ src: item.imageName }"
                />
                <a-descriptions :column="1">
                  <a-descriptions-item label="地点">{{ item.room }}</a-descriptions-item>
                  <a-descriptions-item label="时间">{{ item.date }}</a-descriptions-item>
                </a-descriptions>
              </a-card>
            </a-col>
          </a-row>
        </a-card>
      </a-space>
    </div>

    <a-spin :spinning="loading" />
  </a-layout>
</template>
<script>
import Common from '../common/Common.js';
import UserStorageResource from '../api/base/UserStorageResource.js';
import { LeftOutlined, ReloadOutlined } from '@ant-design/icons-vue';


import AuthImage from '../widget/AuthImage.vue';
import { Notify, Uuid } from 'pc-component-v3';



export default {

  components: {
    AuthImage,LeftOutlined,
    ReloadOutlined,
  },
  data: function () {
    this.Common = Common;
    return {
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 1, // required
      },
      //历史图片分页参数
      pagination2: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 1, // required
        from: 1,
        to: 1, // required
      },
      conditional: '',
      showPager: false, // 是否显示分页
      users: [],
      showDetail: false,
      seletedUser: '',
      activeContent: 1,
      imageInfos: [],
      historyEvents: [],
      //显示类型 表格TABLE 看板BOARD
      USER_SHOW_TYPE: 'TABLE',
      loading: false,
    };
  },

  mounted: function () {
    let _self = this;

    $('#right-container').css('background-color', '#ffffff');

    UserStorageResource.uniqueByKey('USER_SHOW_TYPE').then(
      str => {
        // if(str.errorCode != 0) {
        //   Notify.error('提示', str.errorMessage, false);
        //   return;
        // }
        if (str.data != null) {
          _self.USER_SHOW_TYPE = str.data;
        }
      },
      errorData => {
        Common.processException(errorData);
      },
    );
  },

  beforeUnmount: function () {
    $('#right-container').css('background-color', '#f7f7f7');
  },

  methods: {
    //获取缩略图
    getThumbnailImg: function (src) {
      var srcInfos = src.split('\\');
      return srcInfos[0] + '\\thumbnail\\' + srcInfos[1];
    },

    /**
     * 页数发生变化
     */
    checkDataChangedQueryGridData: function () {
      this.search();
    },
    // 搜索框搜索
    inputSearch: function () {
      this.pagination.current_page = 1;
      this.search();
    },
    /**
     * 搜索
     */
    search: function () {
      var _self = this;
      _self.loading=true;
      var queryParam = {
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        conditional: _self.conditional,
      };

      $.ajax({
        url: Common.getApiURL('userResource/getUsersByName'),
        type: 'post',
        data: JSON.stringify(queryParam),
        contentType: 'application/json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading=false;
          _self.users = data.resultList;
          _self.pagination.total = data.maxCount;
          _self.pagination.last_page =
            data.maxCount % _self.pagination.per_page == 0
              ? data.maxCount / _self.pagination.per_page
              : Math.floor(data.maxCount / _self.pagination.per_page) + 1;
          if (data.resultList != undefined && data.maxCount > 0) {
            _self.showPager = true;
          } else {
            _self.showPager = false;
          }
          _self.loading=false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
     * 获取图片路径
     */
    getImgUrl: function (imageName) {
      return Common.getHostPageBaseURL() + imageName;
    },
    /**
     * 显示资产卡片详细信息
     */
    showItem: function (user) {
      this.seletedUser = user;
      this.showDetail = true;
      var _self = this;
      $.ajax({
        url: Common.getApiURL('UserImageResource/getUserImageInfosByEpc'),
        type: 'GET',
        dataType: 'json',
        data: {
          epc: user.epc,
          start:
            (_self.pagination2.current_page - 1) * _self.pagination2.per_page,
          length: _self.pagination2.per_page,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != undefined) {
            _self.imageInfos = data.resultList;
            _self.pagination2.total = data.maxCount;
            _self.pagination2.last_page =
              _self.pagination2.total % _self.pagination2.per_page == 0
                ? _self.pagination2.total / _self.pagination2.per_page
                : _self.pagination2.total / _self.pagination2.per_page + 1;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    callbackFun: function () {
      if (this.seletedUser == undefined || this.seletedUser == '') {
        return;
      }
      this.showItem(this.seletedUser);
    },
    changeShowType: function () {
      if (this.USER_SHOW_TYPE == 'TABLE') {
        this.USER_SHOW_TYPE = 'BOARD';
      } else {
        this.USER_SHOW_TYPE = 'TABLE';
      }
      let userStorageDtos = [
        {
          key: 'USER_SHOW_TYPE',
          value: this.USER_SHOW_TYPE,
        },
      ];

      UserStorageResource.uploadUserStorage(userStorageDtos).then(
        successData => {
          console.log('#USER_SHOW_TYPE上传成功');
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
  },
};
</script>

<style scoped>
/* 自定义样式 */
.container {
  padding: 24px;
  background-color: #fff;
}
.search-section {
  width: 100%;
}
.search-input {
  width: 100%;
}

.user-card {
  transition: box-shadow 0.3s;
}

.user-card:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.detail-avatar {
  border-radius: 4px;
  cursor: pointer;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
}
:deep(.ant-space ) {
  width: 100%;
}
</style>