<template>
  <a-layout class="container">
    <Navbar title="调拨单" :is-go-back="true" />
    
    <a-card :bordered="false" class="form-card">
      <a-form layout="inline">
        <a-form-item label="原项目事件">
          <a-select
            v-model:value="projectItemId"
            :options="projectOptions"
            show-search
            :filter-option="false"
            placeholder="请选择原项目事件"
            @search="handleSearchProject"
            @change="handleProjectChange"
          />
        </a-form-item>

        <a-button type="primary" @click="addition">提交</a-button>
      </a-form>

      <a-table
        :data-source="pageProjectItemAdjusts"
        :columns="columns"
        :pagination="pagination"
        row-key="inventoryId"
        class="data-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'selection'">
            <a-checkbox 
              v-model:checked="record.checked"
              @change="handleCheckChange(record)"
            />
          </template>
          <template v-else-if="column.dataIndex === 'quantity'">
            <a-input-number
              v-model:value="record.quantity"
              :min="0"
              :max="record.projectItemCanAdjustQuantity"
              @change="handleQuantityChange(record)"
            />
          </template>
          <template v-else>
            {{ record[column.dataIndex] }}
          </template>
        </template>
      </a-table>

      <a-modal
        v-model:visible="modal"
        title="提交调拨单"
        :footer="null"
      >
        <a-form layout="vertical">
          <a-form-item label="目标项目事件">
            <a-select
              v-model:value="targetProjectItemId" 
              :options="projectOptions"
              show-search
              :filter-option="false"
              placeholder="请选择目标项目事件"
              @search="handleSearchProject"
              @change="handleTargetChange"
            />
          </a-form-item>

          <a-table
            :data-source="editProjectItemAdjusts"
            :columns="editColumns"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'selection'">
                <a-radio 
                  :checked="projectItemAdjustId === record.id"
                  @change="handleSelectAdjust(record)"
                />
              </template>
            </template>
          </a-table>

          <div class="modal-footer">
            <a-button @click="cancel">取消</a-button>
            <a-button type="primary" @click="picking">确定</a-button>
          </div>
        </a-form>
      </a-modal>
    </a-card>

    <Loading v-if="loading" />
  </a-layout>
</template>

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

