<template>
  <div class="dataset-version-add-wrapper">
    <!-- 新增版本弹窗 -->
    <el-dialog
      title="新增版本"
      :visible.sync="dialogVisible"
      :showClose="true"
      :closeOnClickModal="false"
      @close="handleClose"
      :append-to-body="true"
      width="900px"
    >
      <div class="form-container">
        <el-form
          v-if="dialogVisible"
          :model="form"
          :rules="rules"
          ref="versionForm"
          label-width="0"
          label-position="top"
          class="version-form"
        >
          <!-- 第一行：数据集名称 + 数据类型 -->
          <div class="form-row">
            <el-form-item label="数据集名称" class="form-col-50">
              <el-input
                class="form-item"
                v-model="form.datasetName"
                disabled
                placeholder=" "
              ></el-input>
            </el-form-item>

            <el-form-item label="数据类型" class="form-col-50">
              <el-input
                class="form-item"
                v-model="form.datasetType"
                disabled
                placeholder=" "
              ></el-input>
            </el-form-item>
          </div>

          <!-- 第二行：标注类型 + 标注模板 -->
          <div class="form-row">
            <el-form-item label="标注类型" class="form-col-50">
              <el-input
                class="form-item"
                v-model="form.labelingType"
                disabled
                placeholder=" "
              ></el-input>
            </el-form-item>

            <el-form-item label="标注模板" class="form-col-50">
              <el-input
                class="form-item"
                v-model="form.labelingTemplate"
                disabled
                placeholder=" "
              ></el-input>
            </el-form-item>
          </div>

          <!-- 第三行：数据变更类型 + 样本名称 -->
          <div class="form-row">
            <el-form-item label="数据变更类型" prop="changeType" class="form-col-50">
              <el-select
                class="form-item"
                v-model="form.changeType"
                placeholder="请选择"
                @change="handleChangeTypeChange"
              >
                <el-option
                  label="新增"
                  value="1"
                ></el-option>
                <el-option
                  label="减少"
                  value="2"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 新增类型时：样本库可新增不可删除 -->
            <el-form-item
              v-if="form.changeType === '1'"
              label="样本名称"
              prop="sampleLibraryIds"
              class="form-col-50"
            >
              <el-select
                class="form-item"
                multiple
                v-model="form.sampleLibraryIds"
                clearable
                placeholder="请选择"
                @remove-tag="handleRemoveSampleLibrary"
                @change="handleSampleLibChange"
              >
                <el-option
                  v-for="item in sampleLibraryList"
                  :key="item.sampleLibraryId"
                  :label="item.sampleLibraryName"
                  :value="item.sampleLibraryId"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 减少类型时：样本库只读不可操作 -->
            <el-form-item
              v-if="form.changeType === '2'"
              label="当前关联样本库"
              class="form-col-50"
            >
              <el-select
                class="form-item"
                multiple
                v-model="form.sampleLibraryIds"
                disabled
                placeholder="无关联样本库"
              >
                <el-option
                  v-for="item in sampleLibraryList"
                  :key="item.sampleLibraryId"
                  :label="item.sampleLibraryName"
                  :value="item.sampleLibraryId"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>

          <!-- 第四行：选择增加/减少数据（仅选择变更类型后显示） -->
          <div class="form-row" v-if="form.changeType">
            <el-form-item
              :label="form.changeType === '1' ? '选择增加数据' : '选择减少数据'"
              :prop="form.changeType === '1' ? 'addDataIds' : 'reduceDataIds'"
              class="form-col-50"
            >
              <div class="data-select-wrapper">
                <el-button
                  type="text"
                  class="select-data-btn"
                  @click="handleSelectData"
                  :disabled="getSelectDataBtnDisabled()"
                >
                  {{ form.changeType === '1' ? '选择增加数据' : '选择减少数据' }}
                </el-button>
<!--                <span class="selected-count" v-if="totalSelectedCount > 0">-->
<!--                  <span v-if="form.changeType === '1'">本次新增{{ changeCount }}个</span>-->
<!--                  <span v-if="form.changeType === '2'">本次减少{{ changeCount }}个</span>-->
<!--                </span>-->
              </div>
              <!-- 存储选中的样本ID列表（隐藏） -->
              <input type="hidden" v-model="form.addDataIds" v-if="form.changeType === '1'" />
              <input type="hidden" v-model="form.reduceDataIds" v-if="form.changeType === '2'" />
            </el-form-item>
          </div>

          <!-- 描述 -->
          <el-form-item label="描述" prop="datasetVersionDesc" class="form-col-100">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 5 }"
              class="form-item"
              v-model.trim="form.datasetVersionDesc"
              clearable
              show-word-limit
              placeholder="请输入"
              maxlength="200"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button class="cancel-btn" @click="handleClose">取消</el-button>
        <el-button type="primary" class="confirm-btn" @click="submitForm">保存</el-button>
      </span>
    </el-dialog>

    <!-- 引入选择数据子组件弹窗 -->
    <DataSelectDialog
      :visible="dataSelectVisible"
      :selected-ids="getCurrentSelectedIds()"
      :sample-library-ids="getSampleLibraryIdsForSelect()"
      :change-type="form.changeType"
      :dataset-version-id="datasetVersionId"
      @close="handleDataSelectClose"
      @confirm="handleDataSelectConfirm"
    />
  </div>
