<template>
  <div class="container1">
    <div class="infobox">
      <div class="header">
        <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>
      <div class="body">
        <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" style="margin-top: 20px">
          Xbar-UCL：{{ value ? JSON.parse(value).avgMax : "-" }}
        </div>
        <div class="text">
          Xbar-MED：{{ value ? JSON.parse(value).avgMid : "-" }}
        </div>
        <div class="text">
          Xbar-LCL：{{ value ? JSON.parse(value).avgMin : "-" }}
        </div>
        <div class="text">
          R-UCL：{{ value ? JSON.parse(value).rangeMax : "-" }}
        </div>
        <div class="text">
          R-MED：{{ value ? JSON.parse(value).rangeMid : "-" }}
        </div>
        <div class="text">
          R-LCL：{{ value ? JSON.parse(value).rangeMin : "-" }}
        </div>
        <div class="text">
          计量单位：{{ value ? JSON.parse(value).unit : "-" }}
        </div>
      </div>
    </div>
    <div class="databox">
      <el-scrollbar :style="{ height: Height + 'px' }">
        <div class="box">
          <div class="title">
            <div style="display: flex; align-items: center">
              <div class="bg"></div>
              样本数据录入
            </div>
            <div class="header" v-show="!addStatus && !editStatus">
              <Search
                :searchOptions="searchForm"
                ref="searchRef"
                @data-list="getTableData"
                @reset-list="reset"
              />
            </div>
            <div class="btns">
              <el-button
                v-if="!addStatus && !editStatus"
                type="primary"
                size="small"
                class="btn"
                @click="changeaddstatus"
                >新增</el-button
              >
              <el-button
                v-if="editStatus || addStatus"
                type="success"
                size="small"
                class="btn"
                @click="submit"
                >确定</el-button
              >
              <el-button
                v-if="editStatus || addStatus"
                type="info"
                size="small"
                class="btn"
                @click="canceleOp"
                >取消</el-button
              >
            </div>
          </div>
          <div class="info" v-if="!addStatus">
            <el-table
              :data="tableData"
              border
              :style="{ height: maxHeight - 50 + 'px', width: maxWidth + 'px' }"
              :show-overflow-tooltip="true"
            >
              <el-table-column
                align="center"
                width="100"
                prop="dateStr"
                sortable
                label="日期"
              >
                <template #default="{ row }"
                  ><span>{{ row.dateStr }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                width="100"
                prop="model"
                label="产品型号"
              >
                <template #default="{ row }"
                  ><span>{{ row.model }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                width="100"
                prop="batchNo"
                label="生产批号"
              >
                <template #default="{ row }"
                  ><span>{{ row.batchNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                width="100"
                align="center"
                prop="accuracys"
                label="数据"
                :show-overflow-tooltip="false"
              >
                <template #default="{ row }">
                  <el-tooltip placement="top">
                    <template #content>
                      <div v-for="(item, index) in row.accuracys" :key="index">
                        <span>数值{{ index + 1 }}: {{ item }}</span>
                      </div>
                    </template>
                    <div class="ellipsis-text">
                      {{ row.accuracys.join(", ") }}
                    </div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="avg"
                label="平均值"
                width="60"
              /><el-table-column
                align="center"
                prop="range"
                label="极差"
                width="60"
              /><el-table-column
                align="center"
                width="80"
                prop="checkUser"
                label="检测人"
              >
                <template #default="{ row }"
                  ><span>{{ row.checkUser }}</span>
                </template> </el-table-column
              ><el-table-column
                align="center"
                prop="checkDeviceNo"
                label="检查设备编号"
              >
                <template #default="{ row }"
                  ><span>{{ row.checkDeviceNo }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="abnormal"
                width="60"
                label="是否异常"
              >
                <template #default="{ row }"
                  ><span>{{ row.abnormal }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="analyseUser" label="分析人">
                <template #default="{ row }"
                  ><span>{{ row.analyseUser }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="measure" label="处置措施">
                <template #default="{ row }"
                  ><span>{{ row.measure }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="160" prop="" label="操作">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    class="btn"
                    @click="updataItem(row)"
                    style="height: 25px"
                    >修改</el-button
                  >
                  <el-button
                    type="info"
                    size="small"
                    class="btn"
                    style="height: 25px"
                    @click="deleteSubmit(row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <Pagination
              :total="currentOption.total"
              :page="currentOption.page"
              :limit="currentOption.limit"
              :pageSizes="currentOption.pageSizes"
              v-model:page="currentOption.page"
              @pagination="getTableData"
            />
          </div>
          <div class="info" v-else>
            <el-form
              ref="ruleFormRef"
              :model="addData"
              :rules="rules"
              label-width="auto"
              class="formStyle"
            >
              <el-form-item label="日期" prop="dateStr">
                <el-date-picker
                  v-model="addData.dateStr"
                  type="date"
                  aria-label="Pick a date"
                  placeholder="Pick a date"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="任务编号" prop="qualityTaskId">
                <el-select
                  v-model="addData.qualityTaskId"
                  @change="
                    (value) => {
                      taskChange(value);
                    }
                  "
                >
                  <el-option
                    v-for="(item, index) in taskOption"
                    :key="index"
                    :label="item.taskCode"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="产品型号" prop="model">
                <el-input :disabled="true" v-model="addData.model" />
              </el-form-item>
              <el-form-item label="生产批号" prop="batchNo">
                <el-input v-model="addData.batchNo" />
              </el-form-item>
              <el-form-item
                v-for="(item, index) in addData.accuracys"
                :label="'数值' + (index + 1)"
                :key="index"
                :rules="[
                  {
                    required: true,
                    trigger: 'change',
                  },
                ]"
              >
                <el-input-number
                  :precision="2"
                  :step="0.01"
                  style="width: 100%"
                  v-model="addData.accuracys[index]"
                />
              </el-form-item>
              <!-- <el-form-item label="平均值" prop="avg">
                <el-input v-model="addData.avg" />
              </el-form-item>
              <el-form-item label="极差" prop="range">
                <el-input v-model="addData.range" />
              </el-form-item> -->
              <el-form-item label="检测人" prop="checkUser">
                <el-input v-model="addData.checkUser" />
              </el-form-item>
              <el-form-item label="检查设备编号" prop="checkDeviceNo">
                <el-input v-model="addData.checkDeviceNo" />
              </el-form-item>
              <!-- <el-form-item label="是否异常" prop="abnormal">
                <el-input v-model="addData.abnormal" />
              </el-form-item> -->
              <el-form-item label="分析人" prop="analyseUser">
                <el-input v-model="addData.analyseUser" />
              </el-form-item>
              <el-form-item label="处置措施" prop="measure">
                <el-input v-model="addData.measure" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="box" v-show="!addStatus">
          <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 XbarR from "./Xbar-R-2.vue";
import XbarS from "./Xbar-S-2.vue";
import P from "./P.vue";
import NP from "./NP.vue";
import C from "./C.vue";
import U from "./U.vue";
import IMR from "./I-MR.vue";
import EWMA from "./EWMA.vue";
import * as echarts from "echarts";
import { useDictionaryStore } from "@/store";
import {
  getData,
  addDatas,
  deleteData,
  updateData,
  getTaskCode,
} from "@/api/analysis";
import Search from "@/components/Search/index.vue";

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

const xbarSRef = ref("xbarSRef");
const xbarSRefMethod = async () => {
  await nextTick();
  if (xbarSRef.value) {
    xbarSRef.value.init(tableData.value);
  }
};
const pRef = ref("pRef");
const pRefMethod = async () => {
  await nextTick();
  if (pRef.value) {
    pRef.value.init();
  }
};
const npRef = ref("npRef");
const npRefMethod = async () => {
  await nextTick();
  if (npRef.value) {
    npRef.value.init();
  }
};
const cRef = ref("cRef");
const cRefMethod = async () => {
  await nextTick();
  if (cRef.value) {
    cRef.value.init();
  }
};
const uRef = ref("uRef");
const uRefMethod = async () => {
  await nextTick();
  if (uRef.value) {
    uRef.value.init();
  }
};
const iMRRef = ref("iMRRef");
const imrRefMethod = async () => {
  await nextTick();
  if (iMRRef.value) {
    iMRRef.value.init();
  }
};
const eWMARef = ref("EWMA");
const eWMARefMethod = async () => {
  await nextTick();
  if (eWMARef.value) {
    eWMARef.value.init();
  }
};
const year = ref("0");
const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 12,
  pageSizes: [12],
});
const lableValue = ref("");
const searchRef = ref(null);
const getTaskOption = async () => {
  const { data } = await getTaskCode({
    operationCode: JSON.parse(value.value).value,
  });
  taskOption.value = data;
};
const getTableData = async () => {
  const { data, code, msg } = await getData({
    ...searchRef.value.searchForm,
    pageNo: currentOption.page,
    pageSize: currentOption.limit,
    // yearStr: year.value,
    operation: lableValue.value,
  });
  if (code == "200") {
    tableData.value = data.records;
    showData.value = { ...data, list: null };
    // if (tableData.value.length > 0) {
    //   setChart1();
    //   setChart2();
    // }
    currentOption.total = data.totalCount;
    currentOption.page = data.pageNo;
    oldDataJSON.value = JSON.stringify(data.records);
  }
  disabled.value = false;
};
const searchForm = [
  {
    label: "日期",
    prop: "createds",
    type: "daterange",
  },
  {
    label: "产品型号",
    prop: "model",
    type: "input",
  },
  {
    label: "生产批号",
    prop: "batchNo",
    type: "input",
  },
];
//编辑状态
const editStatus = ref(false);
const addStatus = ref(false);
const changeEditstatus = () => {
  editStatus.value = !changeEditstatus.value;
  addStatus.value = false;
};
const changeaddstatus = () => {
  addStatus.value = !addStatus.value;
  editStatus.value = false;
};
const canceleOp = () => {
  addStatus.value = false;
  editStatus.value = false;
  reset();
};
const Y1value = ref([]);
const X1array = ref([]);
const setY1value = () => {
  Y1value.value = [];
  tableData.value.forEach((item) => {
    Y1value.value.push(item.avg);
  });
  Y1value.value.unshift("");
  Y1value.value.push("");

  chartsOption1.value.series[0].data = Y1value.value;
};
const setX1array = async () => {
  X1array.value = await [];
  tableData.value.forEach((item, index) => {
    X1array.value.push(index + 1);
  });
  X1array.value.unshift("");
  X1array.value.push("");
  chartsOption1.value.xAxis[0].data = X1array.value;
};
const { dicts } = useDictionaryStore();
const importStatus = ref(false);
const disabled = ref(false);
const tableData = ref([]);
//Form
const ruleFormRef = ref(null);

const addItem = {
  // abnormal: "",
  accuracy1: 0,
  accuracy2: 0,
  accuracy3: 0,
  accuracy4: 0,
  accuracy5: 0,
  analyseUser: "",
  avg: 0,
  batchNo: "",
  checkDeviceNo: "",
  checkUser: "",
  dateStr: "",
  measure: "",
  model: "",
  range: 0,
};
const rules = {
  qualityTaskId: [
    {
      required: true,
      trigger: "change",
    },
  ],
  dateStr: [
    {
      required: true,
      trigger: "change",
    },
  ],
  model: [
    {
      required: true,

      trigger: "change",
    },
  ],
  batchNo: [
    {
      required: true,

      trigger: "change",
    },
  ],
  accuracy1: [
    {
      required: true,

      trigger: "change",
    },
  ],
  accuracy2: [
    {
      required: true,

      trigger: "change",
    },
  ],
  accuracy3: [
    {
      required: true,

      trigger: "change",
    },
  ],
  accuracy4: [
    {
      required: true,

      trigger: "change",
    },
  ],
  accuracy5: [
    {
      required: true,

      trigger: "change",
    },
  ],
  checkUser: [
    {
      required: true,

      trigger: "change",
    },
  ],
  checkDeviceNo: [
    {
      required: true,

      trigger: "change",
    },
  ],
  // abnormal: [
  //   {
  //     required: true,

  //     trigger: "change",
  //   },
  // ],
  analyseUser: [
    {
      required: true,

      trigger: "change",
    },
  ],
  measure: [
    {
      required: false,

      trigger: "change",
    },
  ],
};
const resItem = {
  // abnormal: "",
  analyseUser: "",
  batchNo: "",
  checkDeviceNo: "",
  checkUser: "",
  dateStr: "",
  measure: "",
  model: "",
};
const addData = ref({
  // abnormal: "",
  analyseUser: "",
  batchNo: "",
  checkDeviceNo: "",
  checkUser: "",
  dateStr: "",
  measure: "",
  model: "",
});
const accuracysSum = ref(0);
const taskChange = (value) => {
  taskOption.value.forEach((item) => {
    if (item.id == value) {
      addData.value.model = item.prodtModel;
      accuracysSum.value = Number(item.processCount);
      addData.value.accuracys = [];
      let array = [];
      for (let i = 0; i < accuracysSum.value; i++) {
        array.push(0);
      }
      addData.value.accuracys = array;
    }
  });
};
const oldDataJSON = ref("");
const showData = ref({});
const url = ref(import.meta.env.VITE_APP_BASE_API + "/api/v1/spc/import");
const headers = { Authorization: `${localStorage.getItem("token")}` };
const opOptions = ref([...dicts.spc_operation]);
const sccOptions = ref([...dicts.spc_control_chart]);
const setChart1Info = () => {
  // chartsOption1.value.title[0].text = `上限=${showData.value.avgMax ? showData.value.avgMax : "-"}`;
  // chartsOption1.value.title[0].text = `x̄=${showData.value.avgAvg ? showData.value.avgAvg : "-"}`;
  chartsOption1.value.series[0].markLine.data[0].yAxis = JSON.parse(
    value.value
  ).avgMax;
  chartsOption1.value.series[0].markLine.data[0].label.formatter = `                          上限=${
    JSON.parse(value.value).avgMax ? JSON.parse(value.value).avgMax : "0"
  }`;
  chartsOption1.value.series[0].markLine.data[1].yAxis = JSON.parse(value.value)
    .avgMin
    ? JSON.parse(value.value).avgMin
    : 0;
  chartsOption1.value.series[0].markLine.data[1].label.formatter = `           下限=${JSON.parse(value.value).avgMin ? JSON.parse(value.value).avgMin : "0"}`;
  chartsOption1.value.series[0].markLine.data[2].yAxis = JSON.parse(
    value.value
  ).avgMid;
  chartsOption1.value.series[0].markLine.data[2].label.formatter = `x̄=${
    JSON.parse(value.value).avgMid
  }`;
  // chartsOption1.value.title[2].text = `下限=${showData.value.avgMin ? showData.value.avgMin : "0"}`;
};
const setChart2Info = () => {
  // chartsOption2.value.title[0].text = `上限=${showData.value.rangeMax ? showData.value.rangeMax : "-"}`;
  // chartsOption2.value.title[0].text = `R=${showData.value.rangeAvg ? showData.value.rangeAvg : "-"}`;
  chartsOption2.value.series[0].markLine.data[0].yAxis = JSON.parse(
    value.value
  ).rangeMax;
  chartsOption2.value.series[0].markLine.data[0].label.formatter = `                          上限=${
    JSON.parse(value.value).rangeMax ? JSON.parse(value.value).rangeMax : "0"
  }`;
  chartsOption2.value.series[0].markLine.data[1].yAxis = JSON.parse(value.value)
    .rangeMin
    ? JSON.parse(value.value).rangeMin
    : 0;
  chartsOption2.value.series[0].markLine.data[1].label.formatter = `           下限=${
    JSON.parse(value.value).rangeMin ? JSON.parse(value.value).rangeMin : "0"
  }`;
  chartsOption2.value.series[0].markLine.data[2].yAxis = JSON.parse(
    value.value
  ).rangeMid;
  chartsOption2.value.series[0].markLine.data[2].label.formatter = `x̄=${
    JSON.parse(value.value).rangeMid
  }`;
  // chartsOption2.value.title[2].text = `下限=${showData.value.rangeMin ? showData.value.rangeMin : "0"}`;
};
const setChart1 = () => {
  setChart1Info();
  setY1value();
  setX1array();
  charts1.value.setOption(chartsOption1.value, true);
};
const setChart2 = () => {
  setChart2Info();
  setY2value();
  setX2array();
  charts2.value.setOption(chartsOption2.value, true);
};
//修改
const updataItem = (row) => {
  editStatus.value = true;
  addData.value = row;
  addStatus.value = true;
};
//导入按钮
const onSuccess = (res) => {
  const { code, msg, data } = res;
  if (code != "200") {
    ElMessage.error(msg);
  } else {
    tableData.value = data.list;
    showData.value = { ...data, list: null };
    setChart1();
    setChart2();
    oldDataJSON.value = JSON.stringify(data.list);
    importStatus.value = true;
    ElMessage.success(msg);
  }
};
const taskOption = ref([]);
const value = ref(opOptions.value[0].remark);
const title = ref("调阻精度");

var value2 = ref("");

const showLable = ref("调阻");
const changeSelect = () => {
  setTimeout(async () => {
    getTaskOption();
    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;
    }
    await getTableData();
    chartsOption1.value.title[0].text = `${title.value}的Xbar-R控制图`;
    // tableData.value.forEach((item) => {
    //   item.accuracy1 = 0;
    //   item.accuracy2 = 0;
    //   item.accuracy3 = 0;
    //   item.accuracy4 = 0;
    //   item.accuracy5 = 0;
    //   item.avg = 0;
    //   item.range = 0;
    // });
    // setChart1();
    changeSelect2();
  }, 0);
};
const changeSelect2 = () => {
  if (value2.value === "Xbar-R") {
    xbarRRefMethod();
  } else if (value2.value === "Xbar-S") {
    xbarSRefMethod();
  } 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();
  }
};

// const searchData = computed(() =>
//   tableData.value.filter((item) => item.data.includes(searchValue.value))
// );
const selectRef = ref(null);
//保存
const changeEdit = async () => {
  if (disabled.value == false) {
    disabled.value = true;
  } else {
    const { data, code, msg } = await getHandleData([...tableData.value]);
    if (code == "200") {
      ElMessage.success(msg);
      tableData.value = data.list;
      showData.value = { ...data, list: null };
      setChart1();
      setChart2();
      oldDataJSON.value = JSON.stringify(data.list);
    }
    disabled.value = false;
  }
};
const cancelEdit = () => {
  tableData.value = JSON.parse(oldDataJSON.value);
  disabled.value = false;
};
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 submit = () => {
  if (editStatus.value == true) {
    updateSubmit();
  } else {
    addSubmit();
  }
};
const addSubmit = async () => {
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const { data, code } = await addDatas({
        ...addData.value,
        yearStr: year.value,
        operation: lableValue.value,
      });
      if (code == "200") {
        ElMessage.success("添加成功！");
        reset();
        getTableData();
      }
    } else {
      ElMessage.error("请检查表单信息");
    }
  });
};
const deleteSubmit = async (id) => {
  const { data, code } = await deleteData({
    id,
  });
  if (code == "200") {
    ElMessage.success("删除成功！");
    getTableData();
  }
};
const updateSubmit = async () => {
  const { data, code } = await updateData({
    ...addData.value,
  });
  if (code == "200") {
    ElMessage.success("更新成功！");
    reset();
    getTableData();
  }
};
const reset = () => {
  addStatus.value = false;
  editStatus.value = false;
  addData.value = { ...resItem };
  searchRef.value.searchForm = {};
  currentOption.value = {
    total: 0,
    page: 0,
    limit: 12,
    pageSizes: [12],
    operation: value.value,
  };
  getTableData();
};
const setView = () => {
  setHeight();
  charts1.value = echarts.init(document.getElementById("charts"));
  charts2.value = echarts.init(document.getElementById("charts1"));
  charts1.value.setOption(chartsOption1.value, true);
  charts2.value.setOption(chartsOption2.value, true);
};
onMounted(async () => {
  getTaskOption();
  setHeight();
  year.value = new Date().getFullYear() + "";
  opOptions.value.forEach((item) => {
    if (item.dictLabel == showLable.value) {
      lableValue.value = item.dictValue;
    }
  });

  await getTableData();
  value2.value = "Xbar-R";
  xbarRRefMethod();

  // nextTick(() => {
  //   charts1.value = echarts.init(document.getElementById("charts"));
  //   charts2.value = echarts.init(document.getElementById("charts1"));
  //   charts1.value.setOption(chartsOption1.value, true);
  //   charts2.value.setOption(chartsOption2.value, true);
  // });
  // window.addEventListener("resize", setView);
});
onBeforeUnmount(() => {
  // window.removeEventListener("resize", setView);
});
</script>

<style lang="scss" scoped>
@media print {
  #print {
    margin-left: -18%;
  }
}
.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: 200px;
    .header {
      height: 120px;
      border-bottom: 2px solid #00000010;
      padding: 20px;
    }
    .body {
      padding: 20px;
    }
  }
  .databox {
    flex: 1;
    border-left: 2px solid #00000010;
    .box {
      height: 710px;
      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>
