<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类索引" prop="moduleIndex">
        <el-input
          v-model="queryParams.moduleIndex"
          placeholder="2位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="子类路径" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="正式为树结构选择"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="属性列表" prop="attributes">
        <el-input
          v-model="queryParams.attributes"
          placeholder="请输入属性列表"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <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-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['moduleConf:productConf:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['moduleConf:productConf:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['moduleConf:productConf:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['moduleConf:productConf:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['moduleConf:productConf:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table :loading="loading" :data="sysList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="conf_id" :show-overflow-tooltip="true" v-if="columns[0].visible" prop="confId" />-->
      <el-table-column label="分类索引" align="center" :show-overflow-tooltip="true" v-if="columns[1].visible" prop="moduleIndex" />
      <el-table-column label="子类路径" align="center" :show-overflow-tooltip="true" v-if="columns[2].visible" prop="category" />
      <el-table-column label="属性列表" align="center" :show-overflow-tooltip="true" v-if="columns[3].visible" prop="attributes" />
      <el-table-column label="版本号" align="center" :show-overflow-tooltip="true" v-if="columns[4].visible" prop="version" />
      <el-table-column label="删除标记" align="center" :show-overflow-tooltip="true" v-if="columns[5].visible" prop="deleteFlag">
        <template slot-scope="scope">
          <span v-if="scope.row.deleteFlag === 0">未删除</span>
          <span v-else-if="scope.row.deleteFlag === 1">已删除</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" :show-overflow-tooltip="true" v-if="columns[6].visible" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">禁用</span>
          <span v-else-if="scope.row.status === 1">启用</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <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="['moduleConf:productConf:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['moduleConf:productConf: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"
    />

    <!-- 添加或修改单品配置表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="conf_id" prop="confId">-->
<!--          <el-input v-model="form.confId" placeholder="请输入conf_id" />-->
<!--        </el-form-item>-->
        <el-form-item label="分类索引" prop="moduleIndex">
          <el-input v-model="form.moduleIndex" placeholder="请输入分类索引" />
        </el-form-item>
        <el-form-item label="子类路径" prop="category">
          <el-input v-model="form.category" placeholder="请输入子类路径" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input-number v-model="form.version" :min="0" placeholder="请输入版本号" style="width: 100%" />
        </el-form-item>
        <el-form-item label="删除标记" prop="deleteFlag">
          <el-radio-group v-model="form.deleteFlag">
            <el-radio :label="0">未删除</el-radio>
            <el-radio :label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="属性设置" prop="attributes">
          <div style="width: 100%;">
            <el-table :data="attrList" border style="width: 100%" size="small" max-height="400">
              <el-table-column label="属性名" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attrName" placeholder="请输入属性名" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="属性标识" width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.attr" placeholder="请输入属性标识" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="类型" width="280">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.type" size="small">
                   <el-radio-button label="int">整数</el-radio-button>
                    <el-radio-button label="double">小数</el-radio-button>
                    <el-radio-button label="string">字符串</el-radio-button>
                    <el-radio-button label="datatime">日期</el-radio-button>
                    <el-radio-button label="decimal">金额</el-radio-button>

                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column label="描述" min-width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.description" placeholder="请输入描述" size="small" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="removeAttrRow(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addAttrRow">添加属性</el-button>
            </div>
          </div>
        </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 + '?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">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的单品配置表数据
          </div>
          <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 { listProductConf, getProductConf, delProductConf, addProductConf, updateProductConf } from "@/api/system/moduleConf/productConf";
import { getToken } from "@/utils/auth";

export default {
  name: "ProductConf",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单品配置表表格数据
      sysList: [],
      // 表格列信息
      columns: [
        { key: 0, label: 'conf_id', visible: false },
        { key: 1, label: '分类索引', visible: true },
        { key: 2, label: '子类路径', visible: true },
        { key: 3, label: '属性列表', visible: true },
        { key: 4, label: '版本号', visible: true },
        { key: 5, label: '删除标记', visible: true },
        { key: 6, label: '状态', visible: true }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // confId: null,
        moduleIndex: null,
        category: null,
        attributes: null
      },
      // 表单参数
      form: {},
      // 属性列表数据
      attrList: [],
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的单品配置表数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/test/sys/importData"
      },
      // 表单校验
      rules: {
        // confId: [
        //   { required: true, message: "conf_id不能为空", trigger: "blur" }
        // ],
        category: [
          { required: true, message: "子类路径不能为空", trigger: "blur" }
        ],
        attributes: [
          { required: false, message: "请设置属性", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询单品配置表列表 */
    getList() {
      this.loading = true;
      listProductConf(this.queryParams).then(response => {
        this.sysList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        moduleIndex: null,
        category: null,
        attributes: null,
        version: null,
        deleteFlag: 0,
        status: 1
      };
      this.attrList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.confId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 新增时添加一个默认空行
      this.addAttrRow();
      this.open = true;
      this.title = "添加单品配置表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const confId = row.confId || this.ids
      getProductConf(confId).then(response => {
        this.form = response.data;
        // 解析attributes JSON字符串为attrList
        if (this.form.attributes) {
          try {
            this.attrList = JSON.parse(this.form.attributes);
            // 确保是数组格式
            if (!Array.isArray(this.attrList)) {
              this.attrList = [];
            }
          } catch (e) {
            console.error("解析attributes失败:", e);
            this.attrList = [];
          }
        } else {
          this.attrList = [];
        }
        this.open = true;
        this.title = "修改单品配置表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = this.buildSubmitData();
          if (submitData.confId != null) {
            updateProductConf(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProductConf(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sysIds = row.confId || this.ids;
      this.$modal.confirm('是否确认删除单品配置表编号为"' + sysIds + '"的数据项？').then(function() {
        return delProductConf(sysIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('test/sys/export', {
        ...this.queryParams
      }, `sys_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "单品配置表导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "test/sys/importTemplate",
        {},
        "sys_template_" + 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.$modal.closeLoading()
      this.getList();
    },
    buildSubmitData() {
      // 只保留实体类中定义的字段，过滤掉其他字段
      const data = {};
      // 只添加存在的字段，避免提交 undefined 或空字符串
      if (this.form.moduleIndex !== undefined && this.form.moduleIndex !== null && this.form.moduleIndex !== "") {
        data.moduleIndex = this.form.moduleIndex;
      }
      if (this.form.category !== undefined && this.form.category !== null && this.form.category !== "") {
        data.category = this.form.category;
      }
      if (this.form.version !== undefined && this.form.version !== null) {
        data.version = this.form.version;
      }
      if (this.form.deleteFlag !== undefined && this.form.deleteFlag !== null) {
        data.deleteFlag = this.form.deleteFlag;
      }
      if (this.form.status !== undefined && this.form.status !== null) {
        data.status = this.form.status;
      }
      // 将attrList序列化为JSON字符串
      if (this.attrList && this.attrList.length > 0) {
        data.attributes = JSON.stringify(this.attrList);
      } else {
        data.attributes = null;
      }
      // 如果是修改操作，需要包含 confId
      if (this.form.confId !== null && this.form.confId !== undefined && this.form.confId !== "") {
        data.confId = this.form.confId;
      }
      return data;
    },
    // 添加属性行
    addAttrRow() {
      this.attrList.push({
        attrName: "",
        attr: "",
        type: "字符串",
        description: ""
      });
    },
    // 删除属性行
    removeAttrRow(index) {
      this.attrList.splice(index, 1);
    },
    // 提交上传文件
    submitFileForm() {
      this.$modal.loading("导入中请稍后")
      this.$refs.upload.submit();
    }
  }
};
</script>