export default {
  components: {
    
  },
  data: function () {
    return {
      columns: [
        { title: '选择', dataIndex: 'selection' },
        { title: '物料编码', dataIndex: 'inventoryNo' },
        { title: '物料名称', dataIndex: 'inventoryName' },
        { title: '规格型号', dataIndex: 'inventoryType' },
        { title: '物料数量', dataIndex: 'projectItemQuantity' },
        { title: '待调拨数量', dataIndex: 'projectItemAdjustQuantity' },
        { title: '可调拨数量', dataIndex: 'projectItemCanAdjustQuantity' },
        { title: '数量', dataIndex: 'quantity' },
      ],
      projectItemAdjusts: [],
      pageProjectItemAdjusts: [], //每页显示的数据
      projectItemId: undefined, //原项目事件
      projectItemAdjustId: undefined, //选择的调拨单
      targetProjectItemId: undefined, //目标项目事件
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      //调拨主单分页情况
      pagination2: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },

      checked: false,
      editProjectItemAdjusts: [], //还在编辑状态下的调拨单
      projectItemAdjustNo: undefined, //选择的调拨单的单据号
      loading: false,
      modal: false,
      projectOptions: [], //项目事件下拉框
    };
  },



  mounted: function () {
  },

  methods: {
    /**
             * 全选和反选
             */
    selectAll: function () {
      var _self = this;
      if (_self.checked) {
        for (var i = 0; i < _self.pageProjectItemAdjusts.length; i++) {
          _self.pageProjectItemAdjusts[i].checked = true;
        }
      } else {
        for (var j = 0; j < _self.pageProjectItemAdjusts.length; j++) {
          _self.pageProjectItemAdjusts[j].checked = false;
        }
      }
    },
    /**
             * 点击选择调拨单事件
             */
    setProjectItemAdjust: function (index) {
      var _self = this;
      _self.projectItemAdjustId = _self.editProjectItemAdjusts[index].id;
      _self.projectItemAdjustNo = _self.editProjectItemAdjusts[index].documentNo;
      for (var i = 0; i < _self.editProjectItemAdjusts.length; i++) {
        if (i == index) {
          _self.editProjectItemAdjusts[index].isChecked = true;
        } else {
          _self.editProjectItemAdjusts[i].isChecked = false;
        }
      }
    },
    handleSearchProject: async function(value) {
      try {
        const response = await $.ajax({
          url: Common.getApiURL('ProjectItemResource/queryByCondition'),
          data: { name: value },
          beforeSend: request => Common.addTokenToRequest(request),
        });
      
        this.projectOptions = response.datas.map(item => ({
          label: item.name,
          value: item.id,
        }));
      } catch (error) {
        Common.processException(error);
      }
    },

    // 修改项目选择处理
    handleProjectChange(value) {
      this.projectItemId = value;
      this.pageProjectItemAdjusts = [];
      this.pagination.current_page = 1;
      this.getProjectItemAdjusts();
      this.getEditProjectItemAdjusts();
    },

    // 修改目标项目选择处理
    handleTargetChange(value) {
      this.targetProjectItemId = value;
      this.getEditProjectItemAdjusts();
    },


    /**
             * 查询还在编辑状态下的调拨单
             * 
             */
    getEditProjectItemAdjusts: function () {
      var _self = this;
      var param = {
        start: (_self.pagination2.current_page - 1) * _self.pagination2.per_page,
        length: _self.pagination2.per_page,
        sourceProjectItemId: _self.projectItemId,
        targetProjectItemId: _self.targetProjectItemId,

      };

      ProjectItemAdjustResource.list(param).then(successData => {
        _self.pagination2.total = successData.totalSize;
        _self.editProjectItemAdjusts.splice(0, _self.editProjectItemAdjusts.length);
        var obj = {
          id: null,
          documentNo: '新建调拨单单',
          isChecked: false,
        };
        _self.editProjectItemAdjusts.push(obj);
        for (var i = 0; i < successData.dataList.length; i++) {
          successData.dataList[i].isChecked = false;
          _self.editProjectItemAdjusts.push(successData.dataList[i]);
        }
        _self.pagination2.last_page = Math.ceil(successData.totalSize / successData.range.length);
      }, errorData => {

        Common.processException(errorData);
      });

    },


    //查询项目事件下的物料详情
    getProjectItemAdjusts: function () {
      var _self = this;
      if (_self.projectItemId == undefined) {
        Common.showDialog('提示', '请选择原项目事件', 'error');
        return;
      }
      var param = {
        start: (_self.pagination.current_page - 1) * _self.pagination.per_page,
        length: 1,
        sourceProjectItemId: _self.projectItemId,
      };
      _self.loading=true;

      ProjectItemAdjustResource.list(param).then(successData => {
        _self.pagination.total = successData.totalSize;
        if (successData.dataList != null && successData.dataList.length > 0) {
          _self.projectItemAdjusts = successData.dataList[0].projectItemAdjustLineDtos;
        }
        _self.pagination.last_page = Math.ceil(successData.totalSize / _self.pagination.per_page);
        _self.getDatas();
        _self.loading=false;
      }, errorData => {
        _self.loading=false;
        Common.processException(errorData);
      });

    },

    getDatas: function () {
      var _self = this;
      var start = (_self.pagination.current_page - 1) * _self.pagination.per_page;
      var end = start + _self.pagination.per_page;
      console.log(start + '___' + end);
      //将录入的数据导过来
      if (_self.pageProjectItemAdjusts != null && _self.pageProjectItemAdjusts.length > 0) {
        for (var j = 0; j < _self.pageProjectItemAdjusts.length; j++) {
          var index = _self.pageProjectItemAdjusts[j].index;
          if (_self.pageProjectItemAdjusts[j].quantity != null) {
            _self.projectItemAdjusts[index].quantity = _self.pageProjectItemAdjusts[j].quantity;
          }
        }
      }

      //清空这样显示数据
      _self.pageProjectItemAdjusts.splice(0, _self.pageProjectItemAdjusts.length);

      //重新生成另一页的数据
      for (var i = 0; i < _self.projectItemAdjusts.length; i++) {
        if (i >= start && i < end) {
          var checked = false;
          if (_self.projectItemAdjusts[i].quantity != null && _self.projectItemAdjusts[i].quantity > 0) {
            checked = true;
          }
          var obj = {
            checked: checked,
            inventoryName: _self.projectItemAdjusts[i].inventoryName,
            inventoryNo: _self.projectItemAdjusts[i].inventoryNo,
            inventoryType: _self.projectItemAdjusts[i].inventoryType,
            projectItemQuantity: _self.projectItemAdjusts[i].projectItemQuantity,
            projectItemAdjustQuantity: _self.projectItemAdjusts[i].projectItemAdjustQuantity,
            projectItemCanAdjustQuantity: _self.projectItemAdjusts[i].projectItemCanAdjustQuantity,
            quantity: _self.projectItemAdjusts[i].quantity,
            index: i,
          };
          _self.pageProjectItemAdjusts.push(obj);
        }

      }

    },


    /**
             * [addition 领料]
             * @return {[type]} [description]
             */
    addition: function () {
      var _self = this;
      _self.modal = true;
    },

    /**
             * 取消领料操作
             */
    cancel: function () {
      var _self = this;
      _self.modal = false;
      _self.targetProjectItemId = undefined; //选择目标项目事件
      _self.projectItemAdjustNo = undefined; //选择目标项目事件的单据号
      for (var i = 0; i < _self.editProjectItemAdjusts.length; i++) {
        _self.editProjectItemAdjusts[i].isChecked = false;

      }
    },



    /**
             * 提交前进行判断，是否在已选择的领料单中继续添加
             */
    picking: function () {
      var _self = this;
      _self.modal = false;
      if (_self.projectItemId == undefined) {
        Common.showDialog('提示', '请选择原项目事件', 'error');
        return;
      }
      if (_self.targetProjectItemId == undefined) {
        Common.showDialog('提示', '请选择目标项目事件', 'error');
        return;
      }
      if (_self.projectItemAdjustId != null) {
        Notify.show({
          title: '确认在原有的调拨单中继续添加',
          message: '您确定要将选择的物料添加到调拨单(单据号)' + _self.projectItemAdjustNo + '中吗？如果\\"是\\"的话，请点击\\"确定\\"按钮，否则点击\\"取消\\"按钮',
          buttons: [
            {
              label: '确定',
              cssClass: 'btn-primary',
              action: function (dialogItself) {
                dialogItself.close();
                //判断选择原项目事件与目标项目事件是否相同

                if (_self.projectItemId == _self.targetProjectItemId) {
                  Common.showDialog('提示', '选择的原项目事件与目标项目事件相同', 'error');
                  return;
                } else {
                  _self.submitStock();
                }
              },
            }, {
              label: '取消',
              action: function (dialogItself) {
                dialogItself.close();
              },
            }],
        });
      } else {
        _self.submitStock();
      }
    },

    //提交
    submitStock: function () {
      var currentStock = [];
      var num = 0;
      var num3 = 0;
      var num5 = 0;
      var _self = this;
      _self.getDatas();
      this.projectItemAdjusts.forEach(function (item) {

        if (item.quantity != undefined && item.quantity != '' && item.quantity > 0 && item.quantity <= item.projectItemCanAdjustQuantity) {
          currentStock.push(item);
        }

      });

      if (_self.projectItemId == _self.targetProjectItemId) {
        Common.showDialog('提示', '目标项目事件不能与原项目事件相同', 'error');
        return;
      }
      if (currentStock == null || currentStock.length == 0) {
        Common.showDialog('提示', '物料数量不能全部空或者全部小于等于0.同时填写的数量不能大于可调拨的数量。', 'error');
        return;
      }
      _self.loading=true;
      if (currentStock.length > 0) {

        var param = {
          sourceProjectItemId: _self.projectItemId,
          targetProjectItemId: _self.targetProjectItemId,
          id: _self.projectItemAdjustId,
          projectItemAdjustLineDtos: currentStock,
        };

        ProjectItemAdjustResource.create(param).then(successData => {
          _self.stockOutPrepareSaveResult = successData;
          Notify.success('成功', '调拨成功', 4000);
          _self.getProjectItemAdjusts();
          _self.clear();
          _self.loading=false;
        }, errorData => {
          _self.loading=false;
          Common.processException(errorData);
        });

      } else {
        _self.loading=false;
        Common.showDialog('提示', '请选择要提交的内容', 'error');
      }
    },
    /**
             * 清空赋值的参数
             */
    clear: function () {
      var _self = this;
      _self.targetProjectItemId = undefined; //选择的调拨单
      _self.pageProjectItemAdjusts.splice(0, _self.pageProjectItemAdjusts.length); //清空显示页面数据
      _self.getProjectItemAdjusts();
      _self.getEditProjectItemAdjusts();
      //				_self.stockOutPrepareDocumentNo = undefined;  //选择领料单的单据号
      for (var i = 0; i < _self.editProjectItemAdjusts.length; i++) {
        _self.editProjectItemAdjusts[i].isChecked = false;

      }
      //_self.getDatas();				
    },

    formatDate: function (date) {
      if (date != '' && date != null) {
        var dateStr = date + '';
        return dateStr.substr(0, 10);
      } else {
        return '';
      }
    },
    /**
             * 根据文本中是否有内容判断是否选中
             * @param {Object} item
             */
    checkBoxChange: function (item) {
      if (item.quantity == undefined || item.quantity == '') {
        item.checked = false;
      }
      if (item.quantity > item.projectItemCanAdjustQuantity) {
        Common.showDialog('提示', '物料编码：' + item.inventoryNo + ',物料名称：' + item.inventoryName + '。填写的数量大于可调拨数量。提交时会自动过滤掉此物料。', 'error');
        item.checked = false;
      } else {
        item.checked = true;
      }
    },

  },

};
</script>

<style scoped>
.form-card {
  margin-top: 24px;
  padding: 16px;
}

.data-table {
  margin-top: 24px;
}

.modal-footer {
  margin-top: 24px;
  text-align: right;
}

.ant-form-item {
  margin-right: 24px;
}
</style>