<template>
  <div class="container-fluid">
    <Navbar :title="'库存台账'" :is-go-back="false" />

    <div class="form-inline">
      <div class="form-group">
        <label class="m-label">单据日期：</label>
        <div class="input-group m-input-group">
          <DateTime
            v-model="stockLedgerDto2.startBillDate"
            class="DateTime"
          />
        </div>
      </div>
      <div class="form-group">
        <label class="m-label">~</label>
        <div class="input-group m-input-group">
          <DateTime
            v-model="stockLedgerDto2.endBillDate"
            class="DateTime"
          />
        </div>
      </div>
      <div class="form-group">
        <label class="m-label">审核日期：</label>
        <div class="input-group m-input-group">
          <DateTime
            v-model="stockLedgerDto2.startExamineDate"
            class="DateTime"
          />
        </div>
      </div>
      <div class="form-group">
        <label class="m-label">~</label>
        <div class="input-group m-input-group">
          <DateTime
            v-model="stockLedgerDto2.endExamineDate"
            class="DateTime"
          />
        </div>
      </div>
      <div class="form-group">
        <label class="m-label">存货编码：</label>
        <input
          v-model="stockLedgerDto2.startInventoryNo"
          autocomplete="off"
          type="text"
          class="form-control m-input-group"
          name="startInventoryNo"
          placeholder="请填写编码"
        />
      </div>
      <div class="form-group">
        <label class="m-label">~</label>
        <input
          v-model="stockLedgerDto2.endInventoryNo"
          autocomplete="off"
          type="text"
          class="form-control m-input-group"
          name="endInventoryNo"
          placeholder="请填写编码"
        />
      </div>

      <div class="form-group">
        <label class="m-label">仓库：</label>
        <div class="input-group m-input-group">
          <v-select
            v-model="selected"
            :options="isOptions"
            multiple="multiple"
            placeholder="请选择仓库"
            @input="warehouseSelectChanged()"
          />
        </div>
      </div>
      <button type="button" class="btn btn-info" @click="selectStockLedgers">
        确定
      </button>
    </div>

    <div v-if="stockLedgerDtos.length > 0" class="row" style="margin-top: 15px">
      <div>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>存货编码</th>
              <th>存货名称</th>
              <th>规格型号</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="stockLedgerDto in stockLedgerDtos" :key="stockLedgerDto.id">
              <td>
                <a href="javascript:void(0)" @click="onChoise($event)">{{
                  stockLedgerDto.inventoryNo
                }}</a>
              </td>
              <td>
                {{ stockLedgerDto.inventoryName1 }}
              </td>
              <td>
                {{ stockLedgerDto.inventoryType }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <VueBootstrapPagination :pagination="pagination" :callback="selectStockLedgers" />
    </div>

    <div class="row">
      <ProcessReportResultPreview
        :process-report-result="processReportResult"
      />
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { Notify } from 'pc-component-v3';







import vSelect from 'vue-select';

//获取当前登录信息
var loginInfoJson = localStorage.getItem('#LoginInfo');
var loginInfo = JSON.parse(loginInfoJson);
import 'vue-select/dist/vue-select.css';

export default {
  components: {
    vSelect,
  },

  data: function () {
    return {
      stockLedgerDto2: {
        //startBillDate: undefined,
        //endBillDate: undefined,
        //startExamineDate: undefined,
        //endExamineDate: undefined,
        warehouseIds: [],
        startInventoryNo: '',
        endInventoryNo: '',
      },
      pagination: {
        total: 0,
        per_page: 5, // required
        current_page: 1, // required
        last_page: 1, // required
      },
      processResultData: '',
      processReportResult: {},
      stockLedgerDtos: [],
      maxPage: 1,
      clientId: loginInfo.loginClientId,
      inventory: undefined,
      selected: [],
      warehouseDtos: [],
      isOptions: [],
      isShow: false,
    };
  },

  /**
   * 此内方法页面加载时调用
   */
  mounted: function () {
    this.selectWarehouseByClient();
  },

  methods: {

    /**
     * 根据部门Id查询该部门下所有仓库
     */
    selectWarehouseByClient: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('StockLedgerResource/selectWarehouseByClient'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode == 0) {
            if (data.datas.length > 0) {
              data.datas.forEach(function (item) {
                item.label = item.name;
                item.value = item.id;
              });
            }
            _self.isOptions = data.datas;
            _self.warehouseDtos = data.datas;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 从数据库分页查询出符合条件的所有存货的id和名称
     */
    selectStockLedgers: function () {
      var _self = this;
      this.warehouseSelectChanged();
      /*var whereClause = "";
            if(_self.stockLedgerDto2.startBillDate != undefined && _self.stockLedgerDto2.startBillDate != '' ) {
                if(_self.stockLedgerDto2.endBillDate != undefined && _self.stockLedgerDto2.endBillDate != '') {
                    whereClause += " and mso.documentAccountDate between '"+ _self.stockLedgerDto2.startBillDate + "' and '" +  _self.stockLedgerDto2.endBillDate +"'";
                } else {
                    whereClause += " and mso.documentAccountDate > '" + _self.stockLedgerDto2.startBillDate +"'";
                }
            } else {
                if(_self.stockLedgerDto2.endBillDate != undefined && _self.stockLedgerDto2.endBillDate != '') {
                    whereClause += " and mso.documentAccountDate < '"+ _self.stockLedgerDto2.endBillDate +"'";
                }
            }

            if(_self.stockLedgerDto2.startExamineDate != undefined && _self.stockLedgerDto2.startExamineDate != '') {
                if(_self.stockLedgerDto2.endExamineDate != undefined && _self.stockLedgerDto2.endExamineDate != '') {
                    whereClause += " and mso.verifyDate between '" + _self.stockLedgerDto2.startExamineDate + "' and '"  + _self.stockLedgerDto2.endExamineDate +"'";
                } else {
                    whereClause += " and mso.verifyDate > '" +_self.stockLedgerDto2.startExamineDate +"'";
                }
            } else {
                if(_self.stockLedgerDto2.endExamineDate != undefined && _self.stockLedgerDto2.endExamineDate != '') {
                    whereClause += " and mso.verifyDate < '"+ _self.stockLedgerDto2.endExamineDate +"'";
                }
            }

            if(!_self.stockLedgerDto2.startInventoryNo == "") {
                if(!_self.stockLedgerDto2.endInventoryNo == "") {
                    whereClause += " and it.no between " +_self.stockLedgerDto2.startInventoryNo + " and " + _self.stockLedgerDto2.endExamineDate ;
                } else {
                    whereClause += " and it.no > " + _self.stockLedgerDto2.startInventoryNo ;
                }
            } else {
                if(!_self.stockLedgerDto2.endInventoryNo == "") {
                    whereClause += " and it.no < " +  _self.stockLedgerDto2.endInventoryNo;
                }
            }

            if(_self.stockLedgerDto2.warehouseIds.length >= 1) {
                whereClause += " and wh.id in("+ _self.stockLedgerDto2.warehouseIds +")";
            }*/

      var queryParam = {
        range: {
          start:
            (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        stockLedgerDto3: _self.stockLedgerDto2,
      };
      console.log(queryParam);
      $.ajax({
        url: Common.getApiURL('StockLedgerResource/queryListInventory'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(queryParam),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },

        success: function (successData) {
          if(successData.errorCode == 0) {
            if (successData.data) {
              console.log(successData.data);
              _self.stockLedgerDtos = successData.data.result;
              _self.pagination.total = successData.data.pageCount;
              _self.pagination.last_page =
                successData.data.pageCount > _self.pagination.per_page
                  ? successData.data.pageCount % _self.pagination.per_page == 0
                    ? successData.data.pageCount % _self.pagination.per_page
                    : Math.floor(successData.data.pageCount % _self.pagination.per_page) + 1
                  : 1;
              _self.inventory = successData.data.result[0].inventoryNo;
              _self.subDatas();
              _self.isShow = true;
            } else {
              _self.processReportResult.reportResults = undefined;
              _self.inventory = undefined;
              _self.isShow = false;
              Notify.notice('提示', '查询结果为空。', false);
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 改变当前页
     */
    /*changePageNo: function(classs) {
            var _self = this;

            //var element = event.currentTarget;

            //var classs = $(element).attr("class");
            //console.log(classs);
            if(classs == 'first') {
                _self.stockLedgerDto2.pageCurrent = 1;
            }
            if(classs == 'previou') {
                if(_self.stockLedgerDto2.pageCurrent <= 1) {
                    return;
                } else {
                    _self.stockLedgerDto2.pageCurrent -= 1;
                }
            }
            if(classs == 'nextone') {
                if(_self.stockLedgerDto2.pageCurrent == _self.maxPage) {
                    return;
                } else {
                    _self.stockLedgerDto2.pageCurrent += 1;
                }
            }
            if(classs == 'last') {
                _self.stockLedgerDto2.pageCurrent = _self.maxPage;
            }
            _self.selectStockLedgers();
        },*/

    /**
     * 仓库选择改变
     */
    warehouseSelectChanged: function () {
      var _self = this;
      _self.stockLedgerDto2.warehouseIds = [];
      _self.selected.forEach(function (item) {
        _self.stockLedgerDto2.warehouseIds.push(parseInt(item.value));
      });
      console.log(_self.stockLedgerDto2.warehouseIds);
    },

    /**
     * 点击查看台账详情
     * @param {Object} event
     */
    onChoise: function (event) {
      var _self = this;
      var element = event.currentTarget;
      _self.inventory = parseInt($(element).html());
      _self.subDatas();
    },

    /**
     * 执行流程
     * @return {void}
     */
    subDatas: function () {
      var _self = this;

      //where条件判断拼接
      if (_self.stockLedgerDtos.length < 1) {
        return;
      }
      var whereClause = 'where temp1.clientId = ' + _self.clientId;
      if (_self.inventory) {
        whereClause += ' AND temp1.inventoryNo = \'' + _self.inventory + '\'';
      }

      //拼接单据时间
      if (_self.stockLedgerDto2.startBillDate) {
        if (_self.stockLedgerDto2.endBillDate) {
          whereClause +=
            ' AND temp1.documentAccountDate  between \'' +
            _self.stockLedgerDto2.startBillDate +
            '\' AND \'' +
            _self.stockLedgerDto2.endBillDate +
            '\'';
        } else {
          whereClause +=
            ' AND temp1.documentAccountDate > \'' +
            _self.stockLedgerDto2.startBillDate +
            '\'';
        }
      } else {
        if (_self.stockLedgerDto2.endBillDate) {
          whereClause +=
            ' AND temp1.documentAccountDate < \'' +
            _self.stockLedgerDto2.endBillDate +
            '\'';
        }
      }
      //拼接审核时间
      if (_self.stockLedgerDto2.startExamineDate) {
        if (_self.stockLedgerDto2.endExamineDate) {
          whereClause +=
            ' AND temp1.verifyDate  between \'' +
            _self.stockLedgerDto2.startExamineDate +
            '\' AND \'' +
            _self.stockLedgerDto2.endExamineDate +
            '\'';
        } else {
          whereClause +=
            ' AND temp1.verifyDate > \'' +
            _self.stockLedgerDto2.startExamineDate +
            '\'';
        }
      } else {
        if (_self.endExamineDate) {
          whereClause +=
            ' AND temp1.verifyDate < \'' +
            _self.stockLedgerDto2.endExamineDate +
            '\'';
        }
      }
      if (_self.stockLedgerDto2.warehouseIds.length >= 1) {
        var ids = undefined;
        _self.stockLedgerDto2.warehouseIds.forEach(function (item) {
          if (ids == undefined) {
            ids = item;
          } else {
            ids = ids + ', ' + item;
          }
        });
        whereClause += ' AND temp1.warehouseId in(' + ids + ')';
      }

      //设置参数
      _self.processResultData = {
        processReportNo: '288771',
        modelData: {
          data: {
            whereClause: {
              displayValue: [whereClause],
              fieldType: 'String',
            },
          },
        },
      };
      $.ajax({
        url: Common.getApiURL('ProcessReportResource/runProcess'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.processResultData),
        success: function (successData) {
          if(successData.errorCode == 0) {
            _self.processReportResult = successData.data;
            //请求成功后将报表数据显示
            if (
              _self.processReportResult.reportResults != undefined &&
              _self.processReportResult.reportResults.length > 0
            ) {
              _self.processReportResult.reportResults.forEach(function (
                item,
                index,
              ) {
                item.previewIndex = 1;
                if (index == 0 && _self.inventory != undefined) {
                  item.showPreview = true;
                } else {
                  item.showPreview = false;
                }
              });
            }
          }else{
            Notify.error('提示', successData.errorMessage, false);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.panel-body > div.row {
  margin-bottom: 10px;
}
.userTable {
  width: 100%;
}
.userTable > tr > td {
  padding: 5px 20px;
}

.m-label {
  width: 5em;
}

.m-input-group {
  width: 240px;
}
</style>