<template>
  <div class="container1">
    <div class="infobox">
      <div class="header">
        <div>
          <div class="text">控制图：</div>
          <el-select
            v-model="value2"
            placeholder="Select"
            ref="selectRef2"
            @change="changeSelect2"
          >
            <el-option
              v-for="item in sccOptions"
              :key="item.value"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <!--        <div class="text">
          计量单位：{{ value ? JSON.parse(value).unit : "-" }}
        </div>-->
      </div>
      <div class="body" v-if="value2 === 'Xbar-R' || value2 === 'Xbar-S'">
        <div>
          <div class="text">工序名称：</div>
          <el-select
            v-model="value"
            placeholder="Select"
            ref="selectRef"
            @change="changeSelect"
          >
            <el-option
              v-for="item in opOptions"
              :key="item.value"
              :label="item.dictLabel"
              :value="item.remark"
            />
          </el-select>
          <!--          <div class="text" style="margin-top: 20px">-->
          <!--            上限（3σ）：{{ value ? JSON.parse(value).ucl : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            上限子界限（2σ）：{{ value ? JSON.parse(value).ucl_c : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            上限子界限（σ）：{{ value ? JSON.parse(value).ucl_b : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            中心线：{{ value ? JSON.parse(value).cl : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            下限子界限（σ）：{{ value ? JSON.parse(value).lcl_c : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            下限子界限（2σ）：{{ value ? JSON.parse(value).lcl_b : "-" }}-->
          <!--          </div>-->
          <!--          <div class="text">-->
          <!--            下限（3σ）：{{ value ? JSON.parse(value).lcl : "-" }}-->
          <!--          </div>-->

          <div
            class="edit-item"
            @dblclick="startEdit('ucl')"
            style="margin-top: 20px"
          >
            <span v-if="!editing.ucl" class="text"
              >上限（3σ）：{{ displayValue.ucl }}</span
            >
            <input
              v-else
              v-model.number="editValue.ucl"
              ref="uclInput"
              @blur="saveEdit('ucl')"
              @keyup.enter="saveEdit('ucl')"
              @keyup.escape="cancelEdit1('ucl')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('ucl_c')">
            <span v-if="!editing.ucl_c" class="text"
              >上限子界限（2σ）：{{ displayValue.ucl_c }}</span
            >
            <input
              v-else
              v-model.number="editValue.ucl_c"
              ref="ucl_cInput"
              @blur="saveEdit('ucl_c')"
              @keyup.enter="saveEdit('ucl_c')"
              @keyup.escape="cancelEdit1('ucl_c')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('ucl_b')">
            <span v-if="!editing.ucl_b" class="text"
              >上限子界限（σ）：{{ displayValue.ucl_b }}</span
            >
            <input
              v-else
              v-model.number="editValue.ucl_b"
              ref="ucl_bInput"
              @blur="saveEdit('ucl_b')"
              @keyup.enter="saveEdit('ucl_b')"
              @keyup.escape="cancelEdit1('ucl_b')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('cl')">
            <span v-if="!editing.cl" class="text"
              >中心线：{{ displayValue.cl }}</span
            >
            <input
              v-else
              v-model.number="editValue.cl"
              ref="clInput"
              @blur="saveEdit('cl')"
              @keyup.enter="saveEdit('cl')"
              @keyup.escape="cancelEdit1('cl')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('lcl_c')">
            <span v-if="!editing.lcl_c" class="text"
              >下限子界限（σ）：{{ displayValue.lcl_c }}</span
            >
            <input
              v-else
              v-model.number="editValue.lcl_c"
              ref="lcl_cInput"
              @blur="saveEdit('lcl_c')"
              @keyup.enter="saveEdit('lcl_c')"
              @keyup.escape="cancelEdit1('lcl_c')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('lcl_b')">
            <span v-if="!editing.lcl_b" class="text"
              >下限子界限（2σ）：{{ displayValue.lcl_b }}</span
            >
            <input
              v-else
              v-model.number="editValue.lcl_b"
              ref="lcl_bInput"
              @blur="saveEdit('lcl_b')"
              @keyup.enter="saveEdit('lcl_b')"
              @keyup.escape="cancelEdit1('lcl_b')"
              class="edit-input"
            />
          </div>
          <div class="edit-item" @dblclick="startEdit('lcl')">
            <span v-if="!editing.lcl" class="text"
              >下限（3σ）：{{ displayValue.lcl }}</span
            >
            <input
              v-else
              v-model.number="editValue.lcl"
              ref="lclInput"
              @blur="saveEdit('lcl')"
              @keyup.enter="saveEdit('lcl')"
              @keyup.escape="cancelEdit1('lcl')"
              class="edit-input"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="databox">
      <el-scrollbar :style="{ height: Height + 'px' }">
        <div class="box">
          <div class="info" v-if="value2 === 'Xbar-R'">
            <XbarRList
              ref="xbarrListRef"
              @table-data="handleDataFromChildXbarR"
              v-model:addStatus="addStatus"
              v-model:editStatus="editStatus"
            />
          </div>
          <div class="info" v-if="value2 === 'Xbar-S'">
            <XbarSList
              ref="xbarsListRef"
              @table-data="handleDataFromChildXbarS"
              v-model:addStatus="addStatus"
              v-model:editStatus="editStatus"
            />
          </div>
          <div class="info" v-if="value2 === 'P'">
            <PList
              ref="pListRef"
              @table-data="handleDataFromChildP"
              :chart="chart"
            />
          </div>
          <div class="info" v-if="value2 === 'NP'">
            <NPList
              ref="npListRef"
              @table-data="handleDataFromChildNP"
              :chart="chart"
            />
          </div>
          <div class="info" v-if="value2 === 'C'">
            <CList
              ref="cListRef"
              @table-data="handleDataFromChildC"
              :chart="chart"
            />
          </div>
          <div class="info" v-if="value2 === 'U'">
            <UList
              ref="uListRef"
              @table-data="handleDataFromChildU"
              :chart="chart"
            />
          </div>
          <div class="info" v-if="value2 === 'I-MR'">
            <IMRList
              ref="imrListRef"
              @table-data="handleDataFromChildIMR"
              :chart="chart"
            />
          </div>
          <div class="info" v-if="value2 === 'EWMA'">
            <EWMAList
              ref="imrListRef"
              @table-data="handleDataFromChildEWMA"
              :chart="chart"
            />
          </div>
        </div>
        <div class="box" v-show="!addStatus && !editStatus">
          <div class="info" v-if="value2 === 'Xbar-R'">
            <XbarR ref="xbarRRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'Xbar-S'">
            <XbarS ref="xbarSRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'P'">
            <P ref="pRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'NP'">
            <NP ref="npRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'C'">
            <C ref="cRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'U'">
            <U ref="uRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'I-MR'">
            <IMR ref="iMRRef" :process="showLable" />
          </div>
          <div class="info" v-if="value2 === 'EWMA'">
            <EWMA ref="eWMARef" :process="showLable" />
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import XbarRList from "./Xbar-RList.vue";
import XbarSList from "./Xbar-SList.vue";
import PList from "./PList.vue";
import NPList from "./NPList.vue";
import CList from "./CList.vue";
import UList from "./UList.vue";
import IMRList from "./I-MRList.vue";
import EWMAList from "./EWMAList.vue";
import { useDictionaryStore } from "@/store";
import XbarR from "@/views/analysis/process/Xbar-R-2.vue";
import NP from "@/views/analysis/process/NP.vue";
import C from "@/views/analysis/process/C.vue";
import XbarS from "@/views/analysis/process/Xbar-S-2.vue";
import P from "@/views/analysis/process/P.vue";
import EWMA from "@/views/analysis/process/EWMA.vue";
import IMR from "@/views/analysis/process/I-MR.vue";
import U from "@/views/analysis/process/U.vue";

import { getDictList, updateDict } from "@/api/dict";

const operationList = ref();
const initOpOptions = () => {
  getDictList({ dictCode: "spc_operation" }).then(({ data }) => {
    operationList.value = data;
    opOptions.value = data;
  });
};
initOpOptions();

// 初始值
let initialValue = ref({
  ucl: 0,
  ucl_c: 0,
  ucl_b: 0,
  cl: 0,
  lcl_c: 0,
  lcl_b: 0,
  lcl: 0,
});

// 显示的值
const displayValue = ref(reactive({ ...initialValue.value }));

// 编辑状态
const editing = reactive({
  ucl: false,
  ucl_c: false,
  ucl_b: false,
  cl: false,
  lcl_c: false,
  lcl_b: false,
  lcl: false,
});

// 编辑时的临时值
const editValue = reactive({ ...initialValue.value });

// 输入框引用
const uclInput = ref(null);
const ucl_cInput = ref(null);
const ucl_bInput = ref(null);
const clInput = ref(null);
const lcl_cInput = ref(null);
const lcl_bInput = ref(null);
const lclInput = ref(null);

// 开始编辑
const startEdit = (field) => {
  editing[field] = true;
  editValue[field] = displayValue.value[field];

  nextTick(() => {
    let inputRef = null;
    switch (field) {
      case "ucl":
        inputRef = uclInput.value;
        break;
      case "ucl_c":
        inputRef = ucl_cInput.value;
        break;
      case "ucl_b":
        inputRef = ucl_bInput.value;
        break;
      case "cl":
        inputRef = clInput.value;
        break;
      case "lcl_c":
        inputRef = lcl_cInput.value;
        break;
      case "lcl_b":
        inputRef = lcl_bInput.value;
        break;
      case "lcl":
        inputRef = lclInput.value;
        break;
    }
    inputRef?.focus();
    inputRef?.select();
  });
};

// 保存编辑
const saveEdit = (field) => {
  editing[field] = false;
  displayValue.value[field] = editValue[field];
  console.log(`保存${field}值:`, displayValue.value[field]);
  operationList.value.forEach((v) => {
    if (v.dictLabel === showLable.value) {
      v.remark = JSON.stringify(displayValue.value);
      updateDict(v);
      value.value = JSON.stringify(displayValue.value);
    }
  });
};

// 取消编辑
const cancelEdit1 = (field) => {
  editing[field] = false;
};

const handleDataFromChildXbarR = async (data) => {
  await nextTick();
  xbarRRefMethod(data);
};
const handleDataFromChildXbarS = async (data) => {
  await nextTick();
  xbarSRefMethod(data);
};
const handleDataFromChildEWMA = async (data) => {
  await nextTick();
  eWMARefMethod(data);
};
const handleDataFromChildIMR = async (data) => {
  await nextTick();
  imrRefMethod(data);
};
const handleDataFromChildU = async (data) => {
  await nextTick();
  uRefMethod(data);
};
const handleDataFromChildC = async (data) => {
  await nextTick();
  cRefMethod(data);
};
const handleDataFromChildNP = async (data) => {
  await nextTick();
  npRefMethod(data);
};
const handleDataFromChildP = async (data) => {
  await nextTick();
  pRefMethod(data);
};

const xbarRRef = ref("xbarRRef");
const xbarRRefMethod = async (data) => {
  await nextTick(() => {
    if (xbarRRef.value) {
      xbarRRef.value.init(data);
    }
  });
};

const xbarSRef = ref("xbarSRef");
const xbarSRefMethod = async (data) => {
  await nextTick();
  if (xbarSRef.value) {
    xbarSRef.value.init(data);
  }
};
const pRef = ref("pRef");
const pRefMethod = async (data) => {
  await nextTick();
  if (pRef.value) {
    pRef.value.init(data);
  }
};
const npRef = ref("npRef");
const npRefMethod = async (data) => {
  await nextTick();
  if (npRef.value) {
    npRef.value.init(data);
  }
};
const cRef = ref("cRef");
const cRefMethod = async (data) => {
  await nextTick();
  if (cRef.value) {
    cRef.value.init(data);
  }
};
const uRef = ref("uRef");
const uRefMethod = async (data) => {
  await nextTick();
  if (uRef.value) {
    uRef.value.init(data);
  }
};
const iMRRef = ref("iMRRef");
const imrRefMethod = async (data) => {
  await nextTick();
  if (iMRRef.value) {
    iMRRef.value.init(data);
  }
};
const eWMARef = ref("EWMA");
const eWMARefMethod = async (data) => {
  await nextTick();
  if (eWMARef.value) {
    eWMARef.value.init(data);
  }
};
const year = ref("0");
const lableValue = ref("");

const { dicts } = useDictionaryStore();
const sccOptions = ref([...dicts.spc_control_chart]);
const value2 = ref(sccOptions.value[0].dictValue);

//编辑状态
const editStatus = ref(false);
const addStatus = ref(false);
const changeEditstatus = () => {
  editStatus.value = !changeEditstatus.value;
  addStatus.value = false;
};

const tableData = ref([]);
const opOptions = ref([...dicts.spc_operation]);

const value = ref(opOptions.value[0].remark);
const title = ref("调阻精度");
const xbarrListRef = ref("xbarrListRef");
const xbarsListRef = ref("xbarsListRef");

const showLable = ref("调阻");
const changeSelect = () => {
  setTimeout(() => {
    displayValue.value = JSON.parse(value.value);
    showLable.value = selectRef.value.currentPlaceholder;
    opOptions.value.forEach((item) => {
      if (item.dictLabel == showLable.value) {
        lableValue.value = item.dictValue;
      }
    });
    switch (showLable.value) {
      case "调阻":
        title.value = "调阻精度";
        break;
      case "粘片":
        title.value = "剪切强度";
        break;
      case "键合":
        title.value = "键合强度";
        break;
      default:
        title.value = "调阻精度";
        break;
    }
    chartsOption1.value.title[0].text = `${title.value}的Xbar-R控制图`;

    if (value2.value === "Xbar-R") {
      xbarrListRef.value.init(lableValue.value);
    } else if (value2.value === "Xbar-S") {
      xbarsListRef.value.init(lableValue.value);
    }
  }, 0);
};
const changeSelect2 = () => {
  setTimeout(() => {
  if (value2.value === "Xbar-R") {
    xbarRRefMethod();
    xbarrListRef.value.init(lableValue.value);
  } else if (value2.value === "Xbar-S") {
    xbarSRefMethod();
    console.log(lableValue.value, "2200")
    xbarsListRef.value.init(lableValue.value);
  } else if (value2.value === "P") {
    pRefMethod();
  } else if (value2.value === "NP") {
    npRefMethod();
  } else if (value2.value === "C") {
    cRefMethod();
  } else if (value2.value === "U") {
    uRefMethod();
  } else if (value2.value === "I-MR") {
    imrRefMethod();
  } else if (value2.value === "EWMA") {
    eWMARefMethod();
  }
  }, 0);
};

// const searchData = computed(() =>
//   tableData.value.filter((item) => item.data.includes(searchValue.value))
// );
const selectRef = ref(null);
//保存
const maxHeight = ref(null);
const maxWidth = ref(null);
const charts1 = shallowRef(null);
const charts2 = shallowRef(null);
const chartsOption1 = ref({
  title: [
    // {
    //   text: `x̄=${showData.value.avgAvg ? showData.value.avgAvg : "-"}`,
    //   right: "5%",
    //   top: "42%",
    //   textStyle: {
    //     fontSize: 15,
    //     color: "#333",
    //     fontWeight: 100,
    //   },
    // },
    {
      text: `${title.value}的Xbar-R控制图`,
      left: "40%",
    },
    {
      text: "样",
      left: "4%",
      top: "28%",
    },
    {
      text: "本",
      left: "4%",
      top: "35%",
    },
    {
      text: "均",
      left: "4%",
      top: "42%",
    },
    {
      text: "值",
      left: "4%",
      top: "49%",
    },
  ],
  grid: {
    right: "15%",
  },
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  tooltip: {
    show: true,
  },
  xAxis: [
    {
      type: "category",
      boundaryGap: false,
      data: [],
    },
  ],
  yAxis: [
    {
      type: "value",
    },
  ],
  series: [
    {
      type: "line",
      lineStyle: {
        color: "rgb(26, 122, 240)",
      },
      symbolSize: 13,
      symbol: "circle",
      itemStyle: {
        color: (params) => {
          const avg = JSON.parse(value.value);
          const paramValue = Number(params.value);
          if (
            paramValue <= Number(avg.avgMax) &&
            paramValue >= Number(avg.avgMin)
          ) {
            return "rgb(26, 122, 240)";
          } else {
            return "red";
          }
        },
      },
      markLine: {
        silent: true,
        data: [
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `上限=${JSON.parse(value.value).avgMax ? JSON.parse(value.value).avgMax : "-"}`,
              color: "#333",
            },
            lineStyle: { type: "solid", color: "#333", width: 2 },
          },
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `下限=${JSON.parse(value.value).avgMin ? JSON.parse(value.value).avgMin : "-"}`,
              color: "#333",
            },
            lineStyle: {
              type: "solid",
              color: "#333",
              width: 2,
            },
          },
          {
            yAxis: 0,
            silent: false,
            label: {
              position: "end",
              formatter: ``,
              color: "#333",
            },
            lineStyle: {
              type: "solid",
              color: "#333",
              width: 2,
            },
          },
        ],
      },
    },
  ],
});
const chartsOption2 = ref({
  title: [
    // {
    //   text: `R=${showData.value.rangeAvg ? showData.value.rangeAvg : "-"}`,
    //   right: "5%",
    //   top: "42%",
    //   textStyle: {
    //     fontSize: 15,
    //     color: "#333",
    //     fontWeight: 100,
    //   },
    // },
    {
      text: "样",
      left: "4%",
      top: "28%",
    },
    {
      text: "本",
      left: "4%",
      top: "35%",
    },
    {
      text: "极",
      left: "4%",
      top: "42%",
    },
    {
      text: "值",
      left: "4%",
      top: "49%",
    },
  ],
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  grid: {
    right: "15%",
  },
  xAxis: [
    {
      type: "category",
      boundaryGap: false,
      data: [],
    },
  ],
  yAxis: [
    {
      type: "value",
    },
  ],
  tooltip: {
    show: true,
  },
  series: [
    {
      type: "line",
      lineStyle: {
        color: "rgb(26, 122, 240)",
      },
      symbolSize: 13,
      symbol: "circle",
      itemStyle: {
        color: (params) => {
          const range = JSON.parse(value.value);
          const paramValue = Number(params.value);
          if (
            paramValue <= Number(range.rangeMax) &&
            paramValue >= Number(range.rangeMin)
          ) {
            return "rgb(26, 122, 240)";
          } else {
            return "red";
          }
        },
      },
      markLine: {
        silent: true,
        data: [
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `上限=${JSON.parse(value.value).rangeMax ? JSON.parse(value.value).rangeMax : "-"}`,
              color: "#333",
            },
            lineStyle: { type: "solid", color: "#333", width: 2 },
          },
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `下限=${JSON.parse(value.value).rangeMin ? JSON.parse(value.value).rangeMin : "-"}`,
              color: "#333",
            },
            lineStyle: { type: "solid", color: "#333", width: 2 },
          },
          {
            yAxis: 0,
            silent: false,
            label: {
              position: "end",
              formatter: ``,
              color: "#333",
            },
            lineStyle: {
              type: "solid",
              color: "#333",
              width: 2,
            },
          },
        ],
      },
    },
  ],
});
const Height = ref(0);
const setHeight = () => {
  Height.value = document.querySelector(".databox").clientHeight;
  maxHeight.value = document.querySelector(".info").clientHeight;
  maxWidth.value = document.querySelector(".info").clientWidth;
};
const Y2value = ref([]);
const X2array = ref([]);
const setY2value = () => {
  Y2value.value = [];
  tableData.value.forEach((item) => {
    Y2value.value.push(item.range);
  });
  Y2value.value.unshift("");
  Y2value.value.push("");
  chartsOption2.value.series[0].data = Y2value.value;
};
const setX2array = () => {
  X2array.value = [];
  tableData.value.forEach((item, index) => {
    X2array.value.push(index + 1);
  });
  X2array.value.unshift("");
  X2array.value.push("");
  chartsOption2.value.xAxis[0].data = X2array.value;
};

// 父组件的数据
const chart = ref(value2);

onMounted(async () => {
  setHeight();
  year.value = new Date().getFullYear() + "";
  opOptions.value.forEach((item) => {
    if (item.dictLabel == showLable.value) {
      lableValue.value = item.dictValue;
    }
  });
  value2.value = "Xbar-R";
  xbarrListRef.value.init(lableValue.value);
  displayValue.value = JSON.parse(value.value);
});
onBeforeUnmount(() => {
  // window.removeEventListener("resize", setView);
});
</script>

<style lang="scss" scoped>
@media print {
  #print {
    margin-left: -18%;
  }
}
.ctext {
  margin-bottom: 20px;
}
.double-edit-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.edit-item {
  padding: 8px 0px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 15px;
}

.edit-item:hover {
  background-color: #f5f5f5;
}

.edit-input {
  width: 100px;
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
}

.edit-input:focus {
  border-color: #409eff;
}

.ellipsis-text {
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  width: 100%; /* 宽度占满单元格 */
}

.formStyle {
  width: 400px;
  margin: 20px auto;
}

.container1 {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: white;

  .infobox {
    width: 250px;

    .header {
      //height: 120px;
      //border-bottom: 2px solid #00000010;
      padding: 20px;
    }

    .body {
      border-top: 2px solid #00000010;
      padding: 20px;
    }
  }

  .databox {
    flex: 1;
    border-left: 2px solid #00000010;

    .box {
      height: 810px;
      padding: 5px 20px;
      display: flex;
      flex-direction: column;

      .illustrate {
        padding: 20px 60px;
      }

      .tableTitle {
        text-align: center;
        margin: 10px 0;
        padding-right: 40px;
      }

      .header {
        margin-top: 20px;
        //margin-left: 100px;
        display: flex;
        width: 100%;
        height: auto;
      }

      //.title {
      //  height: 50px;
      //  display: flex;
      //  align-items: center;
      //  margin-bottom: 10px;
      //  justify-content: space-between;
      //  .btns {
      //    display: flex;
      //    align-items: center;
      //    .btn {
      //      height: 24px;
      //      font-size: 14px;
      //      margin: 0 5px;
      //    }
      //  }
      //}
      .info {
        margin-top: 20px;
        flex: 1;
        height: 300px;
      }
    }
  }
}
</style>
