<template>
  <div class="containerBox">
    <el-collapse>
      <el-collapse-item
        v-for="(item, index) in materialsData"
        :key="index + item"
        :name="index"
        :disabled="item.deviceType == 'FJDJC'"
        style="position: relative"
      >
        <template #title>
          {{
            dictS.getLableByValue("device_type", item.deviceType)
          }}&nbsp;&nbsp;&nbsp;<span
            :class="item.state ? 'round green' : 'round'"
          ></span
          >&nbsp; &nbsp;
          <span
            @click.stop="
              addItem(item.deviceNo, item.deviceName, item.deviceType, index)
            "
            v-if="item.deviceType != 'FJDJC'"
            class="opear"
            style="font-size: 18px; color: rgb(10, 89, 247); font-weight: 600"
            >新增数据</span
          >
          <el-select
            v-model="taskValue"
            v-if="item.deviceType == 'DDLSD'"
            placeholder="请选择任务"
            size="large"
            style="position: absolute; right: 200px; z-index: 2; width: 140px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            class="ces"
            type="primary"
            style="position: absolute; right: 60px; z-index: 2"
            v-if="item.deviceType != 'FJDJC'"
            @click.stop="
              startTest(item.deviceName, item.deviceNo, item.deviceType)
            "
            :disabled="item.deviceType == 'DDLSD' && !taskValue"
            >开始检测</el-button
          >
        </template>
        <!-- <el-table
          :data="DDLSDTableData"
          v-if="item.deviceType == 'DDLSD'"
          border
        >
          <el-table-column prop="deviceNo" label="任务号" />
          <el-table-column prop="deviceNo" label="圈数（r）" />
          <el-table-column prop="deviceNo" label="扭力（mN.m）" />
          <el-table-column prop="deviceNo" label="拧紧结果" />
          <el-table-column prop="deviceNo" label="警报" />
        </el-table> -->
        <el-table
          :data="tableData[index]"
          v-if="item.deviceType != 'FJDJC'"
          border
        >
          <el-table-column
            v-for="str in configeObj(materialsData[index].deviceType)"
            :key="str"
            :prop="str"
            :label="showLable(str)"
            width="230px"
          >
            <template #default="{ row }">
              <div v-if="!row.updateStatus">
                {{ row.data[str] }}
              </div>
              <div v-else>
                <el-input v-model="tableData[index][row.index].data[str]" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="created" label="采集时间" width="230px">
            <template #default="{ row }">
              <div v-if="!row.updateStatus">
                {{ row.created }}
              </div>
              <div v-else>
                <el-input v-model="tableData[index][row.index].created" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="150px" fixed="right">
            <template #default="scope">
              <span
                class="opear"
                v-if="scope.row.updateStatus || scope.row.addStatus"
                @click="toSuccess(index, scope.$index)"
                >完成</span
              >
              <span class="opear" v-else @click="toDelete(index, scope.$index)"
                >删除</span
              >
              <span
                class="opear"
                v-if="scope.row.updateStatus || scope.row.addStatus"
                @click="toCancel(index, scope.$index)"
                >取消</span
              ><span class="opear" v-else @click="toEdit(index, scope.$index)"
                >编辑</span
              >
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          v-if="item.deviceType != 'FJDJC'"
          v-model:limit="pageS[index].pageSize"
          v-model:page="pageS[index].pageNo"
          :total="pageS[index].total"
          @pagination="paginationChange(index)"
          position="right"
        />
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script setup>
import {
  getScrewdriverData,
  getAcquisitionData,
  addAcquisitionData,
  updateAcquisitionData,
  delAcquisitionData,
  getTaskList,
  startData,
} from "@/api/prosteps/screwdriver";
import { useProcessStore } from "@/store";
import { useDictionaryStore } from "@/store";
import { emitter, EventsNames } from "@/utils/common";
import dayjs from "dayjs";
const dictS = useDictionaryStore();
const store = useProcessStore();
const tableData = ref([]);
const materialsData = ref([]);
const router = useRouter();
const taskValue = ref("");
const toStartData = async (data) => {
  const { code } = await startData(data);
  if (code == "200") {
    ElMessage.success("开始检测成功");
  }
};
const getTask = async () => {
  const { data } = await getTaskList({});
  options.value = [];
  data.forEach((item) => {
    options.value.push({
      value: item.id,
      label: item.taskName,
    });
  });
};
const options = ref([]);

