<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 class="text">上限：{{ value ? JSON.parse(value).up : "-" }}</div>-->
        <!--        <div class="text">下限：{{ value ? JSON.parse(value).down : "-" }}</div>-->
        <!--        <div class="text">-->
        <!--          计量单位：{{ value ? JSON.parse(value).unit : "-" }}-->
        <!--        </div>-->
        <div class="edit-item" @dblclick="startEdit('up')">
          <span v-if="!editing.up" class="text"
            >上限：{{ displayValue.up }}</span
          >
          <input
            v-else
            v-model.number="editValue.up"
            ref="upInput"
            @blur="saveEdit('up')"
            @keyup.enter="saveEdit('up')"
            @keyup.escape="cancelEdit1('up')"
            class="edit-input"
          />
        </div>

        <div class="edit-item" @dblclick="startEdit('down')">
          <span v-if="!editing.down" class="text"
            >下限：{{ displayValue.down }}</span
          >
          <input
            v-else
            v-model.number="editValue.down"
            ref="downInput"
            @blur="saveEdit('down')"
            @keyup.enter="saveEdit('down')"
            @keyup.escape="cancelEdit1('down')"
            class="edit-input"
          />
        </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="resetData"
              />
            </div>
            <div class="btns">
              <!-- <el-button
                v-if="!editStatus && !addStatus"
                type="primary"
                class="btn"
                @click="changeEditstatus"
                >编辑</el-button
              > -->
              <!--              <el-button-->
              <!--                v-if="!addStatus && !editStatus"-->
              <!--                type="primary"-->
              <!--                class="btn"-->
              <!--                v-print="'#print'"-->
              <!--                @click="printFnc"-->
              <!--                size="small"-->
              <!--                >打印</el-button-->
              <!--              >-->
              <el-upload
                v-if="!addStatus && !editStatus"
                style="float: left"
                :action="uploadUrl"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :limit="1"
                accept=".xlsx, .xls"
                :show-file-list="false"
                ref="uploadRef"
              >
                <el-button size="small" type="primary">Excel导入</el-button>
              </el-upload>
              <el-button
                v-if="!addStatus && !editStatus"
                style="margin-left: 15px"
                type="primary"
                size="small"
                class="btn"
                @click="
                  downloadSPCTemplate(
                    '/api/v1/spc/downloadTemplate',
                    '/spc/template/过程能力指标数据导入模板.xlsx'
                  )
                "
                >模板下载</el-button
              >
              <el-button
                v-if="!addStatus && !editStatus"
                type="primary"
                class="btn"
                @click="changeaddstatus"
                size="small"
                >新增</el-button
              >
              <el-button
                v-if="editStatus || addStatus"
                type="success"
                class="btn"
                @click="submit"
                id="submit"
                >确定</el-button
              >
              <el-button
                v-if="editStatus || addStatus"
                type="info"
                class="btn"
                @click="canceleOp"
                id="cancel"
                >取消</el-button
              >
              <el-button
                style="margin-left: 15px"
                v-if="!addStatus && !editStatus"
                type="primary"
                size="small"
                class="btn"
                @click="downloadData"
                >导出</el-button
              >
              <!--              <span v-if="!addStatus && !editStatus" style="margin: 10px"
                >年份：</span
              >
              <el-date-picker
                v-if="!addStatus && !editStatus"
                v-model="year"
                class="btn"
                type="year"
                style="width: 160px"
                value-format="YYYY"
                placeholder="Pick a year"
                :clear-icon="''"
                @change="getTableData"
              />-->
            </div>
            <!-- 导入代码 -->
            <!-- <div class="btns">
              <el-button
                class="btn"
                :type="disabled ? 'success' : 'primary'"
                @click="changeEdit"
                v-if="importStatus"
                >{{ disabled ? "保存" : "编辑" }}</el-button
              >
              <el-button
                v-if="disabled && importStatus"
                type="info"
                class="btn"
                @click="cancelEdit"
                >取消</el-button
              >
              <el-upload
                class="btn"
                :action="url"
                :show-file-list="false"
                accept=".xlsx, .xls"
                multiple
                :on-success="onSuccess"
                :headers="headers"
              >
                <el-button class="btn" type="primary">导入</el-button>
              </el-upload>
            </div> -->
          </div>
          <!-- <div class="tableTitle">
          调阻精度一致性检测表
          <span style="float: right; right: 30px">2024年</span>
        </div> -->
          <div class="info" v-show="!addStatus">
            <div id="print" v-loading="printLoading">
              <div class="tableTitle">
                <div></div>
                <div>{{ title }}一致性检测表</div>
                <div></div>
              </div>
              <el-table
                v-if="!printStatus"
                :data="showTableData"
                border
                :style="{
                  height: Height - 50 + 'px',
                  width: maxWidth + 'px',
                }"
                :show-overflow-tooltip="true"
              >
                <el-table-column
                  align="center"
                  prop="dateStr"
                  sortable
                  label="日期"
                >
                  <template #default="{ row }"
                    ><span>{{ row.dateStr }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="model" label="产品型号">
                  <template #default="{ row }"
                    ><span>{{ row.model }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="code" label="产品编号">
                  <template #default="{ row }"
                    ><span>{{ row.code }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="batchNo" label="生产批号">
                  <template #default="{ row }"
                    ><span>{{ row.batchNo }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="source" label="数据来源">
                  <template #default="{ row }"
                    ><span>{{ row.source }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  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
                  width="100"
                  align="center"
                  prop="accuracys"
                  label="数据"
                >
                  <template #default="{ row }">
                    <div v-for="(item, index) in row.accuracys" :key="index">
                      <span>数值{{ index + 1 }}: {{ item }}</span>
                    </div>
                  </template>
                </el-table-column>-->
                <!--                                <el-table-column
                  align="center"
                  prop="Cpk"
                  label="Cpk值"
                  width="80"
                >
                  <template #default="{ row }"
                    ><span>{{ Number(row.cpk).toFixed(2) }}</span>
                  </template>
                </el-table-column>-->
                <!--                <el-table-column align="center" 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" prop="remark" label="备注">
                  <template #default="{ row }"
                    ><span>{{ row.remark }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  width="300"
                  prop=""
                  label="操作"
                  id="opear"
                >
                  <template #default="{ row }">
                    <el-button
                      v-if="row.source === '自动'"
                      :type="loadingRows[row.id] ? 'info' : 'primary'"
                      size="small"
                      :loading="loadingRows[row.id]"
                      @click="dataAcquisition(row)"
                      :disabled="loadingRows[row.id]"
                      style="height: 25px"
                    >
                      {{ loadingRows[row.id] ? "数据采集中..." : "采集数据" }}
                    </el-button>
                    <el-button
                      type="primary"
                      class="btn"
                      @click="computeCPK(row.id)"
                      style="height: 25px"
                      size="small"
                      >计算Cpk</el-button
                    >
                    <el-button
                      type="primary"
                      class="btn"
                      @click="updataItem(row.Index)"
                      style="height: 25px"
                      size="small"
                      >修改</el-button
                    >
                    <el-button
                      type="info"
                      class="btn"
                      style="height: 25px"
                      @click="deleteSubmit(row.id)"
                      size="small"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 打印table -->
              <el-table
                v-else
                :data="showTableData"
                :span-method="objectSpanMethod"
                id="table1"
                border
                :style="{
                  height: Height - 160 + 'px',
                  width: maxWidth + 'px',
                }"
                cell-class-name="printStyle"
              >
                <el-table-column
                  align="center"
                  width="60"
                  prop="dateStr"
                  sortable
                  label="日期"
                >
                  <template #default="{ row }"
                    ><span>{{ row.dateStr }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  width="60"
                  prop="model"
                  label="产品型号"
                >
                  <template #default="{ row }"
                    ><span>{{ row.model }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  width="60"
                  prop="batchNo"
                  label="生产批号"
                >
                  <template #default="{ row }"
                    ><span>{{ row.accuracy1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" :label="title">
                  <el-table-column
                    align="center"
                    prop="accuracy1"
                    width="44"
                    label="数值1"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy1 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy2"
                    width="44"
                    label="数值2"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy2 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy3"
                    width="44"
                    label="数值3"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy3 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy4"
                    width="44"
                    label="数值4"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy4 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy5"
                    width="44"
                    label="数值5"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy5 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy6"
                    width="44"
                    label="数值6"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy6 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy7"
                    width="44"
                    label="数值7"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy7 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy8"
                    width="44"
                    label="数值8"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy8 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy9"
                    width="44"
                    label="数值9"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy9 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    prop="accuracy10"
                    width="44"
                    label="数值10"
                  >
                    <template #default="{ row }"
                      ><span>{{ row.accuracy10 }}</span>
                    </template>
                  </el-table-column> </el-table-column
                ><el-table-column
                  align="center"
                  prop="Cpk"
                  label="Cpk值"
                  width="50"
                >
                  <template #default="{ row }"
                    ><span>{{ Number(row.cpk).toFixed(2) }}</span>
                  </template>
                </el-table-column>
                <!--                <el-table-column
                  align="center"
                  width="60"
                  prop="checkUser"
                  label="检测人"
                >
                  <template #default="{ row }"
                    ><span>{{ row.checkUser }}</span>
                  </template> </el-table-column
                ><el-table-column
                  align="center"
                  prop="checkDeviceNo"
                  label="检查设备编号"
                  width="80"
                >
                  <template #default="{ row }"
                    ><span>{{ row.checkDeviceNo }}</span>
                  </template>
                </el-table-column>-->
                <el-table-column
                  align="center"
                  prop="abnormal"
                  width="40"
                  label="是否异常"
                >
                  <template #default="{ row }"
                    ><span>{{ row.abnormal }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="analyseUser"
                  label="分析人"
                  width="60"
                >
                  <template #default="{ row }"
                    ><span>{{ row.analyseUser }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  width="60"
                  align="center"
                  prop="measure"
                  label="处置措施"
                >
                  <template #default="{ row }"
                    ><span>{{ row.measure }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  width="60"
                  align="center"
                  prop="remark"
                  label="备注"
                >
                  <template #default="{ row }"
                    ><span>{{ row.remark }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <!--              <div class="illustrate">-->
              <!--                <div>-->
              <!--                  1）Cpk值为表征内引线键合强度一致性的参数，通过相应的软件计算得出，内引线键合强度一致性是否符合要求的判据：Cpk值≥1.33。-->
              <!--                </div>-->
              <!--                <div>2）“备注”栏填写被测内引线的材料和规格。</div>-->
              <!--              </div>-->
            </div>
            <Pagination
              :total="currentOption.total"
              :page="currentOption.page"
              :limit="currentOption.limit"
              :pageSizes="currentOption.pageSizes"
              v-model:page="currentOption.page"
              v-model:limit="currentOption.limit"
              @pagination="getTableData"
            />
          </div>
          <div class="info" v-if="addStatus">
            <el-scrollbar :style="{ height: Height - 80 + 'px' }">
              <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="Number(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="code">
                  <el-input :disabled="true" v-model="addData.code" />
                </el-form-item>
                <el-form-item label="数据来源" prop="source">
                  <el-input :disabled="true" v-model="addData.source" />
                </el-form-item>
                <!--                <el-form-item label="产品型号" prop="model">
                  &lt;!&ndash; <el-select  v-model="addData.model">
                    <el-option
                      v-for="item in modelOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select> &ndash;&gt;
                  <el-input v-model="addData.model" />
                </el-form-item>-->
                <el-form-item label="生产批号" prop="batchNo">
                  <el-input v-model="addData.batchNo" />
                </el-form-item>
                <!--                <template v-for="(item, index) in 30" :key="index">
                  <el-form-item
                    :label="'数值' + addIndex(index)"
                    :prop="'accuracy' + addIndex(index)"
                    :rules="[
                      {
                        required: true,
                        trigger: 'change',
                      },
                    ]"
                  >
                    <el-input-number
                      :precision="2"
                      :step="0.01"
                      style="width: 100%"
                      v-model="addData[`accuracy${addIndex(index)}`]"
                    />
                  </el-form-item>
                </template>-->
                <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-item label="备注" prop="remark">
                  <el-input
                    maxlength="40"
                    show-word-limit
                    type="textarea"
                    v-model="addData.remark"
                  />
                </el-form-item>
              </el-form>
            </el-scrollbar>
          </div>
        </div>
        <!-- <div class="box" v-show="!addStatus">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <div style="display: flex; align-items: center">
              <div class="bg"></div>
              控制图绘制
            </div>

            <el-button
              type="primary"
              v-print="'#charts'"
              style="margin-left: 10px; height: 25px"
              >打 印</el-button
            >
          </div>
          <div class="info">
            <div id="charts" :style="{ height: maxHeight / 2 + 'px' }"></div>
            <div id="charts1" :style="{ height: maxHeight / 2 + 'px' }"></div>
          </div>
        </div> -->
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { useDictionaryStore } from "@/store";
import {
  getData2,
  addDatas,
  deleteData,
  updateData,
  getTaskCode,
  cpkCompute,
  collectData,
  exportData, saveExceptionData,
} from "@/api/analysis";
import Search from "@/components/Search/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getDictList, updateDict } from "@/api/dict";
import { ref } from "vue";
import { useCrud } from "@/hooks/userCrud";

const { Utils } = useCrud({
  src: "/api/v1/spc/pDownloadTemplate",
});
const { downloadSPCTemplate } = Utils;

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

// 初始值
let initialValue = ref({
  up: 0, // 默认上限值
  down: 0, // 默认下限值
});

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

// 编辑状态
const editing = reactive({
  up: false,
  down: false,
});

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

// 输入框引用
const upInput = ref(null);
const downInput = ref(null);

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

  nextTick(() => {
    const inputRef = field === "up" ? upInput.value : downInput.value;
    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;
};

// 在你的组件 setup 中
const loadingRows = ref({});

const dataAcquisition = async (row) => {
  loadingRows.value = { ...loadingRows.value, [row.id]: true };
  try {
    // 这里替换为你的实际请求
    const { code } = await collectData({
      qualitySpcRecordId: row.id,
      model: row.model,
      batchNo: row.batchNo,
      operation: lableValue.value,
    });
    if (200 == code) {
      ElMessage.success("数据采集成功！");
      getTableData();
    }
  } catch (error) {
    console.error("数据采集失败:", error);
    // 可以在这里添加错误处理，比如显示错误消息
  } finally {
    loadingRows.value = { ...loadingRows.value, [row.id]: false };
  }
};
const cpkApi = async (id) => {
  const { data } = await cpkCompute({
    spcRecordId: id,
  });

  return data;
};

const computeCPK = async (id) => {
  try {
    // 显示加载中的提示
    ElMessageBox.alert("计算中...", "提示", {
      confirmButtonText: "确定",
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
    });

    // 调用后台接口
    const response = await cpkApi(id);

    // 关闭加载中的提示
    ElMessageBox.close();

    const result = ref("");
    if ("error" in response.data) {
      result.value = response.data.error;
    } else {
      const { product, batch, process, cpk, status, mean, std, pp, ppk, ppm } =
        response.data;
      result.value = `产品: ${product}<br>
      批次: ${batch}<br>
      工序: ${process}<br>
      平均值: ${mean}<br>
      标准差: ${std}<br>
      CPK: ${cpk}<br>
      PP: ${pp}<br>
      PPK: ${ppk}<br>
      PPM: ${ppm}<br>
      评级: ${status}`;
    }

    // 显示计算结果
    ElMessageBox.alert(result.value, "计算结果", {
      confirmButtonText: "确定",
      dangerouslyUseHTMLString: true,
    });
  } catch (error) {
    // 处理错误
    ElMessageBox.close();
  }
};

const tableData = ref([]);
const printStatus = ref(false);
const printLoading = ref(false);
const taskOption = ref([]);
const getTaskOption = async () => {
  const { data } = await getTaskCode({
    operationCode: JSON.parse(value.value).value,
  });
  taskOption.value = data;
};
const accuracysSum = ref(0);
const taskChange = (value) => {
  taskOption.value.forEach((item) => {
    if (item.id == value) {
      addData.value.model = item.prodtModel;
      addData.value.code = item.prodtCode;
      addData.value.source = item.source;
      if (item.source === "手动") {
        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;
      } else {
        addData.value.accuracys = [];
      }
    }
  });
};

//打印功能
const printFnc = () => {
  printLoading.value = true;
  printStatus.value = true;
  setTimeout(() => {
    printStatus.value = false;
    printLoading.value = false;
  }, 0);
};
const showTableData = ref([]);
const year = ref("0");
//写死存放合并列 行参数【3,0，0,3,0,0...】
const state = reactive({
  spanArr: [], // 生成一个与行数相同的数组记录每一行设置的合并数
});
//设置合并列
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (
    columnIndex !== 3 &&
    columnIndex !== 4 &&
    columnIndex !== 5 &&
    columnIndex !== 6 &&
    columnIndex !== 7 &&
    columnIndex !== 8 &&
    columnIndex !== 9 &&
    columnIndex !== 10 &&
    columnIndex !== 11 &&
    columnIndex !== 12
  ) {
    if (state.spanArr[rowIndex]) {
      return {
        rowspan: 3,
        colspan: 1,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  } else {
    return {
      rowspan: 1,
      colspan: 1,
    };
  }
};
//解决动态表格数据视图不更新问题
const filterData = (data) => {
  // 合并内容相同的单元格
  let spanArr = [];
  data.forEach((item, index) => {
    spanArr.push(3);
    spanArr.push(0);
    spanArr.push(0);
  });
  state.spanArr = spanArr;
};

//设置展示tableData
const setTableData = (array) => {
  showTableData.value = [];
  //★Index 为实际接口数据Index
  array.forEach((item, index) => {
    let obj1 = { ...item, Index: index };
    // let obj2 = { ...item, Index: index };
    // let obj3 = { ...item, Index: index };
    // for (let i = 1; i < 11; i++) {
    //   obj2[`accuracy${i}`] = obj2[`accuracy${i + 10}`];
    //   obj3[`accuracy${i}`] = obj3[`accuracy${i + 20}`];
    // }
    showTableData.value.push(obj1);
    // showTableData.value.push(obj2);
    // showTableData.value.push(obj3);
  });
};
//接口获取实际data
const getTableData = async () => {
  const { data, code, msg } = await getData2({
    ...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 };
    setTableData(tableData.value);
    // setChart1();
    // setChart2();
    currentOption.total = data.totalCount;
    currentOption.page = data.pageNo;
    oldDataJSON.value = JSON.stringify(data.records);
  }
  disabled.value = false;
};

const downloadData = async () => {
  exportData({
    ...searchRef.value.searchForm,
    pageNo: currentOption.page,
    pageSize: currentOption.limit,
    // yearStr: year.value,
    operation: lableValue.value,
  }).then((response) => {
    const fileData = response.data;
    // const fileName = decodeURI(
    //   response.headers["content-disposition"].split(";")[1].split("=")[1]
    // );
    const fileName = "过程能力数据.xlsx";
    const fileType =
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  });
};


const searchRef = ref(null);
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 = () => {
  X1array.value = [];
  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);

//Form
const ruleFormRef = ref(null);
const addIndex = (index) => {
  return index + 1;
};
const rules = {
  dateStr: [
    {
      required: true,
      trigger: "change",
    },
  ],
  model: [
    {
      required: true,

      trigger: "change",
    },
  ],
  batchNo: [
    {
      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: "",
  avg: 0,
  batchNo: "",
  checkDeviceNo: "",
  checkUser: "",
  dateStr: "",
  measure: "",
  model: "",
  range: 0,
};
const addData = ref({
  abnormal: "",
  analyseUser: "",
  avg: 0,
  batchNo: "",
  checkDeviceNo: "",
  checkUser: "",
  dateStr: "",
  measure: "",
  model: "",
  range: 0,
});
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 value = ref(opOptions.value[0].remark);
//分页参数
const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 40, 50],
});
const modelOptions = ref([]);
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 = showData.value.avgMax;
  chartsOption1.value.series[0].markLine.data[0].label.formatter = `                          上限=${showData.value.avgMax ? showData.value.avgMax : "0"}`;
  chartsOption1.value.series[0].markLine.data[1].yAxis = showData.value.avgMin
    ? showData.value.avgMin
    : 0;
  chartsOption1.value.series[0].markLine.data[1].label.formatter = `           下限=${showData.value.avgMin ? showData.value.avgMin : "0"}`;
  chartsOption1.value.series[0].markLine.data[2].yAxis = showData.value.avgAvg;
  chartsOption1.value.series[0].markLine.data[2].label.formatter = `x̄=${showData.value.avgAvg}`;
  // 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 =
    showData.value.rangeMax;
  chartsOption2.value.series[0].markLine.data[0].label.formatter = `                          上限=${showData.value.rangeMax ? showData.value.rangeMax : "0"}`;
  chartsOption2.value.series[0].markLine.data[1].yAxis = showData.value.rangeMin
    ? showData.value.rangeMin
    : 0;
  chartsOption2.value.series[0].markLine.data[1].label.formatter = `           下限=${showData.value.rangeMin ? showData.value.rangeMin : "0"}`;
  chartsOption2.value.series[0].markLine.data[2].yAxis =
    showData.value.rangeAvg;
  chartsOption2.value.series[0].markLine.data[2].label.formatter = `x̄=${showData.value.rangeAvg}`;
  // 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 = (index) => {
  editStatus.value = true;
  const data = JSON.parse(JSON.stringify(tableData.value[index]));
  addData.value = data;
  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 title = ref("调阻精度");

const showLable = ref("调阻");
const lableValue = ref("");
const changeSelect = () => {
  setTimeout(() => {
    getTaskOption();
    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;
    }
    getTableData();
    // chartsOption1.value.title[3].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();
    // setChart2();
  }, 0);
};

// 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",

      markLine: {
        silent: true,
        data: [
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `上限=${showData.value.avgMax ? showData.value.avgMax : "-"}`,
              color: "#333",
            },
            lineStyle: { type: "solid", color: "#333", width: 2 },
          },
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `下限=${showData.value.avgMin ? showData.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",

      markLine: {
        silent: true,
        data: [
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `上限=${showData.value.rangeMax ? showData.value.rangeMax : "-"}`,
              color: "#333",
            },
            lineStyle: { type: "solid", color: "#333", width: 2 },
          },
          {
            silent: false,
            yAxis: 0,
            label: {
              position: "end",
              formatter: `下限=${showData.value.rangeMin ? showData.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) {
      addData.value.type = "2";
      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) => {
  ElMessageBox.confirm("是否删除所选中数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    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 };
  currentOption.value = {
    total: 0,
    page: 1,
    limit: 10,
    pageSizes: [10, 20, 30, 40, 50],
  };
};

const resetData = () => {
  searchRef.value.searchForm = {};
  getTableData();
};

const uploadUrl = ref("");
const beforeUpload = (file) => {
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  if (!isExcel) {
    ElMessage.error("只能上传Excel文件!");
  }
  return isExcel;
};
const uploadRef = ref("uploadRef");
const handleSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("Excel导入成功！");
    getTableData();
  } else {
    ElMessage.error(response.msg);
  }
  uploadRef.value.clearFiles();
};

watch(
  () => showTableData.value,
  (newVal, oldVal) => {
    filterData(showTableData.value); // 在监测到tableData有更新后调用filterData
  },
  {
    deep: true,
  }
);
onMounted(async () => {
  getTaskOption();
  setHeight();
  year.value = new Date().getFullYear() + "";
  opOptions.value.forEach((item) => {
    if (item.dictLabel == showLable.value) {
      lableValue.value = item.dictValue;
    }
  });
  displayValue.value = JSON.parse(value.value);
  await getTableData();

  uploadUrl.value =
    import.meta.env.VITE_APP_BASE_API +
    "/api/v1/spc/xBarRUpload?type=2&operation=" +
    lableValue.value;
  // 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);
  // });
});
</script>

<style lang="scss" scoped>
@media print {
  #print {
    margin: 0;
    width: 100%;
    padding-right: 10px;
  }
  .illustrate {
    margin-top: 10px;
    padding-left: 20px;
  }
  .tableTitle {
    margin-bottom: 10px;
  }
  #table1 {
    span {
      font-size: 10px;
      fontweight: 300px;
      color: black;
      line-height: 11px !important;
    }
    :deep(.cell) {
      padding: 0 1px !important;
      font-size: 12px !important;
      line-height: 11px !important;
    }
    :deep(.el-table__cell) {
      padding: 0px !important;
      height: 36px !important;
      margin: 0px !important;
      border: 0.5px solid rgb(0, 0, 0, 1) !important;
    }
    height: 503px !important;
    width: 1030px !important;
    border: 2px solid rgba(0, 0, 0, 1);
    padding: 0px !important;
  }
  #opear {
    display: none;
  }
  .tableTitle {
    display: flex;
    justify-content: space-between;
    alignitems: center;
  }
}
.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;
  padding: 20px 0;
}
.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: 100%;
      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: 30px;
      //  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 {
        flex: 1;
        .tableTitle {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }
  }
}
</style>