</template>

<script>
import _ from 'lodash'
import {
  getDatasetDetailAPI,
  addDatasetVersionDataAPI,
  getDatasetRelatedSampleLibsAPI
} from '@/api/data/dataset'
import {
  sampleListAPI,
  getSampleListByVersionIdAPI
} from '@/api/data/sample'
import DataSelectDialog from './child/DataSelectDialog.vue'

export default {
  name: "DatasetVersionAdd",
  components: {
    DataSelectDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    datasetId: {
      type: [String, Number],
      required: true
    },
    datasetVersionId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      dataSelectVisible: false,
      form: {
        datasetId: this.datasetId,
        datasetName: '',
        datasetType: '',
        labelingType: '',
        labelingTemplate: '',
        changeType: '',
        sampleLibraryIds: [],
        addDataIds: '',
        reduceDataIds: '',
        datasetVersionDesc: ''
      },
      rules: {
        changeType: [
          { required: true, message: '请选择数据变更类型', trigger: 'change' }
        ],
        sampleLibraryIds: [
          {
            validator: (rule, value, callback) => {
              if (this.form.changeType === '1' && value.length === 0) {
                callback(new Error('至少选择一个样本库'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        addDataIds: [
          {
            required: true,
            message: '请选择增加的数据',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.changeType === '1' && !value) {
                callback(new Error('请选择增加的数据'));
              } else {
                callback();
              }
            }
          }
        ],
        reduceDataIds: [
          {
            required: true,
            message: '请选择减少的数据',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.form.changeType === '2' && !value) {
                callback(new Error('请选择减少的数据'));
              } else {
                callback();
              }
            }
          }
        ],
        datasetVersionDesc: [
          { max: 200, message: '描述长度不能超过200字符', trigger: 'blur' }
        ]
      },
      sampleLibraryList: [],
      currentRelatedSampleLibs: '',
      relatedSampleLibIds: [],
      // 关键修复：记录初始选中的ID（版本原有数据）
      initialVersionIds: [],
      // 关键修复：总数和变更数分离
      totalSelectedCount: 0,
      changeCount: 0,
      loading: null,
      originalSampleLibraryIds: []
    };
  },
  computed: {
    // 计算属性：获取当前选中的ID字符串
    getCurrentSelectedIds() {
      return () => {
        return this.form.changeType === '1'
          ? this.form.addDataIds
          : this.form.reduceDataIds;
      };
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal;
        if (newVal) {
          this.resetForm(true);
          this.initFormData();
        } else {
          this.resetForm();
        }
      },
      immediate: true,
      deep: true
    },
    datasetId: {
      handler(newVal) {
        if (this.dialogVisible) {
          this.form.datasetId = newVal;
          this.resetForm(true);
          this.initFormData();
        }
      },
      immediate: true
    }
  },
  created() {
    this.initSampleList();
  },
  methods: {
    handleSampleLibChange(newSelectedIds) {
      // 深拷贝避免响应式问题，newSelectedIds是下拉操作后的选中列表
      const finalSelected = [...newSelectedIds];
      // 遍历原有样本库，判断是否有被取消勾选的
      this.originalSampleLibraryIds.forEach(originalId => {
        if (!finalSelected.includes(originalId)) {
          // 原有样本库被取消了，强制加回选中列表
          finalSelected.push(originalId);
          this.$modal.msgWarning('已关联的样本库不可取消，可新增其他样本库');
        }
      });
      // 还原最终的选中列表，覆盖下拉操作的结果
      this.form.sampleLibraryIds = finalSelected;
    },
    /** 初始化样本库列表 */
    async initSampleList() {
      try {
        const res = await sampleListAPI({});
        if (res.code === 200) {
          this.sampleLibraryList = res.rows.map(item => ({
            sampleLibraryId: item.sampleLibraryId,
            sampleLibraryName: item.sampleLibraryName
          }));
        }
      } catch (error) {
        this.$modal.msgError('获取样本库列表失败');
        console.error(error);
      }
    },

    /** 初始化表单数据 */
    async initFormData() {
      try {
        this.loading = this.$loading({ text: '加载中...' });
        // 1. 获取数据集基础信息
        const detailRes = await getDatasetDetailAPI({ datasetId: this.datasetId });
        if (detailRes.code === 200 && detailRes.data) {
          const data = detailRes.data;
          this.form.datasetName = data.datasetName;
          this.form.datasetType = data.datasetType;
          this.form.labelingType = data.labelingType;
          this.form.labelingTemplate = data.labelingTemplate;
        }
        // 2. 获取数据集已关联的样本库
        const requestParams = this.datasetVersionId
          ? { datasetVersionId: this.datasetVersionId }
          : { datasetId: this.datasetId };
        const relatedRes = await getDatasetRelatedSampleLibsAPI(requestParams);
        if (relatedRes.code === 200 && relatedRes.data) {
          this.relatedSampleLibIds = relatedRes.data.map(item => item.sampleLibraryId);
          this.currentRelatedSampleLibs = relatedRes.data.map(item => item.sampleLibraryName).join('、');
          this.form.sampleLibraryIds = [...this.relatedSampleLibIds];
          this.originalSampleLibraryIds = [...this.relatedSampleLibIds];
        }
        // 3. 如果是编辑场景，获取已选样本ID
        if (this.datasetVersionId) {
          await this.getVersionSelectedSamples();
        }
      } catch (error) {
        this.$modal.msgError('获取数据集信息失败');
        console.error(error);
      } finally {
        this.loading && this.loading.close();
      }
    },

    /** 获取版本已选样本ID - 关键修复：记录初始版本ID */
    async getVersionSelectedSamples() {
      try {
        const res = await getSampleListByVersionIdAPI({
          datasetVersionId: this.datasetVersionId
        });
        if (res.code === 200 && res.rows && res.rows.length) {
          const sampleIds = res.rows.map(item => item.sampleId).join(',');
          const sampleIdArray = res.rows.map(item => Number(item.sampleId));

          // 记录版本原有ID（作为基准）
          this.initialVersionIds = [...sampleIdArray];

          if (this.form.changeType === '1') {
            this.form.addDataIds = sampleIds;
          } else if (this.form.changeType === '2') {
            this.form.reduceDataIds = sampleIds;
          }

          // 初始化计数
          this.totalSelectedCount = sampleIdArray.length;
          this.changeCount = 0;
        }
      } catch (error) {
        console.error('获取版本样本失败：', error);
      }
    },

    /** 变更类型切换时重置选中数据 */
    handleChangeTypeChange() {
      // 重置所有选中数据和计数
      this.form.addDataIds = '';
      this.form.reduceDataIds = '';
      this.initialVersionIds = [];
      this.totalSelectedCount = 0;
      this.changeCount = 0;

      if (this.form.changeType === '2') {
        this.form.sampleLibraryIds = [...this.relatedSampleLibIds];
        if (!this.relatedSampleLibIds.length) {
          this.$modal.msgWarning('当前数据集暂无关联样本库，无法选择减少数据');
        }
      } else {
        this.form.sampleLibraryIds = [...this.originalSampleLibraryIds];
      }
    },

    /** 新增类型时，禁止删除已选样本库 */
    handleRemoveSampleLibrary(tag) {
      if (this.originalSampleLibraryIds.includes(tag)) {
        this.$modal.msgWarning('已选样本库不可删除，可新增其他样本库');
        if (!this.form.sampleLibraryIds.includes(tag)) {
          this.form.sampleLibraryIds.push(tag);
        }
      }
    },

    /** 获取选择数据按钮的禁用状态 */
    getSelectDataBtnDisabled() {
      if (this.form.changeType === '1') {
        return !this.form.sampleLibraryIds.length;
      } else if (this.form.changeType === '2') {
        return !this.relatedSampleLibIds.length;
      }
      return true;
    },

    /** 获取传递给选择数据弹窗的样本库ID */
    getSampleLibraryIdsForSelect() {
      if (this.form.changeType === '1') {
        return this.form.sampleLibraryIds;
      } else if (this.form.changeType === '2') {
        return this.relatedSampleLibIds;
      }
      return [];
    },

    /** 打开选择数据弹窗 */
    handleSelectData() {
      this.dataSelectVisible = true;
    },

    /** 关闭选择数据弹窗 */
    handleDataSelectClose() {
      this.dataSelectVisible = false;
    },

    handleDataSelectConfirm({ selectedIds, selectedCount }) {
      // 1. 更新总数
      this.totalSelectedCount = selectedCount;

      // 2. 更新表单中的选中ID
      if (this.form.changeType === '1') {
        this.form.addDataIds = selectedIds;
        // 新增：本次变更数 = 当前总数 - 初始版本数
        this.changeCount = this.totalSelectedCount - this.initialVersionIds.length;
      } else if (this.form.changeType === '2') {
        this.form.reduceDataIds = selectedIds;
        // 减少：本次变更数 = 初始版本数 - 当前总数
        this.changeCount = this.initialVersionIds.length - this.totalSelectedCount;
      }

      this.dataSelectVisible = false;
    },

    /** 提交表单 */
    submitForm() {
      this.$refs.versionForm.validate(async (valid) => {
        if (valid) {
          this.loading = this.$loading({ text: '提交中...' });
          try {
            const params = {
              ...this.form,
              sampleLibraryId: this.form.changeType === '1'
                ? this.form.sampleLibraryIds.join(',')
                : this.relatedSampleLibIds.join(','),
              sampleIds: this.form.changeType === '1'
                ? this.form.addDataIds
                : this.form.reduceDataIds
            };
            delete params.addDataIds;
            delete params.reduceDataIds;
            delete params.sampleLibraryIds;

            console.log('parans',params)
            const res = await addDatasetVersionDataAPI(params);
            if (res.code === 200) {
              this.$modal.msgSuccess('新增版本成功');
              this.$emit('refreshList');
              this.handleClose();
            } else {
              this.$modal.msgError(res.msg || '新增版本失败');
            }
          } catch (error) {
            this.$modal.msgError('操作失败，请稍后重试');
            console.error(error);
          } finally {
            this.loading && this.loading.close();
          }
        }
      });
    },

    /** 重置表单 - 新增force参数，强制清空所有数据 */
    resetForm(force = false) {
      // 强制重置时，清空所有关联数据
      if (force) {
        this.form = {
          datasetId: this.datasetId,
          datasetName: '',
          datasetType: '',
          labelingType: '',
          labelingTemplate: '',
          changeType: '',
          sampleLibraryIds: [],
          addDataIds: '',
          reduceDataIds: '',
          datasetVersionDesc: ''
        };
        this.currentRelatedSampleLibs = '';
        this.relatedSampleLibIds = [];
        this.originalSampleLibraryIds = [];
      } else {
        this.form.changeType = '';
        this.form.sampleLibraryIds = [];
        this.form.addDataIds = '';
        this.form.reduceDataIds = '';
        this.form.datasetVersionDesc = '';
      }

      // 重置计数相关
      this.initialVersionIds = [];
      this.totalSelectedCount = 0;
      this.changeCount = 0;

      // 清空表单验证
      if (this.$refs.versionForm) {
        this.$refs.versionForm.clearValidate();
      }
    },

    /** 关闭弹窗 */
    handleClose() {
      this.dialogVisible = false;
      this.resetForm(true); // 强制清空所有数据
      this.$emit('closeDialog');
    }
  }
};
</script>