const startTest = (a, b, c) => {
  let obj = {
    deviceName: a,
    deviceNo: b,
    deviceType: c,
    operationId: store.scanInfo.operationId,
    operationName: store.processInfo.operationName,
    processId: store.scanInfo.id,
    seqNo: store.useSeqNo,
    workOrderCode: store.odersData.workOrderCode,
    taskId: taskValue.value,
  };
  toStartData(obj);
};
const showLable = (key) => {
  switch (key) {
    case "CH5Val":
      return "CH5";
    case "CH6Val":
      return "CH6";
    case "DataTimes":
      return "采集时间";
    case "torquetarget":
      return "当前任务目标扭力";
    case "tightenTorqueMax":
      return "拧紧过程中最大扭力值";
    case "taskNo":
      return "当前任务号";
    case "warning":
      return "警报";
    case "tightenResult":
      return "最终拧紧结果";
    case "totalCycles":
      return "总圈数";
    case "length":
      return "长度";
    case "height":
      return "高度";
    case "DDLSD1":
      return "拧紧的模式";
    case "DDLSD2":
      return "拧紧旋转方向";
    case "DDLSD3":
      return "目标扭力";
    case "DDLSD4":
      return "扭力保持时间";
    case "DDLSD5":
      return "浮高界定圈数";
    case "DDLSD6":
      return "滑牙界定圈数";
    case "DDLSD7":
      return "触发速度切换的扭力比值";
    case "DDLSD8":
      return "扭力补偿值";
    case "DDLSD9":
      return "开启浮高滑牙检测";
    case "DDLSD10":
      return "触发速度切换的扭力";
    case "DDLSD11":
      return "触发速度切换的速度比值";
    case "DDLSD12":
      return "扭力偏差上限";
    case "DDLSD13":
      return "扭力偏差下限";
    case "DDLSD14":
      return "扭力免检圈数";
    case "DDLSD15":
      return "拧松有效触发的扭力阀值";
    case "DDLSD16":
      return "拧松有效触发的保持时间";
    case "DDLSD17":
      return "自由旋转方向";
    case "DDLSD18":
      return "STEP-00拧紧圈数";
    case "DDLSD19":
      return "STEP-00拧紧速度";
    case "DDLSD20":
      return "STEP-01拧紧圈数";
    case "DDLSD21":
      return "STEP-01拧紧速度";
    case "DDLSD22":
      return "STEP-02拧紧圈数";
    case "DDLSD23":
      return "STEP-02拧紧速度";
    case "DDLSD24":
      return "STEP-03拧紧圈数";
    case "DDLSD25":
      return "STEP-03拧紧速度";
    case "DDLSD26":
      return "STEP-04拧紧圈数";
    case "DDLSD27":
      return "STEP-04拧紧速度";
    case "DDLSD28":
      return "STEP-00拧松圈数";
    case "DDLSD29":
      return "STEP-00拧松速度";
    case "DDLSD30":
      return "STEP-01拧松圈数";
    case "DDLSD31":
      return "STEP-01拧松速度";
    case "DDLSD32":
      return "STEP-02拧松圈数";
    case "DDLSD33":
      return "STEP-02拧松速度";
    case "DDLSD34":
      return "STEP-00自由圈数";
    case "DDLSD35":
      return "STEP-00自由速度";
    default:
      return key;
  }
};

