<template>
  <div style="padding: 20px">
    <el-form :model="form" :rules="formRules" ref="taskForm">
      <el-form-item prop="videoTasksName" label="算法名称">
        <el-input
          v-model="form.videoTasksName"
          size="mini"
          style="width: 200px"
          clearable
          placeholder="请输入算法名称"
        ></el-input>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" type="flex">
      <el-col :span="8">
        <el-card
          shadow="hover"
          :body-style="{ padding: '20px', height: 'calc(100vh - 280px)' }"
        >
          <span slot="header"
            >选择算法
            <p>
              已选则 <span class="number">{{ checkAnalysisList.length }}</span
              >个算法
            </p>
          </span>
          <div>
            <el-checkbox-group
              v-model="checkAnalysisList"
              size="small"
              :key="uniqueKey"
              style="height: calc(100vh - 320px); overflow-y: auto"
            >
              <!-- 自定义复选框组件 -->
              <div
                class="custom-checkbox"
                :class="{
                  'is-checked': checkAnalysisList.some(
                    (val) => item.algorithmId === val.algorithmId
                  ),
                }"
                @click="handleCheckboxChange(item)"
                v-for="item in analysisList"
                :key="item.algorithmId"
              >
                <div class="checkbox-inner">
                  <i
                    v-show="
                      checkAnalysisList.some(
                        (val) => item.algorithmId === val.algorithmId
                      )
                    "
                    class="el-icon-check"
                  ></i>
                </div>
                <div class="checkbox-content">
                  <p>{{ item.algorithmName }}</p>
                  <span>ID : {{ item.algorithmId }} </span>
                  <span>版本 {{ item.algorithmVersion }} </span>
                </div>
              </div>
            </el-checkbox-group>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card
          shadow="hover"
          :body-style="{ padding: '20px', height: 'calc(100vh - 280px)' }"
        >
          <span slot="header"
            >选择摄像头
            <p>
              已选则<span class="number">{{ checkCameraList.length }}</span
              >个摄像头
            </p>
          </span>
          <div>
            <el-table
              :data="cameraList"
              @selection-change="cameraChange"
              ref="cameraTable"
              row-key="cameraId"
              height="calc(100vh - 320px)"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="名称" prop="cameraName"></el-table-column>
              <el-table-column
                label="地址"
                prop="cameraPosition"
              ></el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card
          shadow="hover"
          :body-style="{ padding: '20px', height: 'calc(100vh - 280px)' }"
        >
          <span slot="header"
            >视频分析任务内容
            <p>
              <el-button
                type="primary"
                plain
                size="mini"
                @click="submitForm(0)"
              >
                <i class="el-icon-switch-button el-icon--left"></i>
                创建任务
              </el-button>
              <el-button type="primary" size="mini" @click="submitForm(1)">
                <i class="el-icon-finished el-icon--left"></i>
                立即启用
              </el-button>
            </p>
          </span>
          <div>
            <transition-group name="list" tag="div">
              <div
                class="custom-checkbox"
                :class="{
                  selected: selectedAlgorithmIndex === index, // 新增选中状态
                }"
                @click="handleAlgorithmClick(item, index)"
                v-for="(item, index) in checkAnalysisList"
                :key="index"
              >
                <div class="checkbox-content">
                  <p>{{ item.algorithmName }}</p>
                  <!-- 替换el-tag为原生标签 -->
                  <div
                    v-for="tag in item.checkCameraList"
                    :key="tag.cameraId"
                    class="custom-tag"
                    :class="[tag.type]"
                  >
                    <span>{{ tag.cameraName }}</span>
                    <button
                      class="close-btn"
                      @click="setUpCamera(item, tag)"
                      style="maring-right: 10px"
                    >
                      <i class="el-icon-s-tools"></i>
                    </button>
                    <button class="close-btn" @click="deleteTag(item, tag)">
                      <i class="el-icon-delete" style="color: red"></i>
                    </button>
                  </div>
                  <!-- 原有其他代码保持不变... -->

                  <p>
                    <span>ID : {{ item.algorithmId }} </span>
                    <span>版本 {{ item.algorithmVersion }} </span>
                  </p>
                </div>
              </div>
            </transition-group>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="算法配置"
      :visible.sync="cameraDialogVisible"
      append-to-body
      width="30%"
    >
      <div class="camera-dialog-title">
        <div>
          <span>算法名称</span>
          <p>{{ algorithmDiaData.algorithmName }}</p>
        </div>
        <div>
          <span>摄像头</span>
          <p>{{ cameraDiaData.cameraName }}</p>
        </div>
      </div>
      <el-row type="flex" align="middle" class="compact-row">
        <el-col :span="4">
          <div class="compact-label">
            <span>算法阈值</span>
            <el-tooltip content="阈值取数为整数" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
        </el-col>
        <el-col :span="20">
          <el-input
            v-model="cameraDiaData.interval"
            size="mini"
            placeholder="输入阈值"
            class="compact-input"
          />
        </el-col>
      </el-row>

      <el-row type="flex" align="middle" class="compact-row">
        <el-col :span="4">
          <div class="compact-label">检测区域</div>
        </el-col>
        <el-col :span="20">
          <el-radio-group
            v-model="cameraDiaData.useRoi"
            size="mini"
            class="compact-radio"
            v-if="cameraDialogVisible"
          >
            <el-radio label="false" class="custom-radio">全图</el-radio>
            <el-radio label="true" class="custom-radio">自定义</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <Draw
        v-if="cameraDiaData.useRoi === 'true'"
        :callback="getLocalInfo"
        :val="cameraDiaData.roiPoints"
        :cameraId="cameraDiaData.cameraId"
      ></Draw>
      <div class="camera-dialog-footer">
        <el-button
          size="small"
          class="dialog-btn cancel-btn"
          @click="cameraDialogVisible = false"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          size="small"
          class="dialog-btn confirm-btn"
          @click="handleSaveConfig"
        >
          保存配置
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAlgorithmList } from "@/api/business/algorithmconfig.js";
import { getCameraList } from "@/api/business/cameraconfig.js";
import Draw from "./draw.vue";
import {
  addVideoAnalysisTask,
  updateVideoAnalysisTask,
} from "@/api/business/videoanalysistasks.js";
export default {
  name: "addVideoAnlysisTasks",
  props: {
    editData: {
      type: Object,
      default: () => null,
    },
  },
  components: { Draw },
  data() {
    return {
      form: {
        videoTasksName: "", // 将原videoTasksName移到form对象中
      },
      formRules: {
        videoTasksName: [
          { required: true, message: "算法名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      checkAnalysisList: [], // 选中的算法名称
      // 算法列表
      analysisList: [],
      cameraList: [],
      checkCameraList: [], // 选中的摄像头
      selectedAlgorithmIndex: -1, // 当前选中算法索引
      cameraDialogVisible: false, // 摄像头配置弹窗
      algorithmDiaData: {}, // 算法配置弹窗数据
      cameraDiaData: {}, // 摄像头配置弹窗数据
      uniqueKey: Math.random().toString(36).substr(2, 9), // 生成随机唯一键
    };
  },
  computed: {},
  watch: {
    editData: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          if (newVal && this.analysisList.length && this.cameraList.length) {
            this.handleEditData(newVal);
          }
        }
      },
    },
  },
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    // 获取算法和摄像头列表
    getList() {
      // 使用Promise.all确保两个接口都完成
      Promise.all([getAlgorithmList(), getCameraList()]).then(
        ([algRes, camRes]) => {
          if (algRes.code === 200 && camRes.code === 200) {
            this.analysisList = algRes.rows;
            this.cameraList = camRes.rows;

            // 数据加载完成后主动触发编辑数据处理
            if (this.editData) {
              this.handleEditData(this.editData);
            }
          }
        }
      );
    },
    // 算法选择点击事件
    handleAlgorithmClick(item, index) {
      this.selectedAlgorithmIndex = index;

      this.$nextTick(() => {
        // 先获取当前算法摄像头ID再清空选择
        const currentCameras = item.checkCameraList.map((c) => c.cameraId);

        // 清空前保留表格实例
        const table = this.$refs.cameraTable;
        table.clearSelection();

        // 立即设置新选中状态
        this.cameraList.forEach((row) => {
          if (currentCameras.includes(String(row.cameraId))) {
            table.toggleRowSelection(row, true);
          }
        });
      });
    },
    // 新增编辑数据处理方法
    handleEditData(editData) {
      this.form.videoTasksName = editData.taskName;
      this.checkAnalysisList = editData.algorithmList
        .map((item) => {
          const originItem = this.analysisList.find(
            (alg) => alg.algorithmId == item.algorithmId
          );
          return originItem
            ? {
                ...originItem,
                checkCameraList: item.cameraList.map((camera) => ({
                  cameraId: String(camera.cameraId), // 直接使用传入的摄像头ID
                  cameraName: camera.cameraName, // 直接使用传入的摄像头名称
                  type: "success",
                  interval: camera.interval, // 使用传入的阈值
                  useRoi: camera.useRoi, // 使用传入的ROI配置
                  roiPoints: camera.roiPoints, // 使用传入的坐标点
                })),
              }
            : null;
        })
        .filter(Boolean);

      // 默认选中第一个算法关联的摄像头
      if (this.checkAnalysisList.length > 0) {
        this.selectedAlgorithmIndex = 0;
        this.$nextTick(() =>
          this.handleAlgorithmClick(this.checkAnalysisList[0], 0)
        );
      }
    },
    // 修改后的复选框点击方法
    handleCheckboxChange(item) {
      // 清空原有选择（单选逻辑）
      this.checkAnalysisList = [];

      // 添加当前选中项
      this.checkAnalysisList.push({
        ...item,
        checkCameraList: [],
      });

      // 更新选中索引
      this.selectedAlgorithmIndex = 0;

      // 清空摄像头选择
      this.$nextTick(() => {
        this.$refs.cameraTable.clearSelection();
      });
    },
    // 摄像头选择
    cameraChange(val) {
      const currentAlgorithm =
        this.checkAnalysisList[this.selectedAlgorithmIndex];
      this.checkCameraList = val;
      console.log(this.checkCameraList);

      if (currentAlgorithm) {
        currentAlgorithm.checkCameraList = val.map((item) => ({
          cameraId: item.cameraId,
          cameraName: item.cameraName,
          type: "success",
          interval: "", //阈值
          useRoi: "false", //全图/自定义
          roiPoints: "", //坐标系
        }));
      }
    },
    // 删除标签
    deleteTag(item, tag) {
      const index = item.checkCameraList.findIndex((i) => i.name === tag.name);
      if (index > -1) {
        item.checkCameraList.splice(index, 1);

        // 新增：定位当前算法索引
        const algorithmIndex = this.checkAnalysisList.findIndex(
          (a) => a.algorithmId === item.algorithmId
        );
        if (algorithmIndex > -1) {
          this.selectedAlgorithmIndex = algorithmIndex;
          // 调用算法点击方法触发table渲染
          this.handleAlgorithmClick(item, algorithmIndex);
        }
      }
    },
    //设置摄像头
    setUpCamera(item, tag) {
      this.cameraDialogVisible = true;
      this.algorithmDiaData = { ...item };
      this.cameraDiaData = { ...tag };
    },
    // 在提交时触发验证
    submitForm(taskStatus) {
      console.log(this.editData);

      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          const param = {
            taskStatus: taskStatus,
            taskId: this.editData ? this.editData.taskId : null,
            taskName: this.form.videoTasksName,
            algorithmList: this.checkAnalysisList.map((algorithm) => ({
              algorithmId: algorithm.algorithmId,
              cameraList: algorithm.checkCameraList.map((camera) => camera),
            })),
          };

          // 根据编辑/新增状态调用不同接口
          const apiMethod = this.editData
            ? updateVideoAnalysisTask
            : addVideoAnalysisTask;

          apiMethod(param).then((res) => {
            if (res.code === 200) {
              this.$modal.msgSuccess(this.editData ? "修改成功" : "创建成功");
              this.$emit("close-drawer");
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        }
      });
    },
    // 获取字符串坐标信息
    getLocalInfo(str) {
      this.cameraDiaData.roiPoints = str;
    },
    //阈值弹窗保存配置
    handleSaveConfig() {
      // 优化后的代码
      const matchedAlgorithm = this.checkAnalysisList.find(
        (alg) => alg.algorithmId === this.algorithmDiaData.algorithmId
      );
      const matchedCamera = matchedAlgorithm?.checkCameraList.find(
        (cam) => cam.cameraId === this.cameraDiaData.cameraId
      );

      if (matchedCamera) {
        Object.assign(matchedCamera, {
          interval: this.cameraDiaData.interval ?? matchedCamera.interval,
          useRoi: this.cameraDiaData.useRoi ?? matchedCamera.useRoi,
          roiPoints: this.cameraDiaData.roiPoints || matchedCamera.roiPoints,
        });
      }

      // 关闭弹窗
      this.cameraDialogVisible = false;
    },
  },
};
</script>

