<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">
              <!-- 自定义复选框组件 -->
              <div
                class="custom-checkbox"
                :class="{
                  'is-checked': checkAnalysisList.some(
                    (val) => item.algorithmId === val.algorithmId
                  ),
                }"
                @click="handleCheckboxChange(item)"
                v-for="(item, index) in analysisList"
                :key="index"
              >
                <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"
            >
              <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
                    v-for="tag in item.checkCameraList"
                    :key="tag.cameraName"
                    closable
                    size="mini"
                    @close="deleteTag(item, tag)"
                    :type="tag.type"
                  >
                    {{ tag.name }}
                  </el-tag>
                  <p>
                    <span>ID : {{ item.algorithmId }} </span>
                    <span>版本 {{ item.algorithmVersion }} </span>
                  </p>
                </div>
              </div>
            </transition-group>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getAlgorithmList } from "@/api/business/algorithmconfig.js";
import { getCameraList } from "@/api/business/cameraconfig.js";
import {
  addVideoAnalysisTask,
  updateVideoAnalysisTask,
} from "@/api/business/videoanalysistasks.js";
export default {
  name: "addVideoAnlysisTasks",
  props: {
    editData: {
      type: Object,
      default: () => null,
    },
  },
  components: {},
  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, // 当前选中算法索引
    };
  },
  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((cameraId) => ({
                  cameraId: String(cameraId),
                  name: this.cameraList.find((cam) => cam.cameraId == cameraId)
                    ?.cameraName,
                  type: "success",
                })),
              }
            : null;
        })
        .filter(Boolean);

      // 默认选中第一个算法关联的摄像头
      if (this.checkAnalysisList.length > 0) {
        this.selectedAlgorithmIndex = 0;
        this.$nextTick(() =>
          this.handleAlgorithmClick(this.checkAnalysisList[0], 0)
        );
      }
    },
    // 修改后的复选框点击方法
    handleCheckboxChange(item) {
      const index = this.checkAnalysisList.findIndex(
        (i) => i.algorithmId === item.algorithmId
      );
      if (index > -1) {
        this.checkAnalysisList.splice(index, 1);
      } else {
        // 新增时初始化摄像头列表
        this.checkAnalysisList.push({
          ...item,
          checkCameraList: [],
        });
        this.selectedAlgorithmIndex = this.checkAnalysisList.length - 1;
        // 将清空操作移到else内部
        this.$nextTick(() => {
          this.$refs.cameraTable.clearSelection();
        });
      }
    },
    // 摄像头选择
    cameraChange(val) {
      const currentAlgorithm =
        this.checkAnalysisList[this.selectedAlgorithmIndex];
      if (currentAlgorithm) {
        currentAlgorithm.checkCameraList = val.map((item) => ({
          cameraId: item.cameraId,
          name: item.cameraName,
          type: "success",
        }));
      }
    },
    // 删除标签
    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);
        }
      }
    },
    //提交

    // 在提交时触发验证
    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.cameraId
              ),
            })),
          };

          // 根据编辑/新增状态调用不同接口
          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);
            }
          });
        }
      });
    },
  },
};
</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;
}
</style>
