<template>
  <div>
    <!-- 产业导向管理--目录管理 -->
    <div class="headerbox">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="7rem">
        <el-row>
          <el-col :span="9">
            <el-form-item label="上楼目录类别" prop="slmllb" style="width: 100%;">
              <el-input v-model="queryParams.slmllb" placeholder="请输入上楼目录类别" clearable style="width: 26.5rem;"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="工业大类" prop="industryCategory" style="width: 100%;">
              <el-input v-model="queryParams.industryCategory" placeholder="请输入工业大类" clearable style="width: 20.5rem;"
                @keyup.enter.native="handleQuery" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="产业" prop="industry" style="width: 100%;">
              <el-input v-model="queryParams.industry" placeholder="请输入产业" clearable style="width: 20.5rem;"
                @keyup.enter.native="handleQuery" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="9">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker v-model="queryParams.updateTimeRange" type="daterange" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd" :style="{ width: '100%' }" start-placeholder="开始日期" end-placeholder="结束日期"
                range-separator="至" clearable @change="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item style="margin-left: 2.5rem;">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 表格内容区 -->
    <div class="tablebox">
      <!-- 标签行 -->
      <div class="tablehead">
        <div class="tablebtntwo">
          <div>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:post:add']">新增</el-button>
          </div>
          <div class="tablebtn">
            <el-button type="primary" size="mini" @click="handleExport"
              v-hasPermi="['system:post:export']">导出</el-button>
            <el-button type="primary" size="mini" @click="handleImport">批量导入</el-button>
          </div>
        </div>
      </div>
      <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName">
        <el-table-column label="序号" align="center" prop="id" />
        <el-table-column label="上楼目录类别" align="center" prop="slmllb" />
        <el-table-column label="工业大类" align="center" prop="gydl" />
        <el-table-column label="产业" align="center" prop="cy" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:post:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:post:remove']">删除</el-button>
          </template>
        </el-table-column>
      </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="40rem" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="7rem">
        <el-form-item label="上楼目录类别" prop="slmllb">
          <el-select v-model="form.slmllb" placeholder="请选择上楼目录类别" style="width: 100%;">
            <el-option v-for="dict in dict.type.shangloumulu" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工业大类" prop="industryCategory">
          <el-input v-model="form.industryCategory" placeholder="请输入工业大类" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="产业" prop="industry">
          <el-input v-model="form.industry" placeholder="请输入产业" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker v-model="form.updateTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
            style="width: 100%;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </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"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :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>
        </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 { addCatalog, deleteCatalog, editCatalog, getAllCatalogs } from '@/api/ManageApi/index';

export default {
  dicts: [
    'shangloumulu'
  ],
  name: "Catalog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 目录表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        slmllb: undefined, // 修改为 slmllb
        industryCategory: undefined,
        industry: undefined,
        updateTimeRange: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        slmllb: undefined, // 修改为 slmllb
        industryCategory: undefined,
        industry: undefined,
        updateTime: undefined,
        remark: undefined
      },
      // 表单校验
      rules: {
        slmllb: [
          { required: true, message: "上楼目录类别不能为空", trigger: "change" }
        ],
        industryCategory: [
          { required: true, message: "工业大类不能为空", trigger: "blur" },
          { max: 50, message: "工业大类长度不能超过50个字符", trigger: "blur" }
        ],
        industry: [
          { required: true, message: "产业不能为空", trigger: "blur" },
          { max: 50, message: "产业长度不能超过50个字符", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "change" }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/gysl/ml/importData"
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    // 导入
    handleImport() {
      this.upload.open = true;
    },
    // 文件上传中处理
    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();
    },
    /** 查询目录列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        startTime: this.queryParams.updateTimeRange ? this.queryParams.updateTimeRange[0] : undefined,
        endTime: this.queryParams.updateTimeRange ? this.queryParams.updateTimeRange[1] : undefined
      };
      getAllCatalogs(params).then(response => {
        this.postList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('API Request Error:', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        postName: undefined,
        industryCategory: undefined,
        industry: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增目录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const catalogId = row.id || this.ids;
      editCatalog({ id: catalogId }).then(response => {
        const data = response.data;
        // 确保 updateTime 只包含日期部分
        if (data.updateTime) {
          data.updateTime = data.updateTime.split(' ')[0]; // 去掉时间部分
        }
        this.form = {
          id: data.id,
          postName: data.slmllb,
          industryCategory: data.gydl,
          industry: data.cy,
          updateTime: data.updateTime,
          remark: data.remark
        };
        this.open = true;
        this.title = "修改目录";
      }).catch(error => {
        console.error('API Request Error:', error);
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = {
            id: this.form.id,
            slmllb: this.form.postName,
            gydl: this.form.industryCategory,
            cy: this.form.industry,
            updateTime: this.form.updateTime,
            remark: this.form.remark
          };
          if (this.form.id !== undefined) {
            editCatalog(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('API Request Error:', error);
            });
          } else {
            addCatalog(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('API Request Error:', error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const catalogIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除目录编号为"' + catalogIds + '"的数据项？' + '删除这条信息之后有可能找不回来了，请思考一下哟！').then(() => {
        return deleteCatalog(catalogIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gysl/ml/export', {
        ...this.queryParams
      }, `catalog_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>

<style scoped>
.headerbox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablebox {
  background-color: #fff;
  border-radius: .5rem;
  padding: 1rem;
  margin: .5rem;
  border: 1px solid #eee;
}

.tablehead {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.headbtn {
  display: flex;
}

.tablebtntwo {
  margin-top: 1rem;
  margin-bottom: 1rem;
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.tablebtn {
  display: flex;
  gap: .5rem;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

</style>