<template>
  <div>
    <div class="csTitle-header">
      <el-button type="primary" @click="startCreat">选择设备</el-button>
      <span>产品编码: {{ csObj?.materialName }}</span>
      <span>产品名称: {{ csObj?.materialCode }}</span>
      <span>测试人员: {{ csObj?.creator }}</span>
      <span>测试时间: {{ csObj?.created }}</span>
    </div>

    <div class="bottom-box">
      <el-scrollbar style="height: calc(100vh - 300px); margin-top: 10px">
        <el-table :data="selectedDeviceList" class="left-selected-devs">
          <el-table-column fixed prop="deviceNo" label="设备编号" align="center" />
          <el-table-column fixed prop="deviceName" label="设备名称" align="center" />

          <el-table-column label="操作">
            <template #default="scope">
              <el-button link class="btnText" type="primary" @click="preToStart(scope.row)"> 开始 </el-button>

              <el-button link class="btnText" type="primary" @click="preToLook(scope.row)"> 查看 </el-button>
              <el-button link class="btnText" type="danger" @click="preDel(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <div class="tableView-cssj">
        <el-table :data="tableData">
          <el-table-column fixed prop="parameterName" label="测试项目" align="center" />
          <el-table-column fixed prop="deviceCode" label="测试设备" align="center" />
          <el-table-column fixed prop="value" label="测试值" align="center" />
          <!--        <el-table-column prop="flag" align="center" label="是否合格">
          <template #default="scope">
            <span
              :class="{
                'red-text': scope.row.flag == 0,
                'green-text': scope.row.writeData == 1,
              }"
            >
              {{ scope.row.flag == 1 ? "合格" : "不合格" }}
            </span>
          </template>
        </el-table-column>-->

          <!--      <el-table-column label="操作" fixed="right" width="200">-->
          <!--        <template #default="scope">-->
          <!--                    <el-button-->
          <!--                      link-->
          <!--                      class="btnText"-->
          <!--                      type="primary"-->
          <!--                      @click="handleEdit(scope.row)"-->
          <!--                    >-->
          <!--                      编辑-->
          <!--                    </el-button>-->

          <!--                    <el-popconfirm-->
          <!--                      :visible="scope.row.dialogVisible"-->
          <!--                      title="您确认删除吗？（此操作不可逆）"-->
          <!--                      width="300"-->
          <!--                      @cancel="scope.row.dialogVisible = false"-->
          <!--                      @confirm="handleDelete(scope.row)"-->
          <!--                    >-->
          <!--                      <el-button> 取消 </el-button>-->
          <!--                      <el-button type="primary"> 确认 </el-button>-->
          <!--                      <template #reference>-->
          <!--                        <el-button-->
          <!--                          link-->
          <!--                          class="btnText"-->
          <!--                          type="primary"-->
          <!--                          @click="scope.row.dialogVisible = true"-->
          <!--                          >删除</el-button-->
          <!--                        >-->
          <!--                      </template>-->
          <!--                    </el-popconfirm>-->
          <!--        </template>-->
          <!--      </el-table-column>-->
        </el-table>
        <div style="margin-top: 25px">
          <el-pagination
            background
            :page-size="20"
            :pager-count="8"
            layout="->,prev, pager, next"
            :total="pageTotal"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <el-dialog title="编辑测试项" v-model="dialogVisible">
      <el-form ref="form" :model="editRow" label-width="100px">
        <el-form-item label="测试项目">
          <el-input v-model="editRow.proName" />
        </el-form-item>
        <el-form-item label="测试名称">
          <el-input v-model="editRow.name" />
        </el-form-item>
        <el-form-item label="测试值">
          <el-input v-model="editRow.value" />
        </el-form-item>
        <!--        <el-form-item label="是否合格">
          <el-radio v-model="editRow.flag" :label="1">合格</el-radio>
          <el-radio v-model="editRow.flag" :label="0">不合格</el-radio>
        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="handleDialogCancel">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">确 定</el-button>
      </template>
    </el-dialog>

    <CrudTable
      ref="ctableRef"
      tableTitle="设备绑定"
      :multipleRow="multipleRow"
      tableType="DEVICE"
      @selected-sure="onSelectedFinish"
    />

    <el-dialog title="设置时间" v-model="startSettingVisible" append-to-body style="top: 20%">
      <el-date-picker
        v-model="startSettingTime"
        type="datetimerange"
        start-placeholder="请选择开始时间"
        end-placeholder="请选择结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
      />

      <template #footer>
        <el-button @click="afterTimeCancel">取 消</el-button>
        <el-button type="primary" @click="afterTimeStart">开始</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  addCSSJ,
  dataArrayList,
  deleteCSSJ,
  startCSSJTesting,
  getDeviceList,
  getDeviceListPage,
  getDataDevice,
  addDataDevice,
  delDataDevice,
} from "@/api/prosteps/ceshishuju";
import { useProcessStore } from "@/store";
import { emitter, EventsNames } from "@/utils/common";
import { useCrud } from "@/hooks/userCrud";
const multipleRow = ref(true);

