<template>
  <div class="table-page-container">
    <div ref="lxHeader">
      <lx-header icon="md-apps" text="固定资产管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <DatePicker v-model="select.purchase_date" type="year" placeholder="购置年份" style="width: 200px;margin-right: 10px;" clearable />
            <Input v-model="select.asset_number" style="width: 200px;margin-right: 10px;" placeholder="资产编号" clearable />
            <Input v-model="select.name" style="width: 200px;margin-right: 10px;" placeholder="物资名称" clearable />
            <Input v-model="select.usage_department" style="width: 200px;margin-right: 10px;" placeholder="使用科室" clearable />
            <Input v-model="select.custodian" style="width: 200px;margin-right: 10px;" placeholder="保管人" clearable />
            <Button type="primary" style="margin-left: 8px;" @click="resetSelect">重置</Button>
            <Button type="primary" style="margin-left: 8px;" @click="getWarehouseList">查询</Button>
            <Button type="primary" style="margin-left: 8px;" @click="handleAdd">添加</Button>

            <!-- <Button icon="ios-add" type="primary" style="margin-left: 10px;"
              @click="$refs['imports'].show()">导入</Button> -->
          </div>
        </slot>
      </lx-header>
    </div>

    <div class="table-flex-content">
      <xy-table :list="list" :total="total" @pageSizeChange="pageSizeChange" @pageIndexChange="pageChange"
        :table-item="table" size="medium" :height="tableHeight" style="border-radius: 10px; overflow: hidden; box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08); width: 100%;">
        <template v-slot:btns>
          <el-table-column fixed="right" label="操作" align="center" min-width="140" header-align="center" class-name="table-col-action">
            <template slot-scope="scope">
              <div style="display: flex; gap: 8px; justify-content: center;">
                <Button type="primary" size="small" style="border-radius: 6px;" @click="$refs.addFixAssets.open('editor', scope.row)">编辑</Button>
                <Button type="error" style="margin-left: 0; border-radius: 6px;" size="small" ghost @click="delRow(scope.row.id)">删除</Button>
              </div>
            </template>
          </el-table-column>
        </template>
      </xy-table>
      <AddFixAssets ref="addFixAssets" :warehouseList="list" @refresh="getWarehouseList"></AddFixAssets>
    </div>
  </div>
</template>

