<template>
  <div>
    <div class="csTitle-header">
      <el-button type="primary" @click="startTesting">选择设备</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>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>

      <el-table :data="tableData" class="tableView-cssj">
        <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>

    <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>
    <el-dialog title="设备列表" v-model="dialogDevice" append-to-body>
      <el-table
        :data="deviceList"
        style="width: 100%; height: calc(100vh - 400px); margin-bottom: 10px"
        ref="singleTableRef"
        row-key="id"
        highlight-current-row
        @current-change="handleCurrentChange"
        @selection-change="handleSelectionAllChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="id" width="180" v-if="false" />
        <el-table-column prop="deviceNo" label="设备编号" />
        <el-table-column prop="deviceName" label="设备名称" />
      </el-table>
      <el-pagination
        v-model:current-page="currentPageAll"
        v-model:page-size="pageSizeAll"
        layout="total, prev, pager, next"
        :total="totalAll"
        background
        @size-change="sizeChangeAll"
        @current-change="currentChangeAll"
      />
      <template #footer>
        <el-button @click="dialogDevice = false">取 消</el-button>
        <el-button type="primary" @click="dialogDevice = false"
          >确 定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog title="设置时间" v-model="startSettingVisible" append-to-body>
      <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,
} from "@/api/prosteps/ceshishuju";
import { useProcessStore } from "@/store";
import { emitter, EventsNames } from "@/utils/common";

const store = useProcessStore();

const csObj = ref<any>(null);

const tableData = ref<any[]>([]);

const currentRow = ref<any>(null);
const handleCurrentChange = (val: any) => {
  currentRow.value = val;
};
const deviceList = ref<any[]>([]);
const getList = () => {
  dataArrayList(store.scanInfo.id).then((res: any) => {
    csObj.value = res.data;
    tableData.value = JSON.parse(res.data.testData);
    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 dialogConfirm = () => {
  console.log(currentRow);
  if (!currentRow || !currentRow.value || !currentRow.value.deviceNo) {
    ElMessage.error("未选择设备!");
    return;
  }
  startCSSJTesting(store.scanInfo.id, currentRow.value.deviceNo).then(
    (data) => {
      if (data.code === "200") {
        dialogDevice.value = false;
      }
      if (!emitter.all.has(EventsNames.TEST_DATA)) {
        emitter.on(EventsNames.TEST_DATA, (mesaage: any) => {
          console.log("测试数据获取成功");
          getList();
        });
      }
    }
  );
};
onMounted(() => {
  getList();
  deviceSearch.value.deviceType = "DDS";
  getDeviceListPageAll();
});

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 preToStart = (row) => {
  currentToStartRow = JSON.parse(JSON.stringify(row));
  startSettingVisible.value = true;
};
const preToLook = (row) => {
  // currentToStartRow = JSON.parse(JSON.stringify(row));
  // startSettingVisible.value = true;
};

const startSettingVisible = ref(false);
const startSettingTime = ref<any>(null);
const afterTimeStart = () => {
  console.log(startSettingTime.value);
};
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: 400px;
  background-color: #fff;
  border-radius: 16px;
  height: calc(100vh - 300px);
  margin-right: 10px;
}
.tableView-cssj {
  flex: 1;
  height: calc(100vh - 300px);
  padding: 20px 0px;
  border-radius: 16px;
  margin-top: 10px;
}
.btn {
  width: 180px;
  border-radius: 16px;
  height: 40px;
  font-size: 16px;
  margin: 10px 0;
}
.red-text {
  color: red;
}
.green-text {
  color: green;
}
</style>
