<template>
  <div>
    <div class="grid-item-row1">
      <div class="btn-group m-panel" role="group">
        <div class="form-inline">
          <div class="form-group">
            <label for="assetName">盘点单名称：</label>
            <label for="assetName"> {{ assetInventoryName }}</label>
          </div>
          <div class="form-group">
            <label class="common" for="assetName">盘点单编号：</label>
            <label for="assetName"> {{ assetInventoryNo }}</label>
          </div>
        </div>
        <div class="form-inline">
          <div class="form-group">
            <label for="assetName">资产名称</label>
            <input
              id="assetName"
              v-model="assetName"
              autocomplete="off"
              type="text"
              class="common form-control"
              placeholder="资产名称"
              @keyup.enter="searchDatas"
            />
          </div>
          <div class="form-group">
            <label class="common" for="assetNo">资产编号</label>
            <input
              id="assetNo"
              v-model="assetNo"
              autocomplete="off"
              type="text"
              class="common form-control"
              placeholder="资产编号"
              @keyup.enter="searchDatas"
            />
          </div>
          <div class="form-group">
            <label class="common" for="cardNo">卡片编号</label>
            <input
              id="cardNo"
              v-model="cardNo"
              autocomplete="off"
              type="text"
              class="common form-control"
              placeholder="卡片编号"
              @keyup.enter="searchDatas"
            />
          </div>
          <a-button
            type="primary"
            class="common"
            @click="searchDatas"
          >
            查询
          </a-button>
          <a-button type="primary" danger class="common" @click="clearFilter">
            清空
          </a-button>
        </div>
      </div>
    </div>

    <CommonTable
      ref="table"
      :columns="columns"
      :data-source="dataSource"
      :total="pagination.total"
      @get-pager="getPageParams"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key == 'useStatusId'">
          <select
            v-model="record.useStatusId"
            class="form-control"
            placeholder="盘点使用状态"
          >
            <option />
            <option
              v-for="useStatus in useStatusList"
              :key="useStatus.id"
              :value="useStatus.id"
            >
              {{ useStatus.text }}
            </option>
          </select>
        </template>
        <template v-if="column.key == 'description'">
          <input
            id="cardNo"
            v-model="record.description"
            autocomplete="off"
            type="text"
            class="form-control"
            placeholder="备注"
          />
        </template>
        <template v-if="column.key == 'affirm'">
          <a-button
            class="btn btn-default"
            @click="updateAssetInventoryLine(record, index)"
          >
            人工确认
          </a-button>
        </template>
        <template v-if="column.key == 'info'">
          <button class="btn btn-link" @click="openCurdWindow(record)">
            查看
          </button>
        </template>
      </template>
    </CommonTable>
    <div>
      <a-button v-if="currentStep == 1" type="primary" class="previousBtn" @click="previous">
        上一步
      </a-button>
    </div>
    <!-- <div class="grid-item-row3">
        <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> -->

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

<script>
import Common from '../../common/Common.js';
import AssetInventoryResource from '../../api/asset/AssetInventoryResource.js';
import AssetInventoryLineResource from '../../api/asset/AssetInventoryLineResource.js';
import { Notify, Uuid } from 'pc-component-v3';
import { SqlApi } from 'pc-component-v3';
import UseStatusResource from '../../api/asset/UseStatusResource.js';
import CommonTable from '../../common/CommonTable.vue';