<script>
  import {
    destroy,
    index
  } from "@/api/system/baseForm.js"
  import { getWarehouseTypeList, destroyWarehouseType } from '@/api/system/warehouse'
  import { getStorehouseTypeList } from '@/api/system/storehouseType'
  import AddWarehouse from './components/addWarehouse.vue'
  import {
    getparameteritem
  } from "@/api/system/dictionary.js"
  import AddFixAssets from './components/addFixAssets.vue'
  import { getFixAssetsList, destroyFixAssets, saveFixAssets } from '@/api/system/fixAssets.js'
  export default {
    components: {
      AddFixAssets,
    },
    data() {
      return {
        select: {
          page: 1,
          page_size: 10,
          purchase_date: '',
          asset_number: '',
          name: '',
          usage_department: '',
          custodian: '',
          table_name: 'materialstorages',
          area:''
        },
        typeList: [],
        nameList: [],
        areaList:[],
        total: 0,
        list: [],
        table: [
          { label: '序号', type: 'index', width: 60 },
          { label: '资产编号', prop: 'asset_number', minWidth: 120 },
          { label: '物资名称', prop: 'name', minWidth: 120 },
          { label: '国标分类', prop: 'category', minWidth: 120 },
          { label: '类别名称', prop: 'category_name', minWidth: 120 },
          { label: '物资型号', prop: 'model', minWidth: 120 },
          { label: '数量', prop: 'quantity', minWidth: 80 },
          { label: '计量单位', prop: 'unit', minWidth: 80 },
          { label: '购置时间', prop: 'purchase_date', minWidth: 120 },
          { label: '使用期限', prop: 'expire_date', minWidth: 100 },
          { label: '原值', prop: 'value', minWidth: 100 },
          { label: '使用科室', prop: 'usage_department', minWidth: 120 },
          { label: '保管人', prop: 'custodian', minWidth: 100 },
          { label: '存放地点', prop: 'storage_location', minWidth: 120 },
          { label: '所属库', prop: 'storehouse', minWidth: 120 },
          { label: '使用方向', prop: 'usage_direction', minWidth: 120 },
          { label: '备注', prop: 'remarks', minWidth: 120 }
        ],
        tableHeight: 550 // 默认高度
      }
    },
    created() {
      this.getWarehouseList()
    },
    mounted() {
      this.calcTableHeight();
      window.addEventListener('resize', this.calcTableHeight);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.calcTableHeight);
    },
    methods: {
      async getTypeList() {
        try {
          const formData = new FormData();
          formData.append('page', 1);
          formData.append('page_size', 1000);
          const res = await getStorehouseTypeList(formData);
          this.typeList = res.data;
        } catch (e) {
          this.$message.error('获取仓库类型列表失败');
        }
      },
      async getWarehouseListByType(typeId) {
        try {
          const res = await index({
            table_name: 'materialstorages',
            filter: [{
              key: 'storehouses_id',
              op: 'eq',
              value: typeId
            }]
          });
          this.nameList = res.data;
        } catch (e) {
          this.$message.error('获取仓库列表失败');
        }
      },
      handleTypeChange(typeId) {
        this.select.type = typeId;
        this.select.name = ''; // 清空仓库名称选择
        this.getWarehouseListByType(typeId);
      },
      async getWarehouseList() {
        try {
          const formData = new FormData();
          formData.append('page', this.select.page);
          formData.append('page_size', this.select.page_size);
          // 组装filter
          let filterIdx = 0;
          if (this.select.purchase_date) {
            const year = typeof this.select.purchase_date === 'string'
              ? this.select.purchase_date.slice(0, 4)
              : (this.select.purchase_date.getFullYear
                  ? String(this.select.purchase_date.getFullYear())
                  : '');
            formData.append(`filter[${filterIdx}][key]`, 'purchase_date');
            formData.append(`filter[${filterIdx}][op]`, 'like');
            formData.append(`filter[${filterIdx}][value]`, year);
            filterIdx++;
          }
          if (this.select.asset_number) {
            formData.append(`filter[${filterIdx}][key]`, 'asset_number');
            formData.append(`filter[${filterIdx}][op]`, 'like');
            formData.append(`filter[${filterIdx}][value]`, this.select.asset_number);
            filterIdx++;
          }
          if (this.select.name) {
            formData.append(`filter[${filterIdx}][key]`, 'name');
            formData.append(`filter[${filterIdx}][op]`, 'like');
            formData.append(`filter[${filterIdx}][value]`, this.select.name);
            filterIdx++;
          }
          if (this.select.usage_department) {
            formData.append(`filter[${filterIdx}][key]`, 'usage_department');
            formData.append(`filter[${filterIdx}][op]`, 'like');
            formData.append(`filter[${filterIdx}][value]`, this.select.usage_department);
            filterIdx++;
          }
          if (this.select.custodian) {
            formData.append(`filter[${filterIdx}][key]`, 'custodian');
            formData.append(`filter[${filterIdx}][op]`, 'like');
            formData.append(`filter[${filterIdx}][value]`, this.select.custodian);
            filterIdx++;
          }
          const res = await getFixAssetsList(formData);
          this.list = res.data;
          this.total = res.total;
        } catch (e) {
          this.$message.error('获取库房列表失败');
        }
      },
      pageChange(e) {
        this.select.page = e
        this.getWarehouseList()
      },
      pageSizeChange(e){
        this.select.page_size = e
        this.getWarehouseList()
      },
      delRow(id) {
        if (id) {
          this.$confirm('确认要删除该库房吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              await destroyFixAssets(id);
              this.$message.success('删除成功');
              this.getWarehouseList();
            } catch (e) {
              this.$message.error('删除失败');
            }
          });
        }
      },
      calcTableHeight() {
        const header = this.$refs.lxHeader ? this.$refs.lxHeader.offsetHeight : 0;
        const windowHeight = window.innerHeight;
        const minTableHeight = 600; // 至少能展示一页数据
        this.tableHeight = Math.max(windowHeight - header - 100, minTableHeight);
      },
      resetSelect() {
        this.select = {
          page: 1,
          page_size: 10,
          purchase_date: '',
          asset_number: '',
          name: '',
          usage_department: '',
          custodian: '',
          table_name: 'materialstorages',
          area: ''
        };
        this.nameList = [];
        this.getWarehouseList();
      },
      handleAdd() {
        if (this.$refs.addFixAssets) {
          this.$refs.addFixAssets.resetForm();
          this.$refs.addFixAssets.open('add');
        }
      },
    }
  }
</script>

<style>
.table-page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
  background: #f5f7fa;
}
.table-flex-content {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
.el-table th {
  background: #f5f7fa !important;
  color: #333;
  font-weight: bold;
  font-size: 15px;
}
.el-table td {
  font-size: 14px;
  height: 48px;
}
.el-table {
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
  height: 100%;
}
/* 让操作列自动填充剩余空间 */
.table-col-action {
  flex: 1 !important;
}
</style>
