<template>
  <ele-modal
    :visible.sync="visible"
    :title="title"
    width="800px"
    append-to-body
    @close="cancel"
    :maxable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="create-form"
    >
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="规则编码:" prop="ruleCode">
            <el-input
              v-model="form.ruleCode"
              maxlength="50"
              placeholder="请输入"
              :disabled="type == 'update'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称:" prop="ruleName">
            <el-input
              v-model="form.ruleName"
              maxlength="50"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时间间隔:" prop="forInterval">
            <el-input-number
              v-model="form.forInterval"
              :min="1"
              :max="100"
              controls-position="right"
              class="w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否重复:" prop="repeated">
            <el-radio-group v-model="form.repeated">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序号:" prop="indexNo">
            <el-input-number
              v-model="form.indexNo"
              :min="1"
              :max="99999"
              controls-position="right"
              class="w-full"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="摄像头:" prop="devices" class="!mb-0">
            <Draggable
              :devices="form.devices"
              :camera-list="cameraList"
              ref="draggable"
            />
          </el-form-item>
          
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="save"
        :loading="loading"
      >
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
import * as VideoPollingApi from '@/api/config/videoPolling'
import Draggable from './draggable.vue'

const defForm = {
  id: undefined,
  ruleCode: '',
  ruleName: '',
  forInterval: 10,
  repeated: true,
  indexNo: 100,
  devices: [{ deviceCode: undefined }]
}

export default {
  name: 'VideoPolingForm',
  components: {
    Draggable
  },
    data() {
    return {
      visible: false,
      title: '',
      type: '',
      loading: false,
      form: { ...defForm },
      cameraList: [],
      rules: {
        ruleCode: [{ required: true, message: '规则编码不能为空', trigger: 'blur' }],
        ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
        forInterval: [{ required: true, message: '时间间隔不能为空', trigger: 'blur' }],
        repeated: [{ required: true, message: '请选择是否重复', trigger: 'change' }],
        indexNo: [{ required: true, message: '排序号不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 初始化时获取摄像头列表
    this.getCameraList()
  },
  methods: {
    /** 获取摄像头列表 */
    async getCameraList() {
      try {
        const res = await VideoPollingApi.listByType()
        this.cameraList = res || []
      } catch (e) {
        console.error(e)
      }
    },

    /** devices 更新回调 */
    // handleDevicesUpdate(val) {
    //   this.form.devices = val
    //   console.log('form.devices:', this.form.devices)
    // },

    /** 打开弹窗 */
    openForm(type, id) {
      this.visible = true
      this.type = type
      this.title = type === 'create' ? '新增轮询规则' : '编辑轮询规则'

      // 重置表单
      this.form = { ...defForm }

      // 修改时，加载数据
      if (id) {
        this.loading = true
        VideoPollingApi.getVideoRule(id)
          .then((res) => {
            // 解析 devices 字符串为数组
            let devices = JSON.parse(res.devices || '[]')
            res.devices = devices.length ? devices : [{ deviceCode: undefined }]
            this.form = res

            console.log('res:', res)
          })
          .finally(() => {
            this.loading = false
          })
      }

    },

    /** 取消 */
    cancel() {
      this.form = { ...defForm }
      this.visible = false
    },

    /** 保存 */
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('form:', this.form)
          const devices = this.$refs.draggable.localDevices
          console.log('devices:', devices)
          // 验证摄像头选择
          const hasEmptyCamera = devices.some(item => !item.deviceCode)
          if (hasEmptyCamera) {
            this.$message.warning('请选择摄像头')
            return
          }

          this.loading = true
          const formData = { ...this.form }
          const array = []
          // 处理摄像头数据：直接使用 deviceCode 数组
          devices.forEach((item) => {
              this.cameraList.forEach((camera) => {
                  if (item.deviceCode == camera.deviceCode) {
                      array.push(camera)
                  }
              })
          })

          console.log('array:', array)
          formData.devices = JSON.stringify(array)

          const action = this.type === 'create'
            ? VideoPollingApi.createVideoRule(formData)
            : VideoPollingApi.updateVideoRule(formData)

          action
            .then(() => {
              this.$message.success('操作成功')
              this.cancel()
              this.$emit('success')
            })
            .catch((e) => {
              console.error(e)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    /** 新增摄像头 */
    addCamera() {
      this.form.devices.push({ deviceCode: undefined })
      // 强制刷新 Draggable
      // this.$nextTick(() => {
      //   this.$refs.draggable && this.$refs.draggable.refresh()
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.w-full {
  width: 100%
}
</style>