const dataDeviceList = ref([]);
const onSelectedFinish = (val) => {
  dataDeviceList.value = [];
  if (Object.keys(val).length == 0) {
    ElMessage.error("请选择设备,数据不能为空!");
    return;
  }
  val?.forEach((item, index) => {
    const dataDevice = ref({});
    dataDevice.value.processId = store.scanInfo.id;
    dataDevice.value.seqNo = store.scanInfo.seqNo;
    dataDevice.value.operationId = store.scanInfo.operationId;
    dataDevice.value.operationName = store.scanInfo.operationName;
    dataDevice.value.workOrderCode = store.scanInfo.workOrderCode;
    dataDevice.value.deviceNo = item.deviceNo;
    dataDevice.value.deviceName = item.deviceName;
    dataDevice.value.deviceType = item.deviceType;
    dataDeviceList.value.push(dataDevice.value);
  });
  addDataDevice(dataDeviceList.value).then((res) => {
    if (res.code === "200") {
      const param = ref({ processId: store.scanInfo.id });
      getDataDevice(param.value).then((data) => {
        selectedDeviceList.value = JSON.parse(JSON.stringify(data.data));
      });
    }
  });
};
const store = useProcessStore();
const ctableRef = ref({});
const csObj = ref<any>(null);
const startCreat = () => {
  ctableRef.value?.mergeOption({
    selection: true,
    reserveSelection: true,
  });
  ctableRef.value.startSelect({ deviceType: "DDS_HYG" });
};
const currentPage = ref(1);
const handlePageChange = (val: number) => {
  currentPage.value = val;
  getList();
};
const tableData = ref<any[]>([]);

const currentRow = ref<any>(null);
const handleCurrentChange = (val: any) => {
  currentRow.value = val;
};
const pageTotal = ref(0);
const deviceList = ref<any[]>([]);
const getList = () => {
  if (!currentToStartRow || !currentToStartRow.deviceNo) {
    tableData.value = [];
    return;
  }
  dataArrayList(store.scanInfo.id, currentToStartRow.deviceNo, currentPage.value.toString()).then((res: any) => {
    csObj.value = res.data;
    tableData.value = JSON.parse(res.data.testData);
    pageTotal.value = res.data.total;
    console.log(tableData.value, "返回的列表数据");
  });
};
const deviceSearch = ref<any>({});
const currentPageAll = ref(1);
const pageSizeAll = ref(12);
const totalAll = ref(0);
const sizeChangeAll = (val: number) => {};
const currentChangeAll = (val: number) => {
  getDeviceListPageAll();
};
const selectedDeviceList = ref<any[]>([]);
const handleSelectionAllChange = (vals: any[]) => {
  console.log("handleSelectionAllChange", vals);
  selectedDeviceList.value = JSON.parse(JSON.stringify(vals));
};

