<template>
  <div class="container1">
    <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-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="
                  exportData(
                    '/api/v1/spc/downloadTemplate',
                    '/spc/template/XBarR控制图数据导入模版.xlsx'
                  )
                "
                >模版下载</el-button
              >
              <el-button
                style="margin-left: 15px"
                v-if="!addStatus && !editStatus"
                type="primary"
                size="small"
                class="btn"
                @click="changeaddstatus"
                >新增</el-button
              >
              <el-button
                style="margin-left: 15px"
                v-if="!addStatus && !editStatus"
                type="primary"
                size="small"
                class="btn"
                @click="compute"
                >计算</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 - 150 + 'px',
                width: maxWidth + 'px',
              }"
              :show-overflow-tooltip="true"
              :row-class-name="tableRowClassName"
            >
              <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="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
                align="center"
                prop="avg"
                label="平均值"
                width="60"
              /><el-table-column
                align="center"
                prop="range"
                label="极差"
                width="60"
              />--><!--<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" label="是否异常">
                <template #default="{ row }"
                  ><span>{{ row.abnormal }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="abnormal1"
                label="异常原因"
                :show-overflow-tooltip="false"
              >
                <template #default="{ row }">
                  <el-tooltip placement="top">
                    <template #content>
                      <div
                        v-for="(item, index) in row.abnormal1.split('，')"
                        :key="index"
                      >
                        <span>{{ item }}</span>
                      </div>
                    </template>
                    <div class="ellipsis-text">
                      {{ row.abnormal1 }}
                    </div>
                  </el-tooltip>
                </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="240" prop="" label="操作">
                <template #default="{ row }">
                  <el-button
                    v-if="row.source === '自动'"
                    type="primary"
                    size="small"
                    class="btn"
                    @click="dataAcquisition(row)"
                    style="height: 25px"
                    >采集数据</el-button
                  >
                  <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"
              v-model:limit="currentOption.limit"
              @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="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="source">
                <el-input :disabled="true" v-model="addData.source" />
              </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>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref } from "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";
import { XBarRCompute, collectData } from "@/api/analysis";
import { useCrud } from "@/hooks/userCrud";

const { Utils } = useCrud({
  src: "/api/v1/spc/pDownloadTemplate",
});
const { exportData } = Utils;
const emit = defineEmits(["tableData"]);

const dataAcquisition = async (row) => {
  const { data } = await collectData({
    qualitySpcRecordId: row.id,
    model: row.model,
    batchNo: row.batchNo,
    operation: lableValue.value,
  });
  emit("tableData", data);
  getTableData();
};

const compute = async () => {
  const accuracysList = ref([]);
  for (const item of tableData.value) {
    if (item.accuracys?.length > 0) {
      accuracysList.value.push(item.accuracys);
    } else {
      ElMessage.error(`产品 "${item.model}" 的 "${item.batchNo}" 批次数据为空`);
      return;
    }
  }
  const { data } = await XBarRCompute({
    dataList: accuracysList.value,
    scale: 4,
  });
  emit("tableData", data);
};

const tableRowClassName = ({ row }) => {
  if (row.abnormal === "是") {
    return "warning-row";
  }
  return "";
};

const { dicts } = useDictionaryStore();

const year = ref("0");
const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 40, 50],
});
const lableValue = ref("");
const searchRef = ref(null);
const getTaskOption = async () => {
  const { data } = await getTaskCode({
    operationCode: lableValue.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 };
    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 disabled = ref(false);
const tableData = ref([]);
//Form
const ruleFormRef = ref(null);
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;
      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 oldDataJSON = ref("");
const showData = ref({});
const opOptions = ref([...dicts.spc_operation]);

//修改
const updataItem = (row) => {
  editStatus.value = true;
  addData.value = row;
  addStatus.value = true;
};
const taskOption = ref([]);
const value = ref(opOptions.value[0].remark);
const showLable = ref("调阻");
const maxHeight = ref(null);
const maxWidth = ref(null);
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 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 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导入成功！");
    uploadRef.value.clearFiles();
    getTableData();
  } else {
    ElMessage.error("Excel导入失败！");
  }
};

onMounted(async () => {
  setHeight();
  year.value = new Date().getFullYear() + "";
  opOptions.value.forEach((item) => {
    if (item.dictLabel == showLable.value) {
      lableValue.value = item.dictValue;
    }
  });

  await getTableData();
  uploadUrl.value =
    import.meta.env.VITE_APP_BASE_API +
    "/api/v1/spc/xBarRUpload?operation=" +
    lableValue.value;
});
onBeforeUnmount(() => {});

const init = (data) => {
  lableValue.value = data;
  getTaskOption();
  getTableData();
};

// 暴露 init 方法
defineExpose({
  init,
});
</script>

<style lang="scss" scoped>
@media print {
  #print {
    margin-left: -18%;
  }
}
:deep(.el-table .warning-row) {
  background-color: rgb(241, 142, 142) !important;
}
.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>
