<template>
  <div style="padding: 0 10px;">
    <div class="action-buttons">
      <a-button type="primary" @click="getDatas">搜索</a-button>
      <a-button danger @click="clear">清空</a-button>
      <div>
        <a-form-item label="盘点单名称" :rules="[{ required: true, message: '请输入盘点单名称' }]">
          <a-input v-model:value="inventorySheetName" placeholder="请输入盘点单名称" />
        </a-form-item>
      </div>
      <a-button type="dashed" @click="showDetail = true">
        查看盘点清单({{ selectedRowData.length }})
      </a-button>
    </div>
    <div style="display: flex; gap: 10px;">
      <div style="width: 20%;">
        <div class="filter-section">
          <div class="category-panel">
            <a-form layout="horizontal" :model="formState" :label-col="{ style: 'width:60px' }">
              <a-form-item label="仓库" :rules="[{ required: true }]">
                <a-select v-model:value="formState.inventoryWarehouse" :options="warehouseOptions"
                  option-filter-prop="label" show-search :allow-clear="true" placeholder="请选择仓库" @change="getDatas">
                </a-select>
              </a-form-item>
              <a-form-item label="名称">
                <a-input v-model:value="formState.inventoryName" placeholder="请输入名称" @keyup.enter="getDatas" />
              </a-form-item>
              <a-form-item label="编号">
                <a-input v-model:value="formState.inventoryNo" placeholder="请输入编号" @keyup.enter="getDatas" />
              </a-form-item>
              <a-form-item label="类型">
                <a-select v-model:value="formState.inventoryType" :allow-clear="true" placeholder="请选择类型"
                  @change="getDatas">
                  <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: 80%;margin:10px 0 0 10px;">
        <CommonTable ref="tableRef" :extra-height="100" :columns="currentStockColumns" :data-source="currentStocks"
          :total="currentStocks.length" :is-select="true" :selectedKeys="selectedRowKeys"
          @get-selected="getSelectParams" :is-custom-row-click="true" @custom-row-click="openWindow"
          @getPager="getPageParams">
          <template #bodyCell="{ column, index }">
            <span v-if="column.dataIndex === 'index'">
              {{ index + 1 }}
            </span>
          </template>
        </CommonTable>
      </div>
    </div>
    <div style="display: flex; justify-content: space-between;">
      <a-button type="primary" @click="previous">上一步</a-button>
      <a-button type="primary" @click="next">
        下一步
      </a-button>
    </div>

    <Modal v-model:show="showDetail" title="盘点清单" small="true" :show-canel-button="false" :show-ok-button="false">
      <div>
        <CommonTable :columns="detailColumns" :data-source="selectedRowData" :selected-keys="selectedRowKeys"
          :extra-height="300">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'operation'">
              <a-button danger @click="deleteCountList(record.id)">
                删除
              </a-button>
            </template>
          </template>
        </CommonTable>
      </div>
      <template #footer>
        <a-button type="primary" @click="showDetail = false">关闭</a-button>
      </template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

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