<style scoped lang="scss">
// 自定义复选框样式
.custom-checkbox {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 4px 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  position: relative;
  cursor: pointer;
  transition: all 0.4s;

  &:hover {
    border-color: #409eff;
  }
  &.selected {
    border: 2px solid #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  &.is-checked {
    border-color: #409eff;
    background-color: #f5f7fa;
    // 新增内部框体选中样式
    .checkbox-inner {
      border-color: #409eff;
      background-color: #409eff;
      i {
        color: #fff;
      }
    }
  }

  .checkbox-inner {
    width: 16px;
    height: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 2px;
    margin-right: 8px;
    position: relative;
    background: #fff;
    transition: all 0.2s; // 添加过渡动画

    i {
      position: absolute;
      left: 50%;
      top: 55%; // 微调垂直居中
      transform: translate(-50%, -50%);
      color: #409eff;
      font-weight: bold;
      font-size: 14px; // 增大图标尺寸
    }
  }

  .checkbox-content {
    p {
      margin: 0 0 4px 0;
      font-size: 14px;
    }
    span {
      font-size: 12px;
      color: #909399;
      margin-right: 8px;
    }
  }
}
// 新增动画样式
.list-enter-active {
  transition: all 0.5s ease;
}
.list-leave-active {
  transition: all 0.3s ease;
  position: absolute;
}
.list-enter {
  opacity: 0;
  transform: translateX(-30px);
}
.list-leave-to {
  opacity: 0;
}
.number {
  color: rgb(24, 114, 240);
  font-size: 25px;
}
// 新增自定义标签样式
.custom-tag {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding: 0 8px;
  margin: 2px;
  font-size: 12px;
  border-radius: 4px;
  transition: 0.3s;

  // 不同类型样式
  &.success {
    background-color: #f0f9eb;
    border: 1px solid #e1f3d8;
    color: #67c23a;
  }
  &.warning {
    background-color: #fdf6ec;
    border: 1px solid #faecd8;
    color: #e6a23c;
  }
  &.danger {
    background-color: #fef0f0;
    border: 1px solid #fde2e2;
    color: #f56c6c;
  }

  .close-btn {
    margin-left: 6px;
    border: none;
    background: none;
    color: inherit;
    cursor: pointer;
    font-size: 14px;
    line-height: 1;
    padding: 0 2px;

    &:hover {
      opacity: 0.8;
    }
  }
}
.camera-dialog-title {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
  text-align: center;
  background: #d3d0cd;
  border-radius: 4px;

  padding: 10px;
  div {
    flex: 1;
    p {
      font-size: 20px;
      color: #606266;
      font-weight: bold;
    }
  }
}
.compact-row {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 4px;
}

.compact-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #909399;
}

.compact-input {
  ::v-deep .el-input__inner {
    border-radius: 15px;
    padding: 0 12px;
  }
}

.compact-radio {
  ::v-deep .el-radio-button {
    margin-right: 8px;

    &.is-active {
      .el-radio-button__inner {
        background: #409eff;
        border-color: #409eff;
        box-shadow: none;
      }
    }
  }
}
.camera-dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 0;
  border-top: 1px solid #ebeef5;

  .dialog-btn {
    padding: 7px 15px;
    border-radius: 4px;
    font-weight: 500;
    transition: all 0.3s;

    &.cancel-btn {
      background: #f5f7fa;
      border-color: #dcdfe6;
      color: #606266;
      &:hover {
        background: #f0f6ff;
        border-color: #c6e2ff;
        color: #409eff;
      }
    }

    &.confirm-btn {
      background: #409eff;
      border-color: #409eff;
      &:hover {
        background: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}
</style>