const afterTimeStart = () => {
  const testParam = ref({});
  testParam.value.processId = store.scanInfo.id;
  testParam.value.operationName = store.scanInfo.operationName;
  testParam.value.deviceNo = currentToStartRow.deviceNo;
  testParam.value.deviceType = currentToStartRow.deviceType;
  testParam.value.times = startSettingTime.value;
  const param = ref({ processId: store.scanInfo.id });

  startCSSJTesting(testParam.value).then((data) => {
    if (data.code === "200") {
      dialogDevice.value = false;
      startSettingVisible.value = false;
    }
    if (!emitter.all.has(EventsNames.TEST_DATA)) {
      emitter.on(EventsNames.TEST_DATA, (mesaage: any) => {
        console.log("测试数据获取成功");
        getList();
      });
    }
  });
  getDataDevice(param.value).then((data) => {
    selectedDeviceList.value = JSON.parse(JSON.stringify(data.data));
  });
};
onMounted(() => {
  getList();
  deviceSearch.value.deviceType = "DDS_HYG";
  getDeviceListPageAll();
  const param = ref({ processId: store.scanInfo.id });
  getDataDevice(param.value).then((data) => {
    selectedDeviceList.value = JSON.parse(JSON.stringify(data.data));
  });
});

const getDeviceListPageAll = () => {
  let p = {
    deviceType: "DDS",
    pageSize: pageSizeAll.value,
    pageNo: currentPageAll.value,
  };
  getDeviceListPage(p).then((res: any) => {
    deviceList.value = res.data.records;
    totalAll.value = res.data.totalCount;
  });
};

const startTesting = () => {
  /*startCSSJTesting(store.scanInfo.id).then(() => {
    if (!emitter.all.has(EventsNames.TEST_DATA)) {
      emitter.on(EventsNames.TEST_DATA, (mesaage: any) => {
        console.log("测试数据获取成功");
        getList();
      });
    }
  });*/
  dialogDevice.value = true;
};

onUnmounted(() => {
  if (emitter.all.has(EventsNames.TEST_DATA)) {
    emitter.off(EventsNames.TEST_DATA);
    emitter.all.delete(EventsNames.TEST_DATA);
  }
});

const handleDelete = (row: any) => {
  deleteCSSJ(csObj.value.id).then(() => {
    getList();
  });
};

// 编辑相关代码
const dialogVisible = ref(false);
const dialogDevice = ref(false);
const editRow = ref<any>(null);
const handleEdit = (row: any) => {
  editRow.value = row;
  dialogVisible.value = true;
};
const handleDialogConfirm = () => {
  dialogVisible.value = false;

  let p = {
    materialCode: csObj.value.materialCode,
    materialName: csObj.value.materialName,
    processId: store.scanInfo.id,
    testData: [JSON.stringify(editRow.value)],
    workOrderId: csObj.value.workOrderId,
  };
  addCSSJ(p).then(() => {
    getList();
  });
};
const handleDialogCancel = () => {
  dialogVisible.value = false;
};

// 开始测试后选择时间
let currentToStartRow = null;
const rowTime = ref([]);
const preToStart = (row) => {
  currentToStartRow = JSON.parse(JSON.stringify(row));
  if (row.beginTime) {
    rowTime.value.push(row.beginTime);
    rowTime.value.push(row.endTime);
  }
  startSettingTime.value = rowTime.value;
  rowTime.value = [];
  startSettingVisible.value = true;
};

const preDel = (row) => {
  delDataDevice({ id: row.id }).then((data) => {
    if (data.code === "200") {
      ElMessage.success("操作成功!");
      const param = ref({ processId: store.scanInfo.id });
      getDataDevice(param.value).then((data) => {
        selectedDeviceList.value = JSON.parse(JSON.stringify(data.data));
      });
    }
  });
};
const preToLook = (row) => {
  currentToStartRow = JSON.parse(JSON.stringify(row));
  // startSettingVisible.value = true;
  getList();
};

const startSettingVisible = ref(false);
const startSettingTime = ref<any>(null);
const afterTimeCancel = () => {
  startSettingVisible.value = false;
};
</script>

<style scoped lang="scss">
.csTitle-header {
  display: flex;
  justify-content: space-between;

  font-size: 18px;
  font-weight: bold;
}

.bottom-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-selected-devs {
  width: 450px;
  background-color: #fff;
  border-radius: 16px;
  height: calc(100vh - 300px);
  margin-right: 10px;
}
.tableView-cssj {
  width: 550px;
  flex: 1;
  height: calc(100vh - 300px);
  padding: 20px 0px;
  border-radius: 16px;
  margin-top: 10px;
  background-color: #fff;
}
.btn {
  width: 180px;
  border-radius: 16px;
  height: 40px;
  font-size: 16px;
  margin: 10px 0;
}
.red-text {
  color: red;
}
.green-text {
  color: green;
}
</style>
