<template>
  <div>
    <div class="flex-container">
      <!-- 头部搜索区域 -->
      <div class="flex-header">
        <StockOutPrepareTemplateHeader active-index="1" />
        <a-form layout="inline" class="search-form">
          <a-form-item label="项目事件">
            <a-select
              v-model:value="projectItemId"
              style="width: 220px"
              show-search
              allow-clear
              @change="handleProjectItemChange"
            >
              <a-select-option
                v-for="item in projectItems"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="仓库">
            <a-select
              v-model:value="warehouseId"
              style="width: 220px"
              allow-clear
              @change="handleWarehouseChange"
            >
              <a-select-option
                v-for="item in warehouses"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="需求模板">
            <a-select
              v-model:value="stockOutPrepateTemplateId"
              style="width: 220px"
              show-search
              allow-clear
              @change="handleTemplateChange"
            >
              <a-select-option
                v-for="item in stockOutPrepateTemplateNames"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button @click="queryLines">查询</a-button>
            <a-button @click="clear">清空</a-button>
            <a-button type="primary" @click="save">确定领料</a-button>
          </a-form-item>
        </a-form>
      </div>
      <!-- 表格区域 -->
      <div class="flex-content">
        <a-table
          :columns="columns"
          :data-source="pageStockOutPrepateTemplates"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'pickQuantity'">
              <a-input-number
                v-model:value="record.pickQuantity"
                :min="0"
                :max="record.currentStockCanPickQuantity"
                @change="handlePickQuantityChange(record)"
              />
            </template>
          </template>
        </a-table>
      </div>
      <!-- 分页信息区域 -->
      <div class="flex-footer">
        <div class="pull-left">
          <span>
            第{{ (pagination.current - 1) * pagination.pageSize + 1 }}-{{ pagination.current * pagination.pageSize }}条,
            共计{{ pagination.total }}条,
            每页显示
          </span>
          <a-select
            v-model:value="pagination.pageSize"
            style="width: 80px"
            @change="gridSizeSelect"
          >
            <a-select-option value="10">10</a-select-option>
            <a-select-option value="20">20</a-select-option>
            <a-select-option value="50">50</a-select-option>
          </a-select>
          <span>条</span>
        </div>
        <div class="pull-right">
          <a-pagination
            v-if="pagination.total > 0"
            :current="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @change="getDatas"
          />
        </div>
      </div>
    </div>
    <!-- 加载状态 -->
    <div>
      <a-spin v-if="loading" />
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import StockOutPrepareResource from '../api/wms/StockOutPrepareResource.js';
import StockOutPrepateTemplateResource from '../api/wms/StockOutPrepateTemplateResource.js';
import StockOutPrepareTemplateHeader from './StockOutPrepareTemplateHeader.vue';

