<template>
  <div>
    <div class="product-content">
      <div class="content-header">
        <div class="search-area">
          <el-form :inline="true" :model="queryForm" ref="searchForm">
            <el-form-item label="产品应用编号">
              <el-select 
                v-model="queryForm.type" 
                placeholder="请选择产品"
                @change="handleTypeChange"
              >
                <el-option
                  v-for="(item, index) in productList"
                  :key="index"
                  :value="item.dcp_id"
                  :label="item.dcp_name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 修改JSON数据显示部分 -->
      <div v-if="parsedSpecifications.length" class="specifications-list">
        <el-card 
          v-for="(spec, index) in parsedSpecifications" 
          :key="index" 
          class="spec-card"
        >
          <div class="spec-header">
            <span class="spec-title">{{ spec.psp_name  }}</span>
            <el-button 
              type="primary" 
              size="small" 
              @click="handleUseSpec(spec)"
            >
              使用此规格
            </el-button>
          </div>
          <div class="spec-content">
            <el-tag 
              size="small"
              type="info"
              class="spec-tag"
            >
              {{ spec.psp_name }}: {{ spec.ps_name || '-' }}
            </el-tag>
            <div class="spec-details">
              <div v-if="spec.psp_type">类型: {{ spec.psp_type+"框" }}</div>
              <div v-if="spec.psp_options">选项: {{ spec.psp_options }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="tip-message" v-if="!productList.length">
        <el-empty description="暂无商品信息"></el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import { productList, deleteProduct } from "@/api/ProductMent/product";
import { getInfoDCPPNO } from "@/api/document";
export default {
  name: "CodeJson",
  /*组件参数 接收来自父组件的数据*/
  props: {},
  /*局部注册的组件*/
  components: {},
  /*组件状态值*/
  data() {
    return {
      queryForm: {
        type: "", // 选中的产品ID
      },
      productList: [],
      jsonData: null,
    };
  },

  /*计算属性*/
  computed: {
    parsedSpecifications() {
      if (!this.jsonData) return [];
      try {
        const specs = JSON.parse(this.jsonData);
        return Array.isArray(specs) ? specs : [];
      } catch (e) {
        console.error("解析规格失败:", e);
        return [];
      }
    }
  },

  /*侦听器*/
  watch: {},

  /*
   * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
   * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
   */
  async mounted() {
    await this.fetchProductList();
  },

  /*组件方法*/
  methods: {
    // 处理产品选择变化
    async handleTypeChange(value) {
      if (value) {
        await this.fetchDCPPNO(value);
      } else {
        this.jsonData = null;
      }
    },

    // 获取产品列表
    async fetchProductList() {
      try {
        const res = await productList({
          pageNum: 1,
          pageSize: 999
        });
        this.productList = res.rows || [];
      } catch (error) {
        console.error('获取产品列表失败:', error);
        this.$message.error("获取产品列表失败");
      }
    },

    // 获取指定产品的JSON数据
    async fetchDCPPNO(id) {
      try {
        const res = await getInfoDCPPNO(id);
        console.log(res);
        if (res.data && this.isValidJson(res.data.dcppno)) {
          this.jsonData = res.data.dcppno;
        } else {
          this.$message.warning('获取到的JSON数据格式无效');
          this.jsonData = null;
        }
      } catch (error) {
        console.error('获取DCPPNO数据失败:', error);
        this.$message.error('获取数据失败');
        this.jsonData = null;
      }
    },

    handleUseSpec(spec) {
      const selectedProduct = this.productList.find(
        item => item.dcp_id === this.queryForm.type
      );

      const safeId = `prod_${Date.now()}_${Math.random()
        .toString(36)
        .substr(2, 9)}`;

      const productData = {
        type: "ProductAttr",
        id: safeId,
        content: "",
        attrs: {
          specifications: [spec], // 只包含选中的规格
          label: selectedProduct?.dcp_name || '',
          productInfo: {
            dcp_p_no: JSON.stringify([spec]), // 将单个规格转换为数组
            dcp_name: selectedProduct?.dcp_name || '',
            dcp_model: selectedProduct?.dcp_model || '',
            dcp_oa_code: selectedProduct?.dcp_oa_code || '',
          },
        },
      };

      this.$emit("onPicked", productData);
    },

    // 获取类型的中文释义
    getTypeText(type) {
      const typeMap = {
        1: "输入框",
        2: "单选框",
        3: "多选框",
      };
      console.log(type);
      return typeMap[type] || "输入框";
    },

    // 根据产品规格判断使用什么类型的输入控件
    determineInputType(row) {
      if (!row.psp_type) return 1; // 默认为输入框

      switch (parseInt(row.psp_type)) {
        case 1:
          return 1; // 输入框
        case 2:
          return 2; // 单选框
        case 3:
          return 3; // 多选框
        default:
          return 1;
      }
    },

    // 获取选项值
    getValueItems(row) {
      if (!row.psp_options) return "";
      return row.psp_options;
    },

    // 检查是否为有效的JSON字符串
    isValidJson(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },

    // 解析规格信息
    parseSpecifications(jsonStr) {
      try {
        const specs = JSON.parse(jsonStr);
        return Array.isArray(specs) ? specs : [];
      } catch (e) {
        console.error("解析规格失败:", e);
        return [];
      }
    },
  },
};
</script>
<style lang='css' scoped>
.spec-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 4px 0;
}

.spec-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.invalid-json {
  color: #f56c6c;
  font-size: 12px;
}

.el-table {
  margin-top: 15px;
}

/* 确保长文本正确换行 */
.el-table .cell {
  word-break: break-word;
}

.json-display {
  margin-top: 20px;
}

.json-card {
  margin-bottom: 20px;
}

.json-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.spec-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.spec-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.specifications-list {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.spec-card {
  margin-bottom: 16px;
}

.spec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.spec-title {
  font-weight: bold;
  font-size: 14px;
}

.spec-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.spec-details {
  margin-top: 8px;
  font-size: 13px;
  color: #666;
}

.spec-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>