export default {
  components: { CommonTable, DownOutlined, RightOutlined },
  props: {
    currentStep: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  emits: ['previous', 'next'],
  data() {
    return {
      checked: false,
      inventoryClasses: [],
      type: 0,
      warehouseId: null,
      warehouseName: null,
      checkVouchId: null,
      currentStocks: [],
      pagination: {
        total: 0,
        pageSize: 20,
        current: 1,
        start: 1,
        length: 20,
      },
      isCurrentStock: true,
      uuid: Uuid.createUUID(),
      loading: false,
      panelVisible: true,
      namePanelVisible: true,
      inventorySheetName: '',
      formState: {
        inventoryName: undefined,
        inventoryNo: undefined,
        inventoryType: undefined,
        inventoryWarehouse: undefined,
      },
      warehouseOptions: [],
      selectedRowKeys: [],
      selectedRowData: [],
      showDetail: false,
    };
  },
  computed: {
    currentStockColumns() {
      return [
        { title: '序号', dataIndex: 'index', width: 50 },
        { title: '名称', dataIndex: 'inventoryName', width: 100 },
        { title: '编号', dataIndex: 'inventoryNo', width: 120 },
        { 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' };
      });
    },
    detailColumns() {
      return [
        { title: '序号', dataIndex: 'index', width: 50 },
        { title: '名称', dataIndex: 'inventoryName', width: 100 },
        { title: '编号', dataIndex: 'inventoryNo', width: 120 },
        { title: '类型', dataIndex: 'inventoryType', width: 140 },
        { title: '操作', dataIndex: 'operation', 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() {
    if (this.currentStep && this.currentStep.assetInventoryStep4) {
      const s4 = this.currentStep.assetInventoryStep4;
      this.inventorySheetName = s4.checkVouchName || '';
      if (s4.warehouseId !== undefined && s4.warehouseId !== null) {
        this.formState.inventoryWarehouse = s4.warehouseId;
      }
      if (s4.detailList && s4.detailList.length > 0) {
        this.selectedRowData = s4.detailList;
        this.selectedRowKeys = s4.detailList.map(item => item.id);
      }
    }

    this.getCurrentStock();
    this.getWarehouseList();
  },
  methods: {

    // 获取分页参数
    getPageParams(start, length) {
      this.pagination.start = start;
      this.pagination.length = length;
      this.getCurrentStock();
    },

    // 获取选中的数据
    getSelectParams(selected) {
      this.selectedRowKeys = selected.selectedRowKeys;
      this.selectedRowData = selected.selectedRows;
    },

    // 删除已选择的盘点清单
    deleteCountList: function (data) {
      var _self = this;
      for (var i = 0; i < _self.selectedRowData.length; i++) {
        if (_self.selectedRowData[i].id == data) {
          _self.selectedRowData.splice(i, 1);
          _self.selectedRowKeys.splice(i, 1);
          break;
        }
      }
    },

    // 获取数据
    getDatas() {
      this.$refs.tableRef.backFirstPage();
    },

    // 上一步
    previous: function () {
      var data = {
        currentStep: 0,
        showPage: 0,
        assetInventoryStep4: undefined,
      };
      this.$emit('previous', data);
    },

    // 下一步
    next: function () {
      var _self = this;
      if (_self.inventorySheetName == null || _self.inventorySheetName == '') {
        Notify.error('错误', '请填写盘点单名称', 1000);
        return;
      }
      if (_self.formState.inventoryWarehouse == null || _self.formState.inventoryWarehouse == undefined) {
        Notify.error('错误', '请选择仓库', 1000);
        return;
      }
      if(!_self.selectedRowKeys || _self.selectedRowKeys.length == 0) {
        Notify.error('错误', '请选择盘点清单', 1000);
        return;
      }

      var param = {
        checkVouchName: _self.inventorySheetName,
        inventoryIds: _self.selectedRowKeys,
        warehouseId: _self.formState.inventoryWarehouse,
        detailList: _self.selectedRowData,
      };
      console.log(param, 'param');
      var data = {
        currentStep: 2,
        showPage: 4,
        assetInventoryStep4: param,
      };
      this.$emit('next', data);
    },


    // 查询数据
    getCurrentStock() {
      const _self = this;

      _self.loading = true;
      const obj = {
        inventoryName: _self.formState.inventoryName,
        inventoryNo: _self.formState.inventoryNo,
        inventoryType: _self.formState.inventoryType,
        warehouseId: _self.formState.inventoryWarehouse,
        range: {
          start: (_self.pagination.start - 1) * _self.pagination.length,
          length: _self.pagination.length,
        }
      };
      $.ajax({
        url: Common.getApiURL('InventoryResource/findInventoryByWarehouse'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(obj),
        beforeSend: request => {
          Common.addTokenToRequest(request);
        },
        success: data => {
          if (data.errorCode === 0) {
            if (data.datas && data.datas.length > 0) {
              _self.currentStocks = data.datas
              _self.pagination.total = data.total
            } else {
              _self.currentStocks = []
              _self.pagination.total = 0
            }
          } else {
            message.warning(data.errorMessage);
            _self.currentStocks = []
            _self.pagination.total = 0
          }
          // 保留 selectedRowData 为 detailList 或当前选择，不在这里覆盖
          if (_self.currentStep && _self.currentStep.assetInventoryStep4 && Array.isArray(_self.currentStep.assetInventoryStep4.inventoryIds)) {
            const ids = _self.currentStep.assetInventoryStep4.inventoryIds;
            if (!_self.selectedRowKeys.length) {
              _self.selectedRowKeys = ids.slice();
            }
          }
          _self.loading = false;
        },
        error: (XMLHttpRequest, textStatus, errorThrown) => {
          _self.loading = false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    clear() {
      this.formState = {
        inventoryName: undefined,
        inventoryNo: undefined,
        inventoryType: undefined,
        inventoryWarehouse: 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()}`,
      // );
    },

    // 获取仓库列表
    getWarehouseList: function () {
      var _self = this;
      AssetInventoryResource.getWarehouseList().then(
        successData => {
          if (successData && successData.length > 0) {
            _self.warehouseOptions = successData.map(item => {
              return {
                value: item.id,
                label: item.name,
              };
            });
          }
        },
        errorData => {
          console.log(errorData);
        },
      );
    },
  },
};
</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>