<template>
  <div class="data-info">
    <el-card>
      <el-form :model="dataForm" label-width="120px">
        <el-form-item label="公式名称:">
          <el-input v-model="dataForm.name"></el-input>
        </el-form-item>

        <el-form-item label="公式:">
          <el-input
            type="textarea"
            v-model="dataForm.formula"
            @input="handleFormulaInput"
            ref="formulaInput"
          ></el-input>
          <div style="display: flex; justify-content: flex-end">
            <el-button style="margin-top: 10px" @click="InsertTableData"
              >插入表格数据</el-button
            >
            <el-button
              style="margin-top: 10px"
              type="primary"
              @click="InsertModule"
              >插入模块变量</el-button
            >
          </div>
          <div class="intro">
            公式说明：
            <div>
              格式一：[T][模块引用名][属性引用名] <span>*</span>其中
              [T]表示的是模块引用。
            </div>
            <div>目前仅支持+、-、*、/ 四种计算符合</div>
            <div>示例:　[T][模块01][attr01]+[T][模块01][attr02]</div>
            <div>
              格式二：[T][模块引用名][属性引用名]
              IF(判断条件,true值,false值)<span>*</span>其中
              [T]表示的是模块引用。
            </div>
            <div>
              示例:　[T][图文][测试1]+IF([T][图文][测试1]>30,[T][图文][测试2],11)
            </div>
            <div>
              嵌套示例: [T][图文][测试1] + IF([T][图文][测试2] > 50,
              IF([T][图文][测试1] > 30, [T][图文][测试3], 20),
              IF([T][图文][测试3] > 40, 15, [T][图文][测试2]) )
            </div>
          </div>
        </el-form-item>
        <el-form-item label="保留小数点:">
          <el-input
            v-model.number="dataForm.point"
            type="number"
            min="0"
            max="4"
            :step="1"
            @input="validatePoint"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍:">
          <el-input type="textarea" v-model="dataForm.intro"></el-input>
        </el-form-item>

        <el-form-item label="公式状态:">
          <el-select
            v-model="dataForm.status"
            placeholder="请选择状态"
            size="large"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="text-align: right; margin-top: 20px">
      <el-button type="warning" @click="btnSave">确认保存</el-button>
    </div>
    <el-dialog
      :visible.sync="variablesVisible"
      append-to-body
      width="300"
      custom-class="prod-verify"
      :title="title"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-form :model="insertForm" :rules="insertRules" ref="insertRef">
        <el-form-item label="模块名称:">
          <el-select
            v-model="insertForm.moduleName"
            placeholder="请选择模块"
            size="large"
            style="width: 100%"
            @change="changeModule"
          >
            <el-option
              v-for="(item, index) in list"
              :key="`${item.id}-${index}`"
              :label="item.name"
              :value="item.attrs"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性名称:" prop="Variable">
          <el-select
            v-model="insertForm.Variable"
            placeholder="请选择属性"
            size="large"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in filteredAttrList"
              :key="`${item.id}-${index}`"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="btnInster">确认插入</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="tableDataVisible"
      append-to-body
      width="400"
      custom-class="prod-verify"
      title="插入表格数据"
      :close-on-click-modal="false"
      @close="close"
    >
      <div class="com-formual">
        <el-form>
          <el-form-item>
            <el-select
              v-model="tableCode"
              placeholder="请选择状态"
              @change="onChangeTab"
              size="large"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in tableList"
                :key="item.id"
                :label="item.name"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item style="min-height: 500px" v-if="fileLoadStatus">
            <div
              id="luckysheets"
              ref="luckysheets"
              style="width: 100%; height: 500px"
            ></div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="showConfirm"
      title="数据确认"
      width="500"
      align-center
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div>当前工作表：{{ position.sheet }}</div>
      <div>当前取值：{{ position.value }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showConfirm = false">关闭</el-button>
          <el-button type="primary" @click="onConfirm">确认插入</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { createFormula, updateFormula, getFormulaInfo } from "@/api/formula";
import { searchSourceData, deleteSourceData } from "@/api/sourceData";
import LuckyExcel from "luckyexcel";
export default {
  emits: ["onClose"],
  props: {
    id: {
      type: Number,
      default: 0,
    },
    list: {
      type: Array,
      default: [],
    },
  },
  watch: {
    id: {
      handler(newVal, oldVal) {
        if (newVal == null) return;
        if (newVal == 0) {
          this.resetForm();
        } else {
          // 添加条件以确保在id相同但需要重新获取数据时也能触发
          if (newVal !== oldVal || this.dataForm.id !== newVal) {
            this.getInfo(newVal);
          }
        }
      },
      immediate: true,
    },
    list: {
      handler(newValue, oldValue) {
        console.log("list changed:", newValue);
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      activeName: "base",
      currentCategory: [],
      allCategories: [],

      dataForm: {
        id: 0,
        name: "",
        formula: "",
        intro: "",
        status: 5,
        use_status: 5,
        params: "[]",
        point: 0,
      },
      statusOptions: [
        {
          value: "",
          label: "请选择状态",
        },
        {
          value: 5,
          label: "使用中",
        },
        {
          value: 6,
          label: "已停用",
        },
      ],
      variablesVisible: false,
      title: "",
      insertForm: {
        moduleName: "",
        Variable: "",
      },
      insertRules: {
        Variable: [
          { required: true, message: "请选择变量", trigger: "change" },
        ],
      },
      tableDataVisible: false,
      tableCode: "",
      tableList: [],
      showConfirm: false,
      fileLoadStatus: false,
      position: {
        tb: "",
        c: 0,
        r: 0,
        sheet: "",
        value: "",
      },
      attrList: [],
    };
  },

  mounted() {
    let _this = this;
    this.initTableList();
  },
  computed: {
    uniqueAttrList() {
      const uniqueNames = new Set();
      return this.attrList.filter(attr => {
        if (!uniqueNames.has(attr.name)) {
          uniqueNames.add(attr.name);
          return true;
        }
        return false;
      });
    },
    filteredAttrList() {
      return this.uniqueAttrList.filter(attr => 
         attr.type !== 'Directory'
      );
    }
  },
  methods: {
    validatePoint(value) {
      const intValue = parseInt(value);
      if (isNaN(intValue) || intValue < 0 || intValue > 4) {
        this.dataForm.point = "";
      } else {
        this.dataForm.point = intValue;
      }
    },
    /* 关闭 */
    close() {
      this.insertForm = {};
    },
    /*  */
    handleFormulaInput(value) {
      // 更新 dataForm.formula 的值
      this.dataForm.formula = value;
    },
    resetForm() {
      this.dataForm = {
        id: 0,
        name: "",
        formula: "",
        intro: "",
        status: 5,
        use_status: 5,
        params: "[]",
        point: 0,
      };
    },

    btnSave(e) {
      let _this = this;

      const saveAction = _this.dataForm.id > 0 ? updateFormula : createFormula;

      saveAction(_this.dataForm)
        .then((res) => {
          _this.$message.success(
            _this.dataForm.id > 0 ? "公式更新成功" : "公式创建成功"
          );
          _this.$emit("onClose", true); // Pass a boolean to indicate successful save

          // 添加这行来强制重新获取数据
          _this.getInfo(_this.dataForm.id);
          _this.resetFormAfterSave();
        })
        .catch((error) => {
          console.error("保存失败:", error);
          _this.$message.error("保存失败，请重试");
        });
    },
    resetFormAfterSave() {
      this.dataForm = {
        id: 0,
        name: "",
        formula: "",
        intro: "",
        status: 5,
        use_status: 5,
        params: "[]",
        point: 0,
      };
      // If you have any other data that needs to be reset, do it here
    },

    //产品详情
    getInfo(id) {
      let _this = this;
      let par = {
        id: id,
      };
      getFormulaInfo(par).then((res) => {
        if (!res) return;
        if (res.status != 200) return;
        _this.dataForm = res.data;
      });
    },

    onChangeStatus(e) {
      this.dataForm.status = e;
    },
    //修改分类信息
    onChangeCategory(e) {
      let _this = this;
      _this.dataForm.categoryId = e;
    },
    /* 插入模块变量 */
    InsertModule() {
      this.variablesVisible = true;
      this.title = "插入模块变量";
    },
    extractChineseTemplates(content) {
      const templateRegex = /\{\{([\s\S]*?)\}\}/g; // 修改正则表达式以匹配多行内容
      const chineseRegex = /[\u4e00-\u9fa5]/;
      let match;
      const chineseTemplates = [];
      while ((match = templateRegex.exec(content)) !== null) {
        const trimmedMatch = match[1].trim();
        chineseTemplates.push(trimmedMatch);
      }
      return chineseTemplates;
    },

    processContent(val) {
      if (val && typeof val.content === "string") {
        const chineseTemplates = this.extractChineseTemplates(val.content);
        console.log("Extracted Chinese templates:", chineseTemplates);

        if (val.attrs && Array.isArray(val.attrs)) {
          this.attrList = val.attrs.filter((el) =>
            chineseTemplates.some((template) => template.includes(el.id))
          );
        }
      } else {
        this.attrList = [];
      }
    },
    /* 模块名称 */
    changeModule(value) {
      const selectedIndex = this.list.findIndex(
        (option) => option.attrs === value
      );
      this.processContent(this.list[selectedIndex]);
      //this.attrList = value; // 假设 attrs 属性包含了属性列表
    },
    /* 插入变量 */
    btnInster() {
      this.$refs.insertRef.validate((valid) => {
        if (valid) {
          const selectedModule = this.list.find(
            (module) => module.attrs === this.insertForm.moduleName
          );
          if (selectedModule) {
            const moduleName = selectedModule.name;
            const variableName = this.attrList.find(
              (attr) => attr.id === this.insertForm.Variable
            )?.name;

            if (variableName) {
              const insertText = `[T][${moduleName}][${variableName}]`;
              this.dataForm.formula += insertText;
              this.variablesVisible = false; // 关闭对话框
              this.$message.success("变量插入成功");
            } else {
              this.$message.error("无法找到选中的变量");
            }
          } else {
            this.$message.error("无法找到选中的模块");
          }
        } else {
          /* this.$message.error("请选择变量!"); */
          return false;
        }
      });
    },
    /* 插入表格数据 */
    InsertTableData() {
      this.tableDataVisible = true;
    },

    onConfirm(e) {
      this.showConfirm = false;
      const insertText = `[R][${this.position.tb}][${this.position.sheet}][${
        this.position.r + 1
      },${this.position.c + 1}]`;
      this.dataForm.formula += insertText;
      this.tableDataVisible = false;
      this.$message.success("表格数据插入成功");
      this.insertForm = {
        moduleName: {},
        Variable: "",
      };
    },

    onChangeTab(e) {
      let _this = this;
      let item = _this.tableList[e];
      _this.fileLoadStatus = true;

      item.sourceData = JSON.parse(item.source_data);
      console.log(item.sourceData.exportJson.sheets);

      _this.position.tb = item.code;
      _this.$nextTick(() => {
        luckysheet.destroy();
        luckysheet.create({
          container: "luckysheets",
          data: item.sourceData.exportJson.sheets,
          lang: "zh",
          showinfobar: false, // 是否显示顶部信息栏
          showstatisticBar: false, // 是否显示底部计数栏
          sheetBottomConfig: false, // sheet页下方的添加行按钮和回到顶部按钮配置
          allowEdit: false, // 是否允许前台编辑
          enableAddRow: false, // 是否允许增加行
          enableAddCol: false, // 是否允许增加列
          sheetFormulaBar: false, // 是否显示公式栏
          enableAddBackTop: false, // 返回头部按钮
          showsheetbar: true, // 是否显示底部sheet页按钮
          enableAddRow: false, //允许添加行
          showsheetbarConfig: {
            add: false,
            menu: false,
          },
          hook: {
            cellMousedown: function (cell, position, sheetFile, ctx) {
              _this.position.sheet = sheetFile.name;
              _this.position.r = position.r;
              _this.position.c = position.c;

              if (cell.v) {
                _this.position.value = cell.v;
              } else {
                _this.position.value = "";
                cell.ct.s.map((res) => {
                  _this.position.value += res.v;
                });
              }
              _this.showConfirm = true;
            },
          },
        });
      });
    },

    initTableList() {
      let _this = this;
      searchSourceData({ page: 1, pageSize: 999, status: 5 }).then((res) => {
        if (res.status != 200) return;
        _this.tableList = res.data.dataList;
      });
    },
  },
};
</script>

<style lang="scss">
@import "./dataInfo.scss";
</style>
