<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>
          <span class="diviceName">
            {{ dictS.getLableByValue("device_type", item.deviceType) }}</span
          >
          &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
          >
          <!-- DDLSD -->
          <el-select
            v-model="taskValue"
            v-if="item.deviceType == 'DDLSD'"
            placeholder="请选择任务"
            size="large"
            @change="changeTask"
            style="position: absolute; right: 460px; 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: 340px; z-index: 2"
            v-if="item.deviceType == 'DDLSD'"
            @click.stop="
              startTest1(item.deviceName, item.deviceNo, item.deviceType)
            "
            :disabled="
              (item.deviceType == 'DDLSD' && !taskValue) ||
              btnDisabled ||
              setDiabledStatus
            "
            >设置参数</el-button
          >
          <el-select
            v-model="taskId"
            v-if="item.deviceType == 'DDLSD'"
            placeholder="选择任务号"
            size="large"
            style="position: absolute; right: 180px; z-index: 2; width: 140px"
          >
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <!-- DDLSD -->
          <!-- WKDLT -->

          <el-input-number
            @click.stop
            style="
              position: absolute;
              right: 300px;
              z-index: 2;
              margin-bottom: 1px;
            "
            v-model="tipTemperature"
            :min="50"
            :max="450"
            v-if="item.deviceType == 'WKDLT'"
          />
          <span
            v-if="item.deviceType == 'WKDLT'"
            style="
              position: absolute;
              right: 345px;
              z-index: 2;
              margin-bottom: 1px;
              font-size: 16px;
              color: black !important;
            "
            >℃</span
          >
          <el-button
            class="ces"
            type="primary"
            style="position: absolute; right: 180px; z-index: 2"
            v-if="item.deviceType == 'WKDLT'"
            @click.stop="setTipTemperature"
            :disabled="tipTemperatureDisabled"
            >设置温度</el-button
          >
          <!-- WKDLT -->
          <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) || btnDisabled
            "
            >开始检测</el-button
          >
        </template>

        <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)"
          >
            <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,
  setUpData,
  setUpData1,
} from "@/api/prosteps/screwdriver";
import { useProcessStore } from "@/store";
import { useDictionaryStore } from "@/store";
import { emitter, EventsNames } from "@/utils/common";
defineOptions({
  name: "Screwdriver",
});
const dictS = useDictionaryStore();
const store = useProcessStore();
const tipTemperature = ref(50);
const tipTemperatureDisabled = ref(false);
const setTipTemperature = async () => {
  try {
    tipTemperatureDisabled.value = true;
    const { code } = await setUpData1({ tipTemperature: tipTemperature.value });
    if (code == "200") {
      ElMessage.success("设置成功！");
    }
  } catch (e) {
  } finally {
    setTimeout(() => {
      tipTemperatureDisabled.value = false;
    }, 5000);
  }
};
const changeTask = () => {
  setDiabledStatus.value = false;
};
const setDiabledStatus = ref(false);
const tableData = ref([]);
const materialsData = ref([]);
const router = useRouter();
const taskValue = ref("");
const taskId = ref("1");
const btnDisabled = ref(false);
const toStartData = async (data) => {
  try {
    btnDisabled.value = true;
    const { code } = await startData(data);
    if (code == "200") {
      ElMessage.success("开始检测....");
    }
  } catch (e) {
  } finally {
    setTimeout(() => {
      btnDisabled.value = false;
    }, 3000);
  }
};
const toStartData1 = async (data) => {
  try {
    btnDisabled.value = true;
    const { code } = await setUpData(data);
    if (code == "200") {
      ElMessage.success("设置成功！");
      setDiabledStatus.value = true;
    }
  } catch (e) {
  } finally {
    setTimeout(() => {
      btnDisabled.value = false;
    }, 3000);
  }
};
const getTask = async () => {
  let params = {
    operationCode: store.processInfo.operationCode,
    materialNo: store.scanInfo.materialCode,
  };
  const { data } = await getTaskList(params);
  options.value = [];
  data.forEach((item) => {
    options.value.push({
      value: item.id,
      label: item.taskName,
    });
  });
};
const options = ref([]);
const options2 = ref([
  { value: "1", label: "任务0" },
  { value: "2", label: "任务1" },
  { value: "3", label: "任务2" },
  { value: "4", label: "任务3" },
  { value: "5", label: "任务4" },
  { value: "6", label: "任务5" },
  { value: "7", label: "任务6" },
  { value: "8", label: "任务7" },
]);
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,
    smallTaskId: taskId.value,
  };
  toStartData(obj);
};
const startTest1 = (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,
    smallTaskId: taskId.value,
  };
  toStartData1(obj);
};
const showLable = (key) => {
  switch (key) {
    case "tipTemperature":
      return "温度";
    case "CH5Val":
      return "温度";
    case "CH6Val":
      return "湿度";
    case "DataTimes":
      return "采集时间";
    case "torquetarget":
      return "当前任务目标扭力";
    case "tightenTorqueMax":
      return "拧紧过程中最大扭力值";
    case "taskNo":
      return "当前任务号";
    case "taskName":
      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"];
    case "YBKC":
      return ["length"];
    case "GDC":
      return ["height"];
    case "WKDLT":
      return ["tipTemperature"];
    //电动螺丝刀
    case "DDLSD":
      return [
        "taskName",
        "taskNo",
        "tightenResult",
        "totalCycles",
        "torquetarget",
        "tightenTorqueMax",
        "warning",
      ];
    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>
:deep(.el-collapse-item) {
}
:deep(.el-collapse-item__wrap) {
  background-color: black;
}
.diviceName {
  color: var(--ohos-text);
}
.ces {
  font-size: 18px;
  height: 40px;
}
.containerBox {
  padding: 20px;
  border-radius: 16px !important;
  overflow: hidden;
}
:deep(.el-collapse-item__header) {
  background-color: var(--ohos-box-bg) !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 var(--ohos-box-bg);
}
.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>
