<template>
  <div>
    <div class="grid-container">
      <div class="grid-item-1">
        <div style="margin-top: 10px">
          <div class="col-md-12">
            <div class="form-inline">
              <div class="form-group">
                <label for="name">{{
                  $t("lang.ConsolidatedAssetInventory.inventoryName")
                }}</label>
                <input
                  id="name"
                  v-model="name"
                  type="text"
                  class="form-control"
                  @keydown.enter="resetQuery"
                />
              </div>
              <div class="form-group">
                <label for="documentNo">{{
                  $t("lang.ConsolidatedAssetInventory.inventoryNo")
                }}</label>
                <input
                  id="documentNo"
                  v-model="documentNo"
                  type="text"
                  class="form-control"
                  @keydown.enter="resetQuery"
                />
              </div>
              <div class="form-group">
                <button class="btn btn-primary" @click="resetQuery">
                  {{ $t("lang.ConsolidatedAssetInventory.query") }}
                </button>
                <!-- <button
                  class="btn btn-success"
                  @click="selectCombinedInventory"
                >
                  {{
                    $t(
                      "lang.ConsolidatedAssetInventory.selectCombinedInventory"
                    )
                  }}
                  <span class="badge">{{ selectCombinedInventoryCount }}</span>
                </button> -->
                <button
                  class="btn btn-success"
                  @click="viewConsolidatedCountSheet"
                >
                  {{
                    $t(
                      "lang.ConsolidatedAssetInventory.viewConsolidatedCountSheet"
                    )
                  }}
                  <span class="badge">{{ selectCombinedInventoryCount }}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="grid-item-2">
        <table
          class="fixed-table table-striped table-bordered"
          style="margin-top: 10px"
        >
          <thead>
            <tr>
              <th class="col-md-1">
                <input
                  v-model="checked"
                  type="checkbox"
                  :checked="checked"
                  @change="selectAll()"
                />
              </th>
              <th class="col-md-2">
                {{ $t("lang.ConsolidatedAssetInventory.departmentName") }}
              </th>
              <th class="col-md-3">
                {{ $t("lang.ConsolidatedAssetInventory.organizationName") }}
              </th>
              <th class="col-md-4">
                {{ $t("lang.ConsolidatedAssetInventory.inventoryName") }}
              </th>
              <th class="col-md-5">
                {{ $t("lang.ConsolidatedAssetInventory.inventoryNo") }}
              </th>
              <th class="col-md-6">
                {{ $t("lang.ConsolidatedAssetInventory.startDate") }}
              </th>
              <th class="col-md-7">
                {{ $t("lang.ConsolidatedAssetInventory.expirationDate") }}
              </th>
              <th class="col-md-8">
                {{ $t("lang.ConsolidatedAssetInventory.accountDate") }}
              </th>
            </tr>
          </thead>
          <tbody v-if="inventoryDtos.length > 0">
            <tr
              v-for="item in inventoryDtos"
              :key="item.id"
            >
              <td class="col-md-1">
                <input
                  type="checkbox"
                  name="checkboxinput"
                  :checked="item.checked"
                  @click="changeSelect(item)"
                />
              </td>
              <td class="col-md-2">{{ item.organizationName }}</td>
              <td class="col-md-3">{{ item.clientName }}</td>
              <td class="col-md-4">{{ item.name }}</td>
              <td class="col-md-5">{{ item.documentNo }}</td>
              <td class="col-md-6">{{ item.inventoryStartDate }}</td>
              <td class="col-md-7">{{ item.inventoryEndDate }}</td>
              <td class="col-md-8">{{ item.accountDate }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="grid-item-3">
        <div>
          <div class="pull-left">
            <span>{{ $t("lang.ConsolidatedAssetInventory.the")
            }}{{ (pagination.current_page - 1) * pagination.per_page + 1 }}-{{
              pagination.current_page * pagination.per_page
            }}{{ $t("lang.ConsolidatedAssetInventory.strip") }},{{
              $t("lang.ConsolidatedAssetInventory.inTotal")
            }}{{ pagination.total
            }}{{ $t("lang.ConsolidatedAssetInventory.strip") }},{{
              $t("lang.ConsolidatedAssetInventory.eachPage")
            }}</span>
            <PageSizeSelect @page-size-changed="pageSizeChanged" />
            <span>{{ $t("lang.ConsolidatedAssetInventory.strip") }}</span>
          </div>
          <div class="pull-right">
            <Pagination
              v-if="pagination.last_page > 0"
              :pagination="pagination"
              :callback="getDatas"
              :show-head-and-tail="true"
            />
          </div>
        </div>
      </div>
      <div>
        <a-button type="primary" @click="previous">上一步</a-button>
      </div>
      <div>
        <a-button style="float: right;" type="primary" @click="next">下一步</a-button>
      </div>
      <Modal
        v-model:show="modal"
        title="查看被合并盘点单"
        small="true"
      >
        <div style="height: calc(100vh - 280px); margin-top: 10px">
          <table
            class="fixed-table table-striped table-bordered"
            style="margin-top: 10px"
          >
            <thead>
              <tr>
                <th class="col-md-2">
                  {{ $t("lang.ConsolidatedAssetInventory.inventoryName") }}
                </th>
                <th class="col-md-3">
                  {{ $t("lang.ConsolidatedAssetInventory.inventoryNo") }}
                </th>
                <th class="col-md-1">操作</th>
              </tr>
            </thead>
            <tbody v-if="inventoryDtos1.length > 0">
              <tr
                v-for="item in inventoryDtos1"
                :key="item.id"
              >
                <td>{{ item.name }}</td>
                <td>{{ item.documentNo }}</td>
                <td>
                  <button class="btn btn-danger" @click="deleteAssetInventory(item)">
                    {{ $t("lang.ConsolidatedAssetInventory.delete") }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </Modal>
    </div>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import dayjs from 'dayjs';
import Common from '../common/Common.js';
import AssetInventoryResource from '../api/asset/AssetInventoryResource.js';

module.exports = {
  props: {
    consolidatedCountSheet: {
      type: Object,
      default(){
        return {};
      },
    },
  },

  emits: ['previous','next'],
  data: function () {
    return {
      inventoryDtos: [],
      inventoryDtos1: [],
      combinedInventoryIds: [], //被合并的盘点单
      mergeIntoInventoryIds: [], //合并至的盘点单
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },

      name: null,
      documentNo: null,
      name1: null,
      documentNo1: null,
      checked: false,
      selectCombinedInventoryCount: 0,
      loading: false,
      modal: false,
    };
  },
  components: {
    Common,
    NavBar,
    Loading,
    Pagination,
    DateWidget,
    Modal,
    PageSizeSelect,
  },

  methods: {
    next: function() {
      var _self = this;
      if(_self.combinedInventoryIds.length < 1){
        Common.showDialog('提示', '请至少选择一条被合并盘点单', 'error');
        return;
      }
      var data = {
        currentStep: 2,
        showPage: 2,
        combinedInventoryIds: _self.combinedInventoryIds,
        mergeIntoInventoryIds: _self.consolidatedCountSheet.mergeIntoInventoryIds,
      };
      this.$emit('next', data);
    },
    previous: function() {
      var data = {
        currentStep: 0,
        showPage: 0,
        combinedInventoryIds: [],
        mergeIntoInventoryIds: [],
      };
      this.$emit('previous', data);
    },
    /**
     * 全选和反选
     */
    selectAll: function () {
      var _self = this;
      if (_self.checked) {
        for (var i = 0; i < _self.inventoryDtos.length; i++) {
          _self.inventoryDtos[i].checked = true;
          if (_self.combinedInventoryIds.indexOf(_self.inventoryDtos[i].id,0) == -1) {
            _self.inventoryDtos1.push(_self.inventoryDtos[i]);
            _self.combinedInventoryIds.push(_self.inventoryDtos[i].id);
            _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
          }
        }
      } else {
        for (var j = 0; j < _self.inventoryDtos.length; j++) {
          _self.inventoryDtos[j].checked = false;
          let index = _self.inventoryDtos1.indexOf(_self.inventoryDtos[j]);
          _self.inventoryDtos1.splice(index, 1);
          let index1 = _self.combinedInventoryIds.indexOf(_self.inventoryDtos[j].id);
          _self.combinedInventoryIds.splice(index1, 1);
          _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
        }
      }
    },

    /**
     * 重置分页，然后查询
     */
    resetQuery: function () {
      var _self = this;
      _self.pagination.current_page = 1;
      _self.getDatas();
    },
    /**
     * 表格显示行数发生改变
     */
    pageSizeChanged: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
      this.getDatas();
    },

    /**
     * 查询数据
     */
    getDatas: function () {
      var _self = this;
      _self.loading=true;
      var param = {
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        name: _self.name,
        documentNo: _self.documentNo,
      };
      AssetInventoryResource.findByAssetInventoryRequest(param).then(
        successData => {
          _self.pagination.total = successData.totalSize;
          if (successData.dataList) {
            var isChange = true;
            successData.dataList.forEach(item => {
              if (_self.combinedInventoryIds.indexOf(item.id) < 0) {
                item.checked = false;
                isChange = false;
              }else {
                item.checked = true;
              }
              item.inventoryStartDate = dayjs(item.inventoryStartDate).format('YYYY-MM-DD');
              item.inventoryEndDate = dayjs(item.inventoryEndDate).format('YYYY-MM-DD');
              item.accountDate = dayjs(item.accountDate).format('YYYY-MM-DD');
            });
            _self.checked = isChange;
          }
          _self.inventoryDtos = successData.dataList;
          _self.loading=false;
          if (
            successData.dataList == undefined ||
            successData.dataList.length == 0
          ) {
            return;
          }
          _self.pagination.last_page = Math.ceil(
            successData.totalSize / successData.range.length,
          );
          _self.fixedTableHeader();
        },
        errorData => {
          _self.loading=false;
          Common.processException(errorData);
        },
      );
    },
    changeSelect: function(data) {
      var _self = this;
      data.checked = !data.checked;
      if (data.checked && _self.combinedInventoryIds.indexOf(data.id,0) == -1) {
        _self.inventoryDtos1.push(data);
        _self.combinedInventoryIds.push(data.id);
        _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
      }
      else{
        let index = _self.inventoryDtos1.indexOf(data);
        _self.inventoryDtos1.splice(index, 1);
        let index1 = _self.combinedInventoryIds.indexOf(data.id);
        _self.combinedInventoryIds.splice(index1, 1);
        _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
      }
    },

    /**
     * 加入至被合并盘点单中
     */
    selectCombinedInventory: function () {
      var _self = this;
      _self.loading=true;
      this.inventoryDtos.forEach(function (item) {
        if (item.checked && _self.combinedInventoryIds.indexOf(item.id,0) == -1) {
          _self.inventoryDtos1.push(item);
          _self.combinedInventoryIds.push(item.id);
        }
      });

      if (_self.combinedInventoryIds.length < 1) {
        _self.loading=false;
        Common.showDialog('提示', '请选择数据后再提交', 'error');
        return;
      }

      if (_self.combinedInventoryIds.length > 0) {
        _self.loading=false;
        _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
        Common.showDialog('提示', '加入成功', 'success');
      } else {
        _self.loading=false;
        Common.showDialog('提示', '请选择要提交的内容', 'error');
      }
    },

    /**
     * 查看被合并盘点单模态框
     */
    viewConsolidatedCountSheet: function () {
      var _self = this;
      _self.modal = true;
    },
    /**
     * 删除选中的被合并盘点单
     */
    deleteAssetInventory: function (data) {
      var _self = this;
      var isSuccess = false;
      for(var i = 0 ;i < _self.inventoryDtos1.length; i++){
        if(_self.inventoryDtos1[i].id == data.id){
          _self.inventoryDtos1.splice(i,1);
          isSuccess = true;
          break;
        }
      }
      for(var j = 0 ;j < _self.combinedInventoryIds.length; j++){
        if(_self.combinedInventoryIds[j] == data.id){
          _self.combinedInventoryIds.splice(j,1);
          isSuccess = true;
          break;
        }
      }
      for(var k = 0 ;k < _self.inventoryDtos.length; k++){
        if(_self.inventoryDtos[k].id == data.id){
          _self.inventoryDtos[k].checked = false;
          isSuccess = true;
          break;
        }
      }
      if(isSuccess){
        _self.selectCombinedInventoryCount = _self.combinedInventoryIds.length;
        Common.showDialog('提示', '删除成功', 'success');
      }else{
        Common.showDialog('提示', '删除失败', 'error');
      }

    },

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

    init: function () {
      var _self = this;

      _self.getDatas();

      this.fixedTableHeader();

      // 可调整表格列宽
      _self.$nextTick(function () {
        $('.fixed-table').resizableColumns();
      });
    },
  },

  mounted: function () {
    this.init();
  },

  watch: {
    // 如果路由有变化，会再次执行该方法
    $route: 'init',
  },
};
</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-1 {
  grid-row-start: 1;
  grid-row-end: 3;
  grid-column-start: 1;
  grid-column-end: 3;
}

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

.grid-item-3 {
  grid-row-start: 3;
  grid-row-end: 4;
  grid-column-start: 1;
  grid-column-end: 3;
}

.fixed-table {
  table-layout: fixed;
}

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

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