<template>
  <div class="task-management">
    <!-- 配置抽屉 -->
    <el-drawer
      title="页面配置"
      :visible.sync="configDrawer"
      direction="rtl"
      size="300px"
    >
      <div class="drawer-content">
        <h3 class="drawer-section-title">显示字段</h3>
        <el-checkbox-group v-model="visibleColumns" class="column-checkboxes">
          <el-checkbox
            v-for="col in allColumns"
            :key="col.prop"
            :label="col.prop"
          >
            {{ col.label }}
          </el-checkbox>
        </el-checkbox-group>

        <h3 class="drawer-section-title">表格密度</h3>
        <el-radio-group v-model="tableSize" class="density-radio">
          <el-radio-button label="medium">默认</el-radio-button>
          <el-radio-button label="small">紧凑</el-radio-button>
          <el-radio-button label="mini">超紧凑</el-radio-button>
        </el-radio-group>
      </div>
    </el-drawer>

    <!-- 搜索区域 -->
    <div class="search-container" :class="{ collapsed: !showSearch }">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="84px" :size="formSize">
        <div class="search-form-content" :class="{ 'is-advanced': isAdvanced }">
          <template v-if="isAdvanced">
            <el-form-item label="物料编号" prop="goodsId">
              <el-input
                v-model="queryParams.goodsId"
                placeholder="请输入物料编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="goodsName">
              <el-input
                v-model="queryParams.goodsName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="单位" prop="goodsUnit">
              <el-input
                v-model="queryParams.goodsUnit"
                placeholder="请输入单位"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料类型" prop="goodsType">
              <el-input
                v-model="queryParams.goodsType"
                placeholder="请输入物料类型"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="通用容器类型" prop="normalVehicleType">
              <el-input
                v-model="queryParams.normalVehicleType"
                placeholder="请输入通用容器类型"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料状态" prop="goodsStatus">
              <el-input
                v-model="queryParams.goodsStatus"
                placeholder="请输入物料状态"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="最近更新用户" prop="lastUpdateUser">
              <el-input
                v-model="queryParams.lastUpdateUser"
                placeholder="请输入最近更新用户"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </template>
        </div>
        <div class="search-form-footer">
          <div class="left">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button
              type="text"
              @click="toggleAdvanced"
              class="advanced-toggle"
            >
              {{ isAdvanced ? '收起' : '展开' }}
              <i :class="['el-icon-arrow-' + (isAdvanced ? 'up' : 'down')]"></i>
            </el-button>
          </div>
          <div class="right">
            <el-button
              icon="el-icon-s-operation"
              @click="toggleSearch"
              circle
              size="mini"
            ></el-button>
          </div>
        </div>
      </el-form>
    </div>
    <!-- 工具栏 -->
    <div class="toolbar-container">
      <div class="left">
        <el-button-group>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['app:goods:add']"
          >新增</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['app:goods:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['app:goods:remove']"
          >删除</el-button>
        </el-button-group>
      </div>
      <div class="right">
        <el-tooltip content="导出数据" placement="top">
          <el-button
            type="warning"
            icon="el-icon-download"
            @click="handleExport"
            v-hasPermi="['app:goods:export']"
          >导出</el-button>
        </el-tooltip>
        <el-tooltip content="导入数据" placement="top">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleImport"
            v-hasPermi="['app:goods:import']"
          >导入</el-button>
        </el-tooltip>
        <el-tooltip content="列设置" placement="top">
          <el-button
            icon="el-icon-setting"
            @click="configDrawer = true"
            circle
          ></el-button>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-button
            icon="el-icon-refresh"
            @click="getList"
            circle
          ></el-button>
        </el-tooltip>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="messageList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
        @sort-change="handleSortChange"
        :size="tableSize"
        :max-height="tableHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left"/>
        <template v-for="col in tableColumns">
          <el-table-column
            :key="col.prop"
            :label="col.label"
            :prop="col.prop"
            :width="col.width"
            :min-width="col.minWidth"
            align="center"
            :sortable="col.sortable"
            :show-overflow-tooltip="col.tooltip"
            v-if="isColumnVisible(col.prop)"
          >
            <template slot-scope="scope">
              <template v-if="col.type === 'dict'">
                <dict-tag :options="dict.type[col.dict]" :value="scope.row[col.prop]"/>
              </template>
              <template v-if="col.prop === 'sts'">
                <dict-tag :options="dict.type.kc_sts" :value="scope.row.sts"/>
              </template>
              <template v-else-if="col.type === 'number'">
                <span class="number-column">{{ scope.row[col.prop] }}</span>
              </template>
              <template v-else-if="col.type === 'datetime'">
                <span>{{ parseTime(scope.row[col.prop]) }}</span>
              </template>
              <template v-else>
                {{ scope.row[col.prop] }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="物料名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="单位" prop="goodsUnit">
          <el-input v-model="form.goodsUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="物料类型" prop="goodsType">
          <el-input v-model="form.goodsType" placeholder="请输入物料类型" />
        </el-form-item>
        <el-form-item label="通用容器类型" prop="normalVehicleType">
          <el-input v-model="form.normalVehicleType" placeholder="请输入通用容器类型" />
        </el-form-item>
        <el-form-item label="物料状态" prop="goodsStatus">
          <el-input v-model="form.goodsStatus" placeholder="请输入物料状态" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="最近更新用户" prop="lastUpdateUser">
          <el-input v-model="form.lastUpdateUser" placeholder="请输入最近更新用户" />
        </el-form-item>
        <el-form-item label="最近更新时间" prop="lastUpdateTime">
          <el-date-picker clearable
                          v-model="form.lastUpdateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择最近更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {addMessage, updateMessage} from "@/api/system/message";
import {getToken} from "@/utils/auth";
import {addGoods, delGoods, getGoods, listGoods, updateGoods} from "@/api/system/goods";

export default {
  name: "goods",
  dicts: ['kc_sts','site_type'],
  data() {
    return {
      upload: {
        open: false,
        title: '上传文件',
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/app/goods/importData', // 确保这里填写正确的上传URL
        isUploading: false
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否显示高级搜索
      isAdvanced: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      messageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      daterangeCreateTime: [],
      // 配置抽屉显示状态
      configDrawer: false,
      // 表格大小
      tableSize: 'small',
      // 表单大小
      formSize: 'small',
      // 表格高度
      tableHeight: window.innerHeight - 300,
      // 可见列
      visibleColumns: [],
      // 所有列配置
      allColumns: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        goodsName: null,
        goodsUnit: null,
        goodsType: null,
        normalVehicleType: null,
        goodsStatus: null,
        lastUpdateUser: null,
        lastUpdateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsUnit: [
          { required: true, message: "单位,不能为空不能为空", trigger: "blur" }
        ],
        goodsStatus: [
          { required: true, message: "物料状态，不可为空不能为空", trigger: "blur" }
        ],


      }
    };
  },
  computed: {
    // 当前可见的表格列
    tableColumns() {
      return this.allColumns.filter(col => this.isColumnVisible(col.prop));
    }
  },
  created() {
    this.getList();
    this.initTableHeight();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 初始化表格高度
    initTableHeight() {
      this.tableHeight = window.innerHeight - 300;
    },
    // 处理窗口大小变化
    handleResize() {
      this.tableHeight = window.innerHeight - 300;
    },
    // 检查列是否可见
    isColumnVisible(prop) {
      return this.visibleColumns.includes(prop);
    },
    // 切换搜索区域显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    /** 查询任务明细
     列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listGoods(this.queryParams).then(response => {
        this.allColumns = response.columns
        console.log('All columns:', this.allColumns);
        this.allColumns.forEach((column) => {
          this.visibleColumns.push(column.prop)
        });
        this.messageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsName: null,
        goodsUnit: null,
        goodsType: null,
        normalVehicleType: null,
        goodsStatus: null,
        remark: null,
        lastUpdateUser: null,
        lastUpdateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialCode =  this.ids
      getGoods(materialCode).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialCodes = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除物料编号为"' + materialCodes + '"的数据项？').then(function () {
        return delGoods(materialCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.upload.title = '导入';
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/app/goods/importTemplate', {}, `bas_goods_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true },
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 排序触发事件 */
    handleSortChange({ prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
      this.getList();
    },
    /** 切换高级搜索 */
    toggleAdvanced() {
      this.isAdvanced = !this.isAdvanced;
    },
  }
};
</script>
<style lang="scss" scoped>
.task-management {
  padding: 16px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .search-container {
    background: #fff;
    border-radius: 4px;
    padding: 24px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    transition: all 0.3s ease;

    &.collapsed {
      padding: 0;
      height: 0;
      overflow: hidden;
      margin-bottom: 8px;
    }

    .search-form-content {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 16px;
      transition: all 0.3s;
    }

    .search-form-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 16px;
      border-top: 1px solid #ebeef5;
    }
  }

  .toolbar-container {
    background: #fff;
    padding: 8px 16px;
    border-radius: 4px;
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

    .left {
      display: flex;
      gap: 8px;
    }

    .right {
      display: flex;
      gap: 8px;
    }
  }

  .table-container {
    background: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

    .el-table {
      // 数字列样式
      .number-column {
        font-family: Monaco, Menlo, Consolas, "Courier New", monospace;
        color: #409eff;
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  // 配置抽屉样式
  .drawer-content {
    padding: 20px;

    .drawer-section-title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      margin: 0 0 16px;

      &:not(:first-child) {
        margin-top: 24px;
      }
    }

    .column-checkboxes {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .density-radio {
      width: 100%;

      .el-radio-button {
        margin-right: 8px;
      }
    }
  }
}
</style>
