<template>
  <div>
    <div class="grid-container">
      <div class="grid-item-row1-column1">
        <div class="btn-group m-panel" role="group">
          <button
            type="button"
            class="btn btn-success"
            @click="getAssetInstance"
          >
            {{ $t("lang.AssetInventorySearch.query") }}
          </button>

          <button
            type="button"
            class="btn btn-info"
            @click="generateAssetInventoryLine"
          >
            {{ $t("lang.AssetInventorySearch.generateAssetCountDetails") }}
          </button>

          <button type="button" class="btn btn-danger" @click="clearFilter">
            {{ $t("lang.AssetInventorySearch.empty") }}
          </button>
        </div>
      </div>
      <div class="grid-item-row2-column1">
        <div>
          <div class="panel panel-default m-panel">
            <div
              class="panel-heading"
              @click="type == 1 ? (type = 0) : (type = 1)"
            >
              {{ $t("lang.AssetInventorySearch.ownerDepartment") }}
            </div>
            <div v-show="type == 1" class="panel-body">
              <ClientOrganizationTree
                ref="organization"
                :ids="assetInventoryOrganizationIds"
                @select-changed="selectChanged"
              />
            </div>
          </div>

          <div class="panel panel-default m-panel">
            <div
              class="panel-heading"
              @click="type == 3 ? (type = 0) : (type = 3)"
            >
              {{ $t("lang.AssetInventorySearch.useDepartment") }}
            </div>
            <div v-show="type == 3" class="panel-body">
              <ClientOrganizationTree
                ref="responseOrganization"
                :ids="assetInventoryResponseOrganizationIds"
                @select-changed="selectChanged"
              />
            </div>
          </div>

          <div class="panel panel-default m-panel">
            <div
              class="panel-heading"
              @click="type == 2 ? (type = 0) : (type = 2)"
            >
              {{ $t("lang.AssetInventorySearch.category") }}
            </div>
            <div v-show="type == 2" class="panel-body">
              <div>
                <AssetCategoryTree
                  ref="assetCategory"
                  :ids="assetInventoryCategoryIds"
                  @select-changed="selectChanged"
                />
              </div>
            </div>
          </div>

          <div class="panel panel-default m-panel">
            <div
              class="panel-heading"
              @click="type == 4 ? (type = 0) : (type = 4)"
            >
              {{ $t("lang.AssetInventorySearch.project") }}
            </div>
            <div v-show="type == 4" class="panel-body">
              <div>
                <ProjectItemTree
                  ref="projectItem"
                  :ids="assetInventoryProjectItemIds"
                  @select-changed="selectChanged"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="grid-item-row2-column2">
        <table class="fixed-table table-striped table-bordered">
          <thead>
            <tr>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.ownerClient") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.ownerDepartment") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.useClient") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.useDepartment") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.assetName") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.assetNumber") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.cardNumber") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.type") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.assetClassification") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.subordinateToTheProject") }}
              </th>
              <th style="width: 90px">
                {{ $t("lang.AssetInventorySearch.originalValue") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.placeOfPlacement") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.placementLocation") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.unitOfMeasurement") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.user") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.usageStatus") }}
              </th>
              <th style="width: 100px">
                {{ $t("lang.AssetInventorySearch.userInput") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.licensePlate") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.selfNumbering") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.startUseDate") }}
              </th>
              <th style="width: 130px">
                {{ $t("lang.AssetInventorySearch.remarks") }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="assetInstance in assetInstances"
              :key="assetInstance.id"
              @dblclick="openCurdWindow(assetInstance)"
            >
              <td>{{ assetInstance.clientName }}</td>
              <td>{{ assetInstance.organizationName }}</td>
              <td>{{ assetInstance.responseClientName }}</td>
              <td>{{ assetInstance.responseOrganizationName }}</td>
              <td>{{ assetInstance.name }}</td>
              <td>{{ assetInstance.assetNo }}</td>
              <td>{{ assetInstance.no }}</td>
              <td>{{ assetInstance.type }}</td>
              <td>{{ assetInstance.categoryName }}</td>
              <td>{{ assetInstance.projectItemName }}</td>
              <td>{{ assetInstance.orginalValue }}</td>
              <td>{{ assetInstance.savePosition }}</td>
              <td>{{ assetInstance.locationName }}</td>
              <td>{{ assetInstance.computationUnitName }}</td>
              <td>{{ assetInstance.useUserName }}</td>
              <td>{{ assetInstance.useStatusName }}</td>
              <td>{{ assetInstance.useUserNameInput }}</td>
              <td>{{ assetInstance.vehicleNo }}</td>
              <td>{{ assetInstance.selfNo }}</td>
              <td>{{ assetInstance.depreciationStartDate }}</td>
              <td>{{ assetInstance.description }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="grid-item-row3-column2">
        <div>
          <p class="bg-success m-grid-footer">
            {{ $t("lang.AssetInventorySearch.totalOfOriginalValue") }}:{{
              orginalValueTotal
            }}
          </p>
        </div>
      </div>
      <div class="grid-item-row4-column2">
        <div>
          <div class="pull-left">
            <span>{{ $t("lang.AssetInventorySearch.the")
            }}{{ (pagination.current_page - 1) * pagination.per_page + 1 }}-{{
              pagination.current_page * pagination.per_page
            }}{{ $t("lang.AssetInventorySearch.strip") }},{{
              $t("lang.AssetInventorySearch.inTotal")
            }}{{ pagination.total
            }}{{ $t("lang.AssetInventorySearch.strip") }},{{
              $t("lang.AssetInventorySearch.eachPage")
            }}</span>
            <PageSizeSelect @page-size-changed="pageSizeChanged" />
            <span>{{ $t("lang.AssetInventorySearch.strip") }}</span>
          </div>
          <div class="pull-right">
            <VueBootstrapPagination :pagination="pagination" :callback="pageStartChanged" />
          </div>
        </div>
      </div>
    </div>
    <div class="flex-container-1">
      <div class="flex-content-1">
        <div class="flex-main-1">
          <div>
            <div class="flex-container-2">
              <div class="flex-header-2">
                <div class="m-row" />
              </div>
              <div class="flex-content-2">
                <div class="flex-main-2" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../../common/Common.js';

import AssetInstanceResource from '../../api/asset/AssetInstanceResource.js';
import AssetInventoryResource from '../../api/asset/AssetInventoryResource.js';


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







export default {

  components: {    
    ProjectItemTree,
    AssetCategoryTree,
    ClientOrganizationTree,
  },

  
  props: {
    assetInventoryId: {
      type: Number,
      default: null,
    },
  },
  
  data: function () {
    return {
      assetInventory: {}, // 资产盘点
      clientOrganizations: [], // 所属部门
      responseClientOrganizations: [], // 使用部门
      categories: [], // 资产类别
      projectItems: [], // 项目类别
      useStatus: [], //使用状态
      type: null, //全盘搜索条件
      assetInstances: [],

      additionalHql: '',
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 1, // required
      },
      filter: {},
      totalCount: 0,
      orginalValueTotal: 0,
      totalAmountOfImpairmentTotal: 0,
      netSalvageTotal: 0,
      uuid: Uuid.createUUID(),
      assetInventoryOrganizationIds: [], // 盘点单中已经选中的使用部门
      assetInventoryResponseOrganizationIds: [], // 盘点单中已经选中的所属部门
      assetInventoryCategoryIds: [], // 盘点单中已经选中的资产类别
      assetInventoryProjectItemIds: [], // 盘点单中已经选择的项目
      loading: false,
    };
  },

  mounted: function () {
    var _self = this;

    _self.$nextTick(function () {
      _self.getAssetInventory();
      // 固定行
      _self.fixedTableHeader();
    });

    // 可调整表格列宽
    _self.$nextTick(function () {
      $('.fixed-table').resizableColumns();
    });
  },
  methods: {
    selectChanged: function () {
      var _self = this;
      _self.getAssetInstance();
    },

    /**
     * 查询盘点单DTO,
     * 主要是获取资产盘点中的所属部门集合、使用部门集合、资产类别结合。
     * @author yangzhijie 20200806
     */
    getAssetInventory: function () {
      var _self = this;

      AssetInventoryResource.getResponseOrganizationsAndOrganizationsAndCategory(
        _self.assetInventoryId,
      ).then(
        baseObjectResponse => {
          if(baseObjectResponse.errorCode == 0){
            _self.assetInventoryOrganizationIds = baseObjectResponse.data.organizationIds;

            _self.assetInventoryResponseOrganizationIds =
            baseObjectResponse.data.responseOrganizationIds;

            _self.assetInventoryCategoryIds = baseObjectResponse.data.categoryIds;

            _self.assetInventoryProjectItemIds = baseObjectResponse.data.projectIds;

            _self.assetInventory = baseObjectResponse.data;

            _self.$nextTick(function () {
              _self.$refs.organization.setSelectedIds(
                _self.assetInventoryOrganizationIds,
              );
              _self.$refs.responseOrganization.setSelectedIds(
                _self.assetInventoryResponseOrganizationIds,
              );
              _self.$refs.assetCategory.setSelectedIds(
                _self.assetInventoryCategoryIds,
              );
              _self.$refs.projectItem.setSelectedIds(
                _self.assetInventoryProjectItemIds,
              );
            });
            // 查询资产卡片的数据
            _self.getAssetInstance();
          }else{
            Notify.error('提示', baseObjectResponse.errorMessage, false);
          }
        },
        xmlHttpRequest => {
          Common.processException(xmlHttpRequest);
        },
      );
    },

    /**
     * 根据界面选中的所属部门、使用部门、资产类别、项目查询资产清单
     * @author yangzhijie 20200806
     */
    getAssetInstance: function (isPageChange) {
      var _self = this;

      if (!isPageChange) {
        _self.pagination.current_page = 1;
      }
      var projectItemIds = _self.$refs.projectItem.getSelectedIds();
      var organizationIds = _self.$refs.organization.getSelectedIds();
      var responseOrganizationIds =
        _self.$refs.responseOrganization.getSelectedIds();
      var categoryIds = _self.$refs.assetCategory.getSelectedIds();

      _self.clearPageData();

      _self.loading=true;

      _self.filter.assetDecrease = 0;

      // 账套时间
      _self.filter.depreciationStartDate2 = `${_self.assetInventory.accountDate} 00:00:00`;

      var obj = {
        organizationIds: organizationIds,
        assetCategoryIds: categoryIds,
        responseOrganizationIds: responseOrganizationIds,
        projectItemIds: projectItemIds,
        filter: _self.filter,
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        inventoryStatus: 'OVERALL',
      };

      AssetInstanceResource.getByOrganizationAndCategory(obj).then(
        baseObjectResponse => {
          _self.loading=false;
          if(baseObjectResponse.errorCode != 0) {
            Notify.error('提示', baseObjectResponse.errorMessage, false);
            return;
          }
          _self.redrawAssetInstance(baseObjectResponse.data);
        },
        xmlHttpRequest => {
          Common.processException(xmlHttpRequest);
        },
      );
    },

    /**
     * 生成资产盘点明细
     * @author YangZhiJie 20200806
     */
    generateAssetInventoryLine: function () {
      var _self = this;

      var organizationIds = _self.$refs.organization.getSelectedIds();
      var responseOrganizationIds =
        _self.$refs.responseOrganization.getSelectedIds();
      var categoryIds = _self.$refs.assetCategory.getSelectedIds();
      var projectItemIds = _self.$refs.projectItem.getSelectedIds();

      _self.loading=true;
      var obj = {
        assetInventoryId: _self.assetInventoryId,
        organizationIds: organizationIds,
        responseOrganizationIds: responseOrganizationIds,
        assetCategoryIds: categoryIds,
        projectItemIds: projectItemIds,
      };
      AssetInventoryResource.generateAssetInventoryLineByOrganizationAndCategory(
        obj,
      ).then(
        baseObjectResponse => {
          if(baseObjectResponse.errorCode == 0){
            Common.showDialog('提示', baseObjectResponse.errorMessage, 'success');
          }
          _self.loading=false;
        },
        xmlHttpRequest => {
          _self.loading=false;
          Common.processException(xmlHttpRequest);
        },
      );
    },

    /**
     * 重新绘制资产卡片
     * @author YangZhiJie 20200806
     */
    redrawAssetInstance: function (data) {
      var _self = this;
      console.log(data);
      _self.assetInstances = data.dataList;
      _self.pagination.total = data.totalSize;
      _self.pagination.last_page = Math.ceil(
        data.totalSize / data.range.length,
      );
      _self.totalCount = data.totalSize;
      _self.orginalValueTotal = data.totalOrginalValue;
      _self.totalAmountOfImpairmentTotal = data.totalAmountOfImpairment;
      _self.netSalvageTotal = data.totalNetSalvage;

      _self.fixedTableHeader();
    },

    /**
     * 清空分页数据
     * @author YangZhiJie 20200806
     */
    clearPageData: function () {
      var data = {
        dataList: [],
        totalSize: 0,
        range: {
          start: 0,
          length: this.pagination.per_page,
        },
        totalOrginalValue: 0,
        totalAmountOfImpairment: 0,
        totalNetSalvage: 0,
      };
      this.redrawAssetInstance(data);
    },

    /**
     * 清空界面的搜索条件
     * @author YangZhiJie 20200806
     * @author XiongLiuJie 20211119
     */
    clearFilter: function () {
      this.filter.assetDecrease = 0;
      // 账套时间
      this.filter.depreciationStartDate2 = `${this.assetInventory.accountDate} 00:00:00`;
      this.initTreeData();
      this.getAssetInstance();
    },

    /**
     * 初始化数据
     * @author LeiGuoXian
     * @date 2020-09-15
     */
    initTreeData: function () {
      var _self = this;
      _self.$refs.projectItem.initProjectItem1();
      _self.$refs.organization.initClientOrganization1();
      _self.$refs.responseOrganization.initClientOrganization1();
      _self.$refs.assetCategory.initAssetCategory1();
    },

    /**
     * 表格显示行数发生改变
     * @author YangZhiJie 20200806
     */
    pageSizeChanged: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
      this.getAssetInstance();
    },

    /**
     * 页数发生变化
     * @author YangZhiJie 20200806
     */
    pageStartChanged: function () {
      this.getAssetInstance(true);
    },

    /**
     * 冻结表头
     */
    fixedTableHeader: function () {
      var _self = this;
      _self.$nextTick(function () {
        $('.fixed-table').tableFixer({
          head: true,
        });
      });

      // 给table的外面的div设置固定的高度，如果不设置固定高度，无法固定表格的表头
      // let height = $(".flex-content").outerHeight(true) - 20;
      // $(".table-fixed-out").css("height", height);
    },

    /**
     * 打开资产卡片的CURD窗口
     */
    openCurdWindow: function (assetInstance) {
      let url = Common.getRedirectUrl(
        '#/desktop/window/window-read/view/040701/0/' +
          assetInstance.id +
          '?currPage=1&currIndex=1&totalCount=1&uuid=' +
          Uuid.createUUID(),
      );
      window.open(url, '资产卡片');
    },
  },
};
</script>

<style scoped>
.grid-container {
  margin-top: 10px;
  display: grid;
  grid-template-columns: 300px auto;
  grid-template-rows: 35px 1fr 40px 40px;
  gap: 10px;
  justify-items: stretch;
  align-items: stretch;
  height: calc(100vh - 170px);
  overflow: auto;
}

.grid-item-row1-column1 {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 1;
  grid-column-end: 3;
}

.grid-item-row2-column1 {
  grid-row-start: 2;
  grid-row-end: 5;
  grid-column-start: 1;
  grid-column-end: 2;
  overflow: auto;
}

.grid-item-row2-column2 {
  grid-row-start: 2;
  grid-row-end: 3;
  grid-column-start: 2;
  grid-column-end: 3;
  overflow: auto;
}

.grid-item-row3-column2 {
  grid-row-start: 3;
  grid-row-end: 4;
  grid-column-start: 2;
  grid-column-end: 3;
}

.grid-item-row4-column2 {
  grid-row-start: 4;
  grid-row-end: 5;
  grid-column-start: 2;
  grid-column-end: 3;
}
</style>

<style scoped>
.m-grid-footer {
  padding: 10px;
}

.m-panel {
  margin-bottom: 0px;
}

.fixed-table {
  table-layout: fixed;
  width: 800px !important;
  min-width: 800px !important;
}

table.fixed-table tr {
  height: 40px;
}

table.fixed-table th,
table.fixed-table td {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
