<template>
  <Navbar :title="'货位调整'" :is-go-back="false" />
  <div>
    <a-form :colon="false">
      <a-row :gutter="[8, 0]" justify="space-start">
        <a-col>
          <a-form-item label="调整前货位" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-select
              v-model:value="positionBeforeId" placeholder="请选择调整前货位" class="w-full"
              @change="handlePositionBeforeChange"
            >
              <a-select-option v-for="item in positionBefores" :key="item.positionId" :value="item.positionId">
                {{ item.positionNo }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="调整后货位" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-select v-model:value="positionAfterId" placeholder="请选择调整后货位" class="w-full">
              <a-select-option v-for="item in positionAfters" :key="item.positionId" :value="item.positionId">
                {{ item.positionNo }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="搜索内容" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-input
              v-model:value="queryMessage" placeholder="请输入工具的中文名称或SKU或序列号" class="w-full"
              @press-enter="handleSearch"
            />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="工具类型" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-select v-model:value="selectType" class="w-full" @change="changeSelectType">
              <a-select-option value="1">RFID管理</a-select-option>
              <a-select-option value="2">非RFID管理</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button type="primary" @click="submitBefore">确认调整</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table
      :columns="columns" :data-source="selectType === '2' ? currentStockDtos : inventoryInstanceDatas"
      :pagination="pagination" :loading="loading" row-key="id" @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'image'">
          <img
            :src="Common.getThumbnailImageSrc(className, record.imageName)" class="image"
            @click="$refs.imagePreview.preview(className, record.imageName)"
          />
        </template>
        <template v-if="column.key === 'adjustQuantity' && selectType === '2'">
          <a-input-number v-model="record.adjustQuantity" :min="0" @change="checkBoxChange(record)" />
        </template>
      </template>
    </a-table>

    <a-modal v-model:visible="modal" title="调整确认" :footer="null">
      <p>您确认要进行货位调整吗？</p>
      <div class="modal-footer">
        <a-button @click="closeModal">取消</a-button>
        <a-button type="primary" @click="handleSubmit">确认</a-button>
      </div>
    </a-modal>

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

<script>
import Common from '../common/Common.js';
import CurrentStockResource from '../api/wms/CurrentStockResource.js';
import AdjustPositionResource from '../api/wms/AdjustPositionResource.js';
import InventoryInstanceResource from '../api/common/InventoryInstanceResource.js';

export default {
  data() {
    return {
      formLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      },
      checked: false,
      positionBefores: [],
      positionBeforeId: null,
      positionAfterId: null,
      positionAfters: [],
      queryMessage: '',
      currentStockDtos: [],
      inventoryInstanceDatas: [],
      pagination: {
        total: 0,
        pageSize: Common.pageSize,
        current: 1,
      },
      className: 'com.leanwo.prodog.model.common.Inventory',
      selectType: '1',
      loading: false,
      modal: false,
      columns: [
        {
          title: '序号',
          key: 'index',
          render: (text, record, index) => index + 1,
        },
        {
          title: '图片',
          key: 'image',
        },
        {
          title: '中文名称',
          dataIndex: 'inventoryName',
          key: 'inventoryName',
        },
        {
          title: 'SKU',
          dataIndex: 'inventoryCode',
          key: 'inventoryCode',
        },
        {
          title: '序列号',
          dataIndex: 'no',
          key: 'no',
        },
        {
          title: '库存数量',
          dataIndex: 'stockQuantity',
          key: 'stockQuantity',
        },
        {
          title: '调整数量',
          key: 'adjustQuantity',
        },
      ],
    };
  },
  mounted() {
    this.loadSelectPositionBefore();
    this.loadSelectPositionAfter();
  },
  methods: {
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.handleSearch();
    },
    filterOption(input, option) {
      return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    handlePositionBeforeChange() {
      this.handleSearch();
    },
    handleSearch() {
      if (this.selectType === '1') {
        this.queryInventoryInstance();
      } else {
        this.queryInventory();
      }
    },
    changeSelectType() {
      this.handleSearch();
    },
    checkBoxChange(item) {
      if (!item.adjustQuantity || item.adjustQuantity === 0) {
        item.checked = false;
      } else {
        item.checked = true;
      }
    },
    closeModal() {
      this.modal = false;
    },
    submitBefore() {
      if (!this.positionBeforeId || !this.positionAfterId) {
        Notify.error('错误', '调整前货位与调整后货位不允许为空', false);
        return;
      }
      if (this.positionBeforeId === this.positionAfterId) {
        Notify.error('错误', '调整前货位与调整后货位不能相同', false);
        return;
      }
      const data =
        this.selectType === '2' ? this.currentStockDtos : this.inventoryInstanceDatas;
      let checkCount = 0;
      let falseData = true;
      data.forEach(item => {
        if (item.checked) {
          checkCount++;
          if (this.selectType === '2' && (!item.adjustQuantity || item.adjustQuantity <= 0)) {
            falseData = false;
          }
        }
      });
      if (!falseData) {
        Notify.error('错误', '调整数量必须大于0', false);
        return;
      }
      if (checkCount > 0) {
        this.modal = true;
      } else {
        Notify.error('错误', '请选择最少一条数据进行提交', false);
      }
    },
    handleSubmit() {
      this.modal = false;
      if (this.selectType === '2') {
        this.submit1();
      } else {
        this.submit2();
      }
    },
    submit1() {
      const currentStockDtoBs = this.currentStockDtos.filter(item => item.checked);
      this.loading = true;
      $.ajax({
        url: Common.getApiURL('AdjustPositionResource/saveAdjustPosition'),
        type: 'post',
        data: {
          currentStockDtoBs: JSON.stringify(currentStockDtoBs),
          positionBeforeId: this.positionBeforeId,
          positionAfterId: this.positionAfterId,
        },
        beforeSend: request => Common.addTokenToRequest(request),
        success: successData => {
          this.loading = false;
          if (successData.errorCode === 0) {
            if (successData.data) {
              Notify.success('成功', '操作成功', false);
              this.queryInventory();
            }
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
    submit2() {
      const inventoryInstanceDtos = this.inventoryInstanceDatas.filter(item => item.checked);
      this.loading = true;
      $.ajax({
        url: Common.getApiURL('AdjustPositionResource/saveAdjustPosition2'),
        type: 'post',
        data: {
          inventoryInstanceDtos: JSON.stringify(inventoryInstanceDtos),
          positionBeforeId: this.positionBeforeId,
          positionAfterId: this.positionAfterId,
        },
        beforeSend: request => Common.addTokenToRequest(request),
        success: successData => {
          this.loading = false;
          if (successData.errorCode === 0) {
            if (successData.data) {
              Notify.success('成功', '操作成功', false);
              this.queryInventoryInstance();
            }
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
    queryInventory() {
      this.loading = true;
      const queryMessage = $.trim(this.queryMessage);
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const length = this.pagination.pageSize;
      $.ajax({
        url: Common.getApiURL('CurrentStockResource/queryCurrentStockByPosition'),
        type: 'get',
        data: {
          positionBeforeId: this.positionBeforeId,
          queryMessage,
          start,
          length,
        },
        beforeSend: request => Common.addTokenToRequest(request),
        success: successData => {
          this.loading = false;
          if (successData.errorCode === 0) {
            if (successData.datas) {
              this.currentStockDtos = successData.datas.map(item => ({
                ...item,
                checked: false,
              }));
              this.pagination.total = successData.total;
            }
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
    queryInventoryInstance() {
      this.loading = true;
      const queryMessage = $.trim(this.queryMessage);
      const start = (this.pagination.current - 1) * this.pagination.pageSize;
      const length = this.pagination.pageSize;
      $.ajax({
        url: Common.getApiURL('InventoryInstanceResource/queryByPosition'),
        type: 'get',
        data: {
          positionBeforeId: this.positionBeforeId,
          queryMessage,
          start,
          length,
        },
        beforeSend: request => Common.addTokenToRequest(request),
        success: successData => {
          this.loading = false;
          if (successData.errorCode === 0) {
            if (successData.datas) {
              this.inventoryInstanceDatas = successData.datas.map(item => ({
                ...item,
                checked: false,
              }));
              this.pagination.total = successData.total;
            }
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
    loadSelectPositionBefore() {
      this.loading = true;
      $.ajax({
        url: Common.getApiURL('positionResource/queryByCondition'),
        type: 'get',
        beforeSend: request => Common.addTokenToRequest(request),
        success: data => {
          this.loading = false;
          if (data.errorCode === 0) {
            this.positionBefores = data.datas.map(item => ({
              positionId: item.positionId,
              positionNo: item.positionNo,
            }));
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
    loadSelectPositionAfter() {
      this.loading = true;
      $.ajax({
        url: Common.getApiURL('positionResource/queryByCondition'),
        type: 'get',
        beforeSend: request => Common.addTokenToRequest(request),
        success: data => {
          this.loading = false;
          if (data.errorCode === 0) {
            this.positionAfters = data.datas.map(item => ({
              positionId: item.positionId,
              positionNo: item.positionNo,
            }));
          }
        },
        error: errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      });
    },
  },
};
</script>

<style scoped>
.adjust-positions-container {
  padding: 24px;
}

.search-form {
  margin-bottom: 24px;
}

.image {
  width: 40px;
  height: 40px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}

.horizontal-form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.w-full {
  width: 160px;
}

:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}

:deep(.ant-form-item-label > label) {
  font-size: 14px !important;
  font-weight: 600 !important;
}
</style>