<style lang="scss" scoped>
.dataset-version-add-wrapper {
  width: 100%;
}

.form-container {
  padding: 0 20px;
}

.version-form {
  .form-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -15px 16px;
  }

  .form-col-50 {
    flex: 0 0 calc(50% - 30px);
    margin: 0 15px;
  }

  .form-col-100 {
    flex: 0 0 calc(100% - 30px);
    margin: 0 15px;
  }

  .el-form-item {
    margin-bottom: 0;

    .el-form-item__label {
      font-size: 14px;
      color: #333;
      padding: 0 0 8px 0;
      line-height: 1;
      font-weight: normal;

      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
    }

    .form-item {
      width: 100%;
      border-radius: 4px;

      &.el-select {
        .el-select__tags {
          flex-wrap: wrap;
          height: auto !important;
          min-height: 36px;
        }
      }

      &.el-textarea {
        height: auto;
      }
    }
  }

  .data-select-wrapper {
    display: flex;
    align-items: center;
    height: 36px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
    background: #fff;

    .select-data-btn {
      padding: 0;
      color: #1f72ea;
      font-size: 14px;
      height: 100%;
      display: flex;
      align-items: center;
    }

    .selected-count {
      margin-left: 10px;
      font-size: 14px;
      color: #666;
      // 突出显示变更数
      span {
        color: #1f72ea;
        font-weight: 500;
      }
    }
  }
}

::v-deep .el-dialog__header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;

  .el-dialog__title {
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }
}

::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

::v-deep .el-dialog__footer {
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.confirm-btn {
  width: 98px;
  height: 36px;
  background: #1F72EA !important;
  border-radius: 4px !important;
  color: #fff !important;
  border: none !important;
  font-size: 14px;
  margin-left: 10px;
}

.cancel-btn {
  width: 98px;
  height: 36px;
  background: #fff !important;
  border: 1px solid #dcdfe6 !important;
  border-radius: 4px !important;
  color: #666 !important;
  font-size: 14px;
}
</style>