export default {
  components: {
    StockOutPrepareTemplateHeader,
  },
  data() {
    return {
      stockOutPrepateTemplates: [],
      pageStockOutPrepateTemplates: [],
      stockOutPrepateTemplateId: undefined,
      warehouseId: undefined,
      projectItemId: undefined,
      pagination: {
        total: 0,
        pageSize: Common.pageSize,
        current: 1,
      },
      projectItems: [],
      warehouses: [],
      stockOutPrepateTemplateNames: [],
      loading: false,
    };
  },
  computed: {
    columns() {
      return [
        {
          dataIndex: 'inventoryNo',
          title: '物料编码',
        },
        {
          dataIndex: 'inventoryName',
          title: '物料名称',
        },
        {
          dataIndex: 'inventoryType',
          title: '规格型号',
        },
        {
          dataIndex: 'currentStockQuantity',
          title: '库存数量',
        },
        {
          dataIndex: 'currentStockOutQuantity',
          title: '待出库数量',
        },
        {
          dataIndex: 'currentStockCanPickQuantity',
          title: '可领用数量',
        },
        {
          dataIndex: 'quantity',
          title: '需求数量',
        },
        {
          dataIndex: 'pickQuantity',
          title: '领用数量',
        },
      ];
    },
  },
  watch: {
    'pagination.pageSize': function (curVal, oldVal) {
      if (curVal !== undefined) {
        this.getDatas();
      }
    },
  },
  created() {
    if (!window.localStorage) {
      alert('浏览器不支持localstorage');
    } else {
      const storage = window.localStorage;
      this.warehouseId = storage.getItem('warehouseId');
      this.warehouseName = storage.getItem('warehouseName');
      this.projectItemId = storage.getItem('projectItemId');
      this.projectItemName = storage.getItem('projectItemName');
      this.stockOutPrepateTemplateId = storage.getItem('stockOutPrepateTemplateId');
      this.stockOutPrepateTemplateName = storage.getItem('stockOutPrepateTemplateName');
    }
  },
  mounted() {
    this.loadSelectProjectItem();
    this.loadSelectWarehouse();
    this.loadSelectTemplate();
  },
  methods: {
    // 加载项目事件选项
    loadSelectProjectItem() {
      const _self = this;
      $.ajax({
        url: Common.getApiURL('ProjectItemResource/queryByCondition'),
        dataType: 'json',
        type: 'get',
        data: { name: '' },
        beforeSend: Common.addTokenToRequest,
        success(data) {
          if (data.errorCode === 0) {
            _self.projectItems = data.datas;
          }
        },
        error(errorData) {
          Common.processException(errorData);
        },
      });
    },
    // 加载仓库选项
    loadSelectWarehouse() {
      const _self = this;
      $.ajax({
        url: Common.getApiURL('WarehouseResource/queryByCondition'),
        dataType: 'json',
        type: 'get',
        data: { name: '' },
        beforeSend: Common.addTokenToRequest,
        success(data) {
          if (data.errorCode === 0) {
            _self.warehouses = data.datas;
          }
        },
        error(errorData) {
          Common.processException(errorData);
        },
      });
    },
    // 加载需求模板选项
    loadSelectTemplate() {
      const _self = this;
      $.ajax({
        url: Common.getApiURL('StockOutPrepateTemplateResource/queryByCondition'),
        dataType: 'json',
        type: 'get',
        data: { name: '' },
        beforeSend: Common.addTokenToRequest,
        success(data) {
          if (data.errorCode === 0) {
            _self.stockOutPrepateTemplateNames = data.datas;
          }
        },
        error(errorData) {
          Common.processException(errorData);
        },
      });
    },
    // 修改每页显示数量
    gridSizeSelect(newPageSize) {
      this.pagination.pageSize = newPageSize;
      this.pagination.current = 1;
      this.pageStockOutPrepateTemplates = [];
      this.stockOutPrepateTemplates = [];
      this.queryLines();
    },
    // 查询领料模板详情
    queryLines() {
      if (!this.projectItemId) {
        Common.showDialog('提示', '请选择项目事件', 'error');
        return;
      }
      if (!this.warehouseId) {
        Common.showDialog('提示', '请选择仓库', 'error');
        return;
      }
      if (!this.stockOutPrepateTemplateId) {
        Common.showDialog('提示', '请选择需求模板', 'error');
        return;
      }
      const param = {
        warehouseId: this.warehouseId,
        projectItemId: this.projectItemId,
        stockOutPrepateTemplateDtoId: this.stockOutPrepateTemplateId,
      };
      this.loading = true;
      this.pageStockOutPrepateTemplates = [];
      StockOutPrepateTemplateResource.queryStockOutPrepateTemplateDto(param)
        .then(successData => {
          if (successData.errorCode === 0) {
            this.pagination.total = successData.data.stockOutPrepateTemplateLineDtos.length;
            this.stockOutPrepateTemplates = successData.data.stockOutPrepateTemplateLineDtos;
            this.getDatas();
          } else {
            Notify.error('提示', successData.errorMessage, false);
          }
        })
        .catch(errorData => {
          Common.processException(errorData);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取分页数据
    getDatas() {
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const end = start + this.pagination.pageSize;
      if (this.pageStockOutPrepateTemplates.length > 0) {
        this.pageStockOutPrepateTemplates.forEach(item => {
          this.stockOutPrepateTemplates[item.index].pickQuantity = item.pickQuantity;
        });
      }
      this.pageStockOutPrepateTemplates = [];
      for (let i = 0; i < this.stockOutPrepateTemplates.length; i++) {
        if (i >= start && i < end) {
          const obj = {
            ...this.stockOutPrepateTemplates[i],
            index: i,
          };
          this.pageStockOutPrepateTemplates.push(obj);
        }
      }
    },
    // 清空数据
    clear() {
      this.pageStockOutPrepateTemplates = [];
      this.stockOutPrepateTemplates = [];
    },
    // 提交领料数据
    save() {
      const currentStock = [];
      let num = 0;
      let num3 = 0;
      let num5 = 0;
      this.getDatas();
      this.stockOutPrepateTemplates.forEach(item => {
        if (item.pickQuantity === undefined || item.pickQuantity === '') {
          num++;
        }
        if (item.pickQuantity <= 0 && item.currentStockCanPickQuantity > 0) {
          num5++;
        }
        if (item.pickQuantity > item.currentStockCanPickQuantity) {
          num3++;
        } else {
          currentStock.push(item);
        }
      });
      if (!this.projectItemId) {
        Common.showDialog('提示', '请选择项目事件', 'error');
        return;
      }
      if (!this.warehouseId) {
        Common.showDialog('提示', '请选择仓库', 'error');
        return;
      }
      if (!this.stockOutPrepateTemplateId) {
        Common.showDialog('提示', '请选择需求模板', 'error');
        return;
      }
      if (num > 0) {
        Common.showDialog('提示', '请填写领用数量', 'error');
        return;
      }
      if (num3 > 0) {
        Common.showDialog('提示', '领用数量大于可领数量', 'error');
        return;
      }
      if (num5 > 0) {
        Common.showDialog('提示', '填写的领用数量必须大于零', 'error');
        return;
      }
      const param = {
        projectItemId: this.projectItemId,
        warehouseId: this.warehouseId,
        stockOutPrepateTemplateId: this.stockOutPrepateTemplateId,
        pickingCarDtoList: currentStock,
      };
      this.loading = true;
      if (currentStock.length > 0) {
        StockOutPrepareResource.saveByTemplate(param)
          .then(successData => {
            if (successData.errorCode === 0) {
              Notify.success('成功', '领料成功', 4000);
              this.pageStockOutPrepateTemplates = [];
              this.stockOutPrepateTemplates = [];
            } else {
              Notify.error('提示', successData.errorMessage, false);
            }
          })
          .catch(errorData => {
            Common.processException(errorData);
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.loading = false;
        Common.showDialog('提示', '请选择要提交的内容', 'error');
      }
    },
    // 表格分页变化处理
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.getDatas();
    },
    // 项目事件选择变化处理
    handleProjectItemChange(value) {
      this.projectItemId = value;
      this.clear();
    },
    // 仓库选择变化处理
    handleWarehouseChange(value) {
      this.warehouseId = value;
      this.clear();
    },
    // 需求模板选择变化处理
    handleTemplateChange(value) {
      this.stockOutPrepateTemplateId = value;
      this.clear();
    },
    // 领用数量变化处理
    handlePickQuantityChange(record) {
      // 可根据需求添加额外逻辑
    },
  },
};
</script>

<style scoped>
.flex-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 85px);
}

.flex-header {
  flex: 0 0 100px;
}

.flex-footer {
  margin-top: 0.8em;
  flex: 0 0 35px;
}

.flex-content {
  margin-top: 0.8em;
  flex: 1;
  overflow: auto;
  width: 100%;
}

.pull-left {
  float: left;
}

.pull-right {
  float: right;
}
</style>