export default {
  components: {
    CommonTable,
  },
  props: {
    currentStep: {
      type: Number,
      required: true,
      default: 1,
    },
    id: {
      type: Number,
      required: true,
      default: 0,
    },
  },
  emits: ['next', 'changeStep'],
  data: function () {
    return {
      // 表格数据
      columns: [
        {
          title: '资产名称',
          key: 'assetName',
          dataIndex: 'assetName',
          width: 100,
        },
        {
          title: '资产编号',
          key: 'assetNo',
          dataIndex: 'assetNo',
          width: 100,
        },
        {
          title: '卡片编号',
          key: 'cardNo',
          dataIndex: 'cardNo',
          width: 100,
        },
        {
          title: '盘点使用状态',
          key: 'useStatusId',
          dataIndex: 'useStatusId',
          width: 180,
        },
        {
          title: '备注',
          key: 'description',
          dataIndex: 'description',
          width: 180,
        },
        {
          title: '确认',
          key: 'affirm',
          dataIndex: 'affirm',
          width: 100,
        },
        {
          title: '账面位置',
          key: 'locationName',
          dataIndex: 'locationName',
          width: 100,
        },
        {
          title: '账面使用状态',
          key: 'useStatusName',
          dataIndex: 'useStatusName',
          width: 110,
        },
        {
          title: '规格型号',
          key: 'assetType',
          dataIndex: 'assetType',
          width: 100,
        },
        {
          title: '类别名称',
          key: 'assetCategoryName',
          dataIndex: 'assetCategoryName',
          width: 100,
        },
        {
          title: '责任人',
          key: 'custodianUserName',
          dataIndex: 'custodianUserName',
          width: 100,
        },
        {
          title: '使用人',
          key: 'useUserName',
          dataIndex: 'useUserName',
          width: 100,
        },
        {
          title: '保管人',
          key: 'depositoryUserName',
          dataIndex: 'depositoryUserName',
          width: 100,
        },
        {
          title: '所属单位',
          key: 'clientName',
          dataIndex: 'clientName',
          width: 100,
        },
        {
          title: '所属部门',
          key: 'organizationName',
          dataIndex: 'organizationName',
          width: 100,
        },
        {
          title: '使用单位',
          key: 'userClientName',
          dataIndex: 'userClientName',
          width: 100,
        },
        {
          title: '使用部门',
          key: 'useOrganizationName',
          dataIndex: 'useOrganizationName',
          width: 100,
        },
        {
          title: '详细信息',
          key: 'info',
          dataIndex: 'info',
          width: 100,
          fixed: 'right',
        },
      ].map(item => ({ ...item, align: 'center' })),
      dataSource: [],
      assetInventoryId: null, // 资产盘点单Id
      assetInventory: {}, // 资产盘点
      assetInventoryNo: null,
      assetInventoryName: null,

      assetName: null, // 资产名称
      assetNo: null, // 资产编号
      cardNo: null, // 卡片编号

      assetInventoryLines: [],
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 1, // required
      },
      totalCount: 0,
      uuid: Uuid.createUUID(),
      useStatusList: [],
      loading: false,
    };
  },

  mounted: function () {
    var _self = this;

    // 根据UUID获取盘点单的id
    // var uuid = _self.$route.params;
    _self.assetInventoryId = this.$props.id;
    _self.getAssetInventory();

    // 固定行
    // _self.fixedTableHeader();

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

    _self.getUseStatusList();
  },
  methods: {
    selectChanged: function () {
      var _self = this;
      _self.getAssetInventoryLine();
    },

    // 从子组件获取的分页参数
    getPageParams: function (start, length) {
      this.pagination.current_page = start;
      this.pagination.per_page = length;
      this.getAssetInventoryLine();
    },
    searchDatas: function () {
      this.$refs.table.backFirstPage();
    },

    /**
     * 查询盘点单DTO,
     * 主要是获取资产盘点中的所属部门集合、使用部门集合、资产类别结合。
     * @author yangzhijie 20200806
     */
    getAssetInventory: function () {
      var _self = this;
      AssetInventoryResource.getResponseOrganizationsAndOrganizationsAndCategory(
        _self.assetInventoryId,
      ).then(
        data => {
          // console.log(data, '11111');
          _self.assetInventory = data;
          _self.assetInventoryNo = data.data.documentNo;
          _self.assetInventoryName = data.data.name;
          // 查询资产卡片的数据
          _self.getAssetInventoryLine();
        },
        xmlHttpRequest => {
          Common.processException(xmlHttpRequest);
        },
      );
    },

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

      // if (!isPageChange) {
      //   _self.pagination.current_page = 1;
      // }

      // _self.clearPageData();

      _self.loading = true;

      var parameter = {
        assetInventoryId: _self.assetInventoryId,
        assetNo:
          _self.assetNo != null && _self.assetNo.length > 0
            ? '%' + _self.assetNo + '%'
            : null,
        assetName:
          _self.assetName != null && _self.assetName.length > 0
            ? '%' + _self.assetName + '%'
            : null,
        no:
          _self.cardNo != null && _self.cardNo.length > 0
            ? '%' + _self.cardNo + '%'
            : null,
        pageStart:
          (_self.pagination.current_page - 1) * _self.pagination.per_page,
        pageLength: _self.pagination.per_page,
      };

      SqlApi.execute('20220428_145050', parameter).then(
        successData => {
          // console.log(successData, '222222');
          if (successData.errorCode == 0) {
            _self.redrawAssetInstance(successData);
            _self.dataSource = successData.dataList;
            _self.pagination.total = successData.totalSize;
          } else {
            Notify.error('盘亏数据查询异常', successData.errorMessage, true);
          }

          _self.loading = false;
        },
        errorData => {
          Common.processException(errorData);
          _self.loading = false;
        },
      );
    },

    /**
     * 重新绘制资产卡片
     * @author YangZhiJie 20200806
     */
    redrawAssetInstance: function (data) {
      var _self = this;
      if (data.dataList != null) {
        data.dataList.forEach(element => {
          element.description = '';
          element.useStatusId = '';
        });
      }
      _self.assetInventoryLines = data.dataList;
      _self.pagination.total = data.totalSize;
      _self.pagination.last_page = Math.ceil(
        data.totalSize / _self.pagination.per_page,
      );
      _self.totalCount = data.totalSize;
      // _self.fixedTableHeader();
    },

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

    /**
     * 清空界面的搜索条件
     * @author YangZhiJie 20200806
     */
    clearFilter: function () {
      this.assetName = null;
      this.assetNo = null;
      this.cardNo = null;
      this.searchDatas();
    },

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

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

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

    /**
     * 打开资产卡片的CURD窗口
     */
    openCurdWindow: function (assetInventoryLine) {
      let index = window.location.href.indexOf('#');
      let url = window.location.href.slice(0, index);
      let path =
        url +
        '#/desktop/window/window-read/view/040701/0/' +
        assetInventoryLine.assetInstanceId +
        '?currPage=1&currIndex=1&totalCount=1&uuid=' +
        Uuid.createUUID();
      // let url = Common.getRedirectUrl(
      //   '#/desktop/window/window-read/view/040701/0/' +
      //     assetInventoryLine.assetInstanceId +
      //     '?currPage=1&currIndex=1&totalCount=1&uuid=' +
      //     Uuid.createUUID(),
      // );

      window.open(path);
    },

    /**
     * 获取使用状况
     */
    getUseStatusList: function () {
      var _self = this;
      UseStatusResource.getUseStatus().then(
        data => {
          _self.useStatusList = data.datas;
        },
        xmlHttpRequest => {
          Common.processException(xmlHttpRequest);
        },
      );
    },
    next: function () {
      var _self = this;
      _self.$emit('next');
    },
    // 回到上一步
    previous: function () {
      var _self = this;
      _self.$emit('changeStep', {step:0});
    },
    /**
     * 更新资产盘点明细中的备注和使用状态。
     */
    updateAssetInventoryLine: function (assetInventoryLine, index) {
      let _self = this;
      if (
        assetInventoryLine.description == null ||
        assetInventoryLine.description === '' ||
        assetInventoryLine.useStatusId == null ||
        assetInventoryLine.useStatusId === ''
      ) {
        Notify.error('错误', '请填写"盘点使用状态"和"备注"信息\'。');
        return;
      }
      AssetInventoryLineResource.checkLossConfirm(
        assetInventoryLine.assetInventoryLineId,
        assetInventoryLine.description,
        true,
        assetInventoryLine.useStatusId,
      ).then(
        data => {
          if (data.errorCode == 0) {
            if (
              assetInventoryLine.useStatusId != null &&
              assetInventoryLine.useStatusId != ''
            ) {
              _self.assetInventoryLines.splice(index, 1);
              _self.pagination.total = _self.pagination.total - 1;
              _self.pagination.last_page = Math.ceil(
                _self.pagination.total / _self.pagination.per_page,
              );
            }
          } else {
            Notify.error('错误', '该盘点明细已经被删除，请确认');
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
  },
};
</script>

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

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

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

.grid-item-row3 {
  grid-row-start: 3;
  grid-row-end: 4;
  grid-column-start: 1;
  grid-column-end: 2;
}
</style>

<style scoped>
.common {
  margin-left: 8px;
}

.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;
}
:deep(.ant-table-pagination.ant-pagination) {
  margin: 4px 0;
}
.previousBtn {
  position: fixed;
  top: 90%;
}
</style>