const toEdit = (index, rowIndex) => {
  tableData.value[index][rowIndex].updateStatus = true;
};
const toDelete = async (index, rowIndex) => {
  const no = tableData.value[index][rowIndex].deviceNo;
  const { code } = await delAcquisitionData({
    id: tableData.value[index][rowIndex].id,
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
    setAcquisitionDatas(no, index);
  }
};
const toSuccess = (index, rowIndex) => {
  if (tableData.value[index][rowIndex].addStatus == true) {
    addInfo(index, rowIndex);
  } else {
    editInfo(index, rowIndex);
  }
};
const addInfo = async (index, rowIndex) => {
  const { code } = await addAcquisitionData({
    ...tableData.value[index][rowIndex],
    data: JSON.stringify(tableData.value[index][rowIndex].data),
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
    tableData.value[index][rowIndex].addStatus = false;
    tableData.value[index][rowIndex].updateStatus = false;
  }
};
const editInfo = async (index, rowIndex) => {
  const { code } = await updateAcquisitionData({
    ...tableData.value[index][rowIndex],
    data: JSON.stringify(tableData.value[index][rowIndex].data),
  });
  if (code == "200") {
    ElMessage.success("操作成功！");
    tableData.value[index][rowIndex].updateStatus = false;
  }
};
const toCancel = (index, rowIndex) => {
  if (tableData.value[index][rowIndex].addStatus == true) {
    tableData.value[index].splice(rowIndex, 1);
  } else {
    tableData.value[index][rowIndex].updateStatus = false;
    tableData.value[index][rowIndex].data = JSON.parse(
      tableData.value[index][rowIndex].resdata
    );
  }
};
const configeObj = (type) => {
  switch (type) {
    //温湿度
    case "WXDJC":
      return ["CH5Val", "CH6Val", "DataTimes"];
    case "YBKC":
      return ["length"];
    case "GDC":
      return ["height"];
    case "WKDLT":
      return ["temperature"];
    //电动螺丝刀
    case "DDLSD":
      return [
        "taskNo",
        "torquetarget",
        "tightenTorqueMax",
        "warning",
        "tightenResult",
        "totalCycles",
      ];
    default:
      return ["数据1", "数据2", "数据3"];
  }
};
const addItem = (no, name, type, index) => {
  let data = {};
  switch (type) {
    case "WXDJC":
      data = { CH5Val: "", CH6Val: "", DataTimes: "" };
      break;
    case "YBCK":
      data = { CH5Val: "", CH6Val: "", DataTimes: "" };
      break;
    case "WKDLT":
      data = {temperature:""};
      break;
    case "GDC":
      data = { CH5Val: "", CH6Val: "", DataTimes: "" };
      break;
    case "DDLSD":
      data = {
        DDLSD1: "",
        DDLSD2: "",
        DDLSD3: "",
        DDLSD4: "",
        DDLSD5: "",
        DDLSD6: "",
        DDLSD7: "",
        DDLSD8: "",
        DDLSD9: "",
        DDLSD10: "",
        DDLSD11: "",
        DDLSD12: "",
        DDLSD13: "",
        DDLSD14: "",
        DDLSD15: "",
        DDLSD16: "",
        DDLSD17: "",
        DDLSD18: "",
        DDLSD19: "",
        DDLSD20: "",
        DDLSD21: "",
        DDLSD22: "",
        DDLSD23: "",
        DDLSD24: "",
        DDLSD25: "",
        DDLSD26: "",
        DDLSD27: "",
        DDLSD28: "",
        DDLSD29: "",
        DDLSD30: "",
        DDLSD31: "",
        DDLSD32: "",
        DDLSD33: "",
        DDLSD34: "",
        DDLSD35: "",
      };
      break;
  }
  tableData.value[index].push({
    deviceNo: no,
    deviceName: name,
    deviceType: type,
    data: data,
    operationId: store.odersData.operationId,
    operationName: store.processInfo.operationName,
    processId: store.scanInfo.id,
    seqNo: store.scanInfo.seqNo,
    workOrderCode: store.odersData.workOrderCode,
    index: tableData.value[index].length,
    addStatus: true,
    updateStatus: true,
  });
};
const tableKey = ref(false);
const getData = async () => {
  const res = await getScrewdriverData();
  materialsData.value = res.data;
  materialsData.value.forEach((item, index) => {
    pageS.value.push({ ...page });
    getAcquisitionDatas(item.deviceNo, index);
  });
};
const paginationChange = (index1) => {
  materialsData.value.forEach((item, index) => {
    if (index == index1) {
      setAcquisitionDatas(item.deviceNo, index);
    }
  });
};
const getAcquisitionDatas = async (No, index) => {
  const res = await getAcquisitionData({
    deviceNo: No,
    operationId: store.odersData.operationId,
    pageNo: pageS.value[index].pageNo,
    pageSize: pageS.value[index].pageSize,
    processId: store.scanInfo.id,
  });
  pageS.value[index].total = res.data.totalCount;
  res.data.records.forEach((item, index) => {
    item.resdata = item.data;
    item.data = JSON.parse(item.data);
    item.updateStatus = false;
    item.index = index;
  });
  tableData.value[index] = res.data.records;
};
const setAcquisitionDatas = async (No, index) => {
  const res = await getAcquisitionData({
    deviceNo: No,
    operationId: store.odersData.operationId,
    pageNo: pageS.value[index].pageNo,
    pageSize: pageS.value[index].pageSize,
    processId: store.scanInfo.id,
  });
  pageS.value[index].total = res.data.totalCount;
  res.data.records.forEach((item, index) => {
    item.resdata = item.data;
    item.data = JSON.parse(item.data);
    item.updateStatus = false;
    item.index = index;
  });
  tableData.value[index] = res.data.records;
};
const DDLSDTableData = ref([]);
const pageS = ref([]);
const page = {
  pageSize: 10,
  pageNo: 1,
  total: 0,
};
onMounted(async () => {
  await getData();
  getTask();
});
emitter.on(EventsNames.GETDATA_DDLSD, (name) => {
  materialsData.value.forEach((item, index) => {
    if (item.deviceType == "DDLSD" && item.deviceNo == name) {
      setAcquisitionDatas(item.deviceNo, index);
    }
  });
});
emitter.on(EventsNames.GETDATA_YBKC, (name) => {
  materialsData.value.forEach((item, index) => {
    if (item.deviceType == "YBKC" && item.deviceNo == name) {
      setAcquisitionDatas(item.deviceNo, index);
    }
  });
});
emitter.on(EventsNames.GETDATA_GDC, (name) => {
  materialsData.value.forEach((item, index) => {
    if (item.deviceType == "GDC" && item.deviceNo == name) {
      setAcquisitionDatas(item.deviceNo, index);
    }
  });
});
emitter.on(EventsNames.GETDATA_WKDLT, (name) => {
  materialsData.value.forEach((item, index) => {
    if (item.deviceType == "WKDLT" && item.deviceNo == name) {
      setAcquisitionDatas(item.deviceNo, index);
    }
  });
});
</script>

<style lang="scss" scoped>
.ces {
  font-size: 18px;
  height: 40px;
}
.containerBox {
  background-color: white;
  padding: 20px;
}
:deep(.el-collapse-item__header) {
  background-color: rgb(241, 243, 245) !important;
  padding: 0 20px;
  height: 80px;
}
:deep(.el-badge) {
  font-size: $f24;
}
:deep(.el-collapse-item__header) {
  font-size: $f24;
}
:deep(.el-pagination) {
  span {
    font-weight: 600 !important;
  }
}
:deep(.el-collapse-item__wrap) {
  padding: 20px;
  border: 1px solid rgb(241, 243, 245);
}
.opear {
  font-size: 16px;
  margin-right: 5px;
  cursor: pointer;
}
.round {
  width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: red;
}
.green {
  background-color: green;
}
</style>
