<template>
  <div style="padding: 0 10px;">
    <Navbar :title="'选择工装设备生成盘点详情'" :is-go-back="false" />
    <div class="action-buttons">
      <a-button type="primary" @click="searchDatas">搜索</a-button>
      <a-button type="dashed" @click="generateCheckVouchs">生成盘点明细</a-button>
      <a-button danger @click="clear">清空</a-button>
    </div>
    <div style="display: flex; gap: 10px;">
      <div style="width: 26%;">
        <div class="filter-section">
          <div class="category-panel">
            <a-form layout="horizontal" :model="formState">
              <a-form-item label="名称">
                <a-input v-model:value="formState.inventoryName" placeholder="请输入名称" @keyup.enter="getCurrentStock" />
              </a-form-item>
              <a-form-item label="编号">
                <a-input v-model:value="formState.inventoryNo" placeholder="请输入编号" @keyup.enter="getCurrentStock" />
              </a-form-item>
              <a-form-item label="类型">
                <a-select v-model:value="formState.inventoryType" placeholder="请选择类型" @change="getCurrentStock">
                  <a-select-option :value="undefined">全部工装设备</a-select-option>
                  <a-select-option value="Clamp">工装</a-select-option>
                  <a-select-option value="Instrument">设备</a-select-option>
                  <a-select-option value="FinishProduct">成品</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </div>
      <div style="width: 74%;margin:10px 0 0 10px;">
        <CommonTable
          ref="tableRef" :columns="currentStockColumns" :data-source="currentStocks"
          :total="currentStocks.length" :is-custom-row-click="true" @custom-row-click="openWindow"
        >
          <template #bodyCell="{ column, index }">
            <span v-if="column.dataIndex === 'index'">
              {{ index + 1 }}
            </span>
          </template>
        </CommonTable>
      </div>
    </div>

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

<script>
import Common from '../common/Common.js';
import { UserStorageResource, Uuid, Notify } from 'pc-component-v3';
import { message, Modal } from 'ant-design-vue';
import CommonTable from '../common/CommonTable.vue';
import { DownOutlined, RightOutlined } from '@ant-design/icons-vue';

export default {
  components: { CommonTable, DownOutlined, RightOutlined },
  data() {
    return {
      checked: false,
      inventoryClasses: [],
      type: 0,
      warehouseId: null,
      warehouseName: null,
      checkVouchId: null,
      currentStocks: [],
      pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
      },
      isCurrentStock: true,
      uuid: Uuid.createUUID(),
      loading: false,
      panelVisible: true,
      namePanelVisible: true,
      formState: {
        inventoryName: '',
        inventoryNo: '',
        inventoryType: undefined,
      },
    };
  },
  computed: {
    currentStockColumns() {
      return [
        { title: '序号', dataIndex: 'index', width: 50 },
        { title: '名称', dataIndex: 'inventoryName', width: 100 },
        { title: '编号', dataIndex: 'inventoryNo', width: 100 },
        { title: '类型', dataIndex: 'inventoryType', width: 140 },
        { title: '默认货位', dataIndex: 'inventoryPosition', width: 140 },
        { title: '实际货位', dataIndex: 'inventoryActulPosition', width: 140 },
        { title: '所在仓库', dataIndex: 'inventoryWarehouse', width: 100 },
      ].map(item => {
        return { ...item, align: 'center' };
      });
    },
  },

  created() {
    const _self = this;
    const uuid = this.$route.params.uuid;
    UserStorageResource.uniqueByKey(uuid + '_modelData').then(
      str => {
        if (str.data) {
          const modelData = JSON.parse(str.data);
          _self.checkVouchId = modelData.id;
          _self.warehouseId = modelData.data.warehouse.id;
          _self.warehouseName = modelData.data.warehouse.displayValue[0];
        }
      },
      errorData => {
        Common.processException(errorData);
      },
    );
  },
  mounted() {
    this.getCurrentStock();
  },
  methods: {

    searchDatas() {
      this.getCurrentStock();
    },

    getCurrentStock() {
      const _self = this;

      _self.loading = true;
      const obj = {
        inventoryName: _self.formState.inventoryName,
        inventoryNo: _self.formState.inventoryNo,
        inventoryType: _self.formState.inventoryType,
      };
      $.ajax({
        url: Common.getApiURL('InventoryResource/checkVouchFindInventoryByCondition'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(obj),
        beforeSend: request => {
          Common.addTokenToRequest(request);
        },
        success: data => {
          if (data.errorCode === 0) {
            _self.currentStocks = data.datas;
          } else {
            message.warning(data.errorMessage);
          }
          _self.loading = false;
        },
        error: (XMLHttpRequest, textStatus, errorThrown) => {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    generateCheckVouchs() {
      const _self = this;
      let information = '';
      if (!_self.formState.inventoryType && _self.formState.inventoryName === '' && _self.formState.inventoryNo === '') {
        information =
          `您确定要将仓库：【${_self.warehouseName}】下所有物料生成盘点明细`;
      } else {
        information = '您确定要根据选择的过滤条件生成对应的盘点明细';
      }
      Modal.confirm({
        title: '确认生成盘点明细',
        content: `${information} 吗？如果"是"的话，请点击"确定"按钮，否则点击"取消"按钮`,
        onOk() {
          _self.loading = true;
          const obj = {
            checkVouchId: _self.checkVouchId,
            inventoryIds: _self.currentStocks.map(item => item.id),
          };
          $.ajax({
            url: Common.getApiURL(
              'CheckVouchResource/generateCheckVouchsByInventorys',
            ),
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(obj),
            beforeSend: request => {
              Common.addTokenToRequest(request);
            },
            success: data => {
              if (data.errorCode === 0) {
                message.success(data.errorMessage);
              } else {
                message.warning(data.errorMessage);
              }
              _self.loading = false;
            },
            error: (XMLHttpRequest, textStatus, errorThrown) => {
              _self.loading = false;
              Common.processException(XMLHttpRequest, textStatus, errorThrown);
            },
          });
        },
        onCancel() { },
      });
    },
    clear() {
      this.formState = {
        inventoryName: '',
        inventoryNo: '',
        inventoryType: undefined,
      };
      this.getCurrentStock();
    },
    openWindow(item) {
      console.log(item);
      // window.open(
      //   `#/desktop/window1/window-read/view/050405/0/${item.id}?currPage=1&currIndex=1&totalCount=1&uuid=${Uuid.createUUID()}`,
      // );
    },
    togglePanel() {
      this.panelVisible = !this.panelVisible;
    },
    toggleNamePanel() {
      this.namePanelVisible = !this.namePanelVisible;
    },
  },
};
</script>

<style scoped>
.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.panel-header {
  background-color: #fafafa;
  padding: 10px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.selected-positions {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.filter-section {
  margin-top: 20px;
}

.category-panel,
.position-panel {
  margin-top: 20px;
}

.inventory-table {
  margin-top: 20px;
}

.pagination-info {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
:deep(.ant-form-item){
  margin-bottom: 10px !important;
}
:deep(.ant-form-item-label > label) {
  font-size: 14px !important;
  font-weight: 600 !important;
}
</style>