<template>
  <div>
    <el-form :model="form" ref="form" label-width="130px" class="dynamic-form">
      <template v-if="showTactics">
        <el-col :span="24">
          <el-form-item label="策略名称" prop="policyName">
            <el-input v-model="form.policyName" :disabled="readonly" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" type="textarea" :disabled="readonly" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="关联资源组" prop="resourceGroupName">
            <el-input v-model="form.resourceGroupName" :disabled="readonly" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="包含设备" prop="includedDevicesName">
            <template v-if="readonly">
              {{form.includedDevicesName}}
            </template>
            <template v-else>
              <el-input v-model="form.includedDevicesName" :disabled="readonly" clearable></el-input>
            </template>
          </el-form-item>
        </el-col>
      </template>
      <!-- 动态源文件部分 循环多个源文件地址    -->
      <div v-for="(source, index) in form.sources" :key="index" class="source-item">
        <!-- 源文件地址格式 -->
        <el-col :span="14">
          <el-form-item :label="`源文件${index + 1}地址格式`" :prop="`sources.${index}.sourceFilePathType`" :rules="[{ required: true, message: '请选择地址格式', trigger: 'change' }]">
            <el-radio-group v-model="source.sourceFilePathType" :disabled="readonly">
<!--              <el-radio label="platform">平台文件地址</el-radio>-->
              <el-radio label="1">外网HTTP(S)</el-radio>
            </el-radio-group>
            <div v-if="!readonly" class="tip">注意：当文件大小超过100M时，请选择【外网HTTP(S)】地址格式</div>
<!--            <div class="error-tip" v-if="source.sizeError">您选择的文件已经超过100M，请更改文件地址格式选择</div>-->
          </el-form-item>
        </el-col>
        <el-col :span="10" style="vertical-align: top;" v-if="readonly ? false : index === 0 ? true : false">
          <el-form-item style="margin-left: -130px;">
            <el-button type="primary" @click="addSource" class="add-btn">添加</el-button>
          </el-form-item>
        </el-col>
        <!-- 添加源文件按钮 -->
        <el-col :span="10" v-if="readonly ? false : index !== 0 ? true : false">
          <el-form-item style="margin-left: -130px;">
            <el-button type="danger" @click="removeSource(index)" class="delete-btn">删除</el-button>
          </el-form-item>
        </el-col>
        <!-- 源文件地址 -->
        <el-col :span="12">
          <el-form-item :label="`源文件${index + 1}地址`" :prop="`sources.${index}.sourceFilePath`" :rules="[{ required: true, message: '请输入外网地址', trigger: 'blur' }]">
            <el-input v-model="source.sourceFilePath" :disabled="readonly" placeholder="请输入外网地址" clearable></el-input>
          </el-form-item>
        </el-col>
      </div>

      <el-col :span="24">
        <!-- 目标目录 -->
        <el-form-item label="目标目录" prop="targetDirectory">
          <el-input v-model="form.targetDirectory" :disabled="readonly" placeholder="请输入目标目录路径" clearable></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <!-- 命令内容部分 -->
        <el-form-item label="命令内容">
          <div v-for="(cmd, index) in form.commands" :key="index" class="command-item">
            {{index + 1}}. <el-input v-model="cmd.commandContent" :disabled="readonly" class="ml5" placeholder="请输入命令" clearable></el-input>
            <el-button type="primary" @click="addCommand" v-if="readonly ? !readonly : index === 0" class="command-btn">添加</el-button>
            <el-button type="danger" @click="removeCommand(index)" v-if="readonly ? !readonly : index >= 1" class="command-btn">删除</el-button>
          </div>
        </el-form-item>
      </el-col>

      <!-- 执行方式 -->
      <el-form-item label="执行方式" prop="executionMethod">
        <el-select v-model="form.executionMethod" placeholder="请选择执行方式" :disabled="readonly" clearable>
          <el-option v-for="dict in dict.type.policy_method" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <!-- 定时时间 -->
      <el-form-item label="定时时间" v-if="form.executionMethod === '1'" prop="scheduledTime" :rules="[{ required: true, message: '请选择定时时间', trigger: 'change' }]">
        <el-date-picker v-model="form.scheduledTime" :disabled="readonly" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width: 100%;"></el-date-picker>
      </el-form-item>
      <template v-if="showView">
        <el-form-item label="策略状态" prop="policyStatus">
          <el-select v-model="form.policyStatus" placeholder="请选择执行方式" :disabled="readonly" clearable>
            <el-option v-for="dict in dict.type.policy_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="下发策略时间" prop="deployTime">
          <el-date-picker v-model="form.deployTime" :disabled="readonly" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="form.createTime" :disabled="readonly" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime">
          <el-date-picker v-model="form.updateTime" :disabled="readonly" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" style="width: 100%;"></el-date-picker>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
    export default {
      name: 'DynamicForm',
      dicts: ['policy_method', 'policy_status'],
      props: {
        formData: {
          type: Object,
          default: () => ({
            sources: [{sourceFilePathType: '1', sourceFilePath: ''}],                    // 源文件数组，初始为空
            commands: [{commandContent: ''}],         // 命令内容数组
          })
        },
        // 是否只读
        readonly: {
          type: Boolean,
          default: false
        },
        // 是否展示第一级的策略信息
        showTactics: {
          type: Boolean,
          default: false
        },
        // 详情
        showView: {
          type: Boolean,
          default: false
        }
      },
      watch: {
        // 监听 props 变化，实时更新内部数据
        formData: {
          immediate: true, // 初始化时立即执行一次
          handler(newVal) {
            if (newVal && typeof newVal === 'object' && Object.keys(newVal).length === 0) {
              this.form = JSON.parse(JSON.stringify({sources: [{sourceFilePathType: '1', sourceFilePath: ''}], commands: [{commandContent: ''}]}));
            } else {
              this.form = JSON.parse(JSON.stringify(newVal));
            }
          },
        },
      },
      data() {
        return {
          form: {}
        };
      },
      methods: {
        // 添加源文件
        addSource() {
          // sizeError: false
          this.form.sources.push({sourceFilePathType: '1', sourceFilePath: ''});
        },

        // 删除源文件
        removeSource(index) {
          this.form.sources.splice(index, 1);
        },

        // 添加命令
        addCommand() {
          this.form.commands.push({commandContent: ''});
        },

        // 删除命令
        removeCommand(index) {
          this.form.commands.splice(index, 1);
        },

        // 提交表单
        submitForm() {
          return new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (valid) {
                resolve(this.form);
                // // 在这里可以添加自定义验证逻辑，例如检查大文件是否使用了正确的地址格式
                // const hasError = this.form.sources.some(source => {
                //   // 假设这里有判断文件大小的逻辑
                //   const fileSize = this.getFileSize(source.address); // 假设的方法
                //   source.sizeError = fileSize > 100 && source.format === 'platform';
                //   return source.sizeError;
                // });
                // if (!hasError) {
                //   this.$message.success('表单提交成功');
                //   console.log('表单数据:', this.form);
                // } else {
                //   this.$message.error('存在文件大小与地址格式不匹配的问题，请检查');
                // }
              } else {
                this.$message.error('表单验证失败，请检查必填项');
                reject(new Error('验证失败')); // 失败时返回错误
                return false;
              }
            });
          });
        },

        // 重置表单
        resetForm() {
          this.$refs.form.resetFields();
          // 重置数组类型的字段
          this.form.sources = [
            { format: '', address: '', sizeError: false },
            { format: '', address: '', sizeError: false }
          ];
          this.form.commands = [''];
        },

        // 模拟获取文件大小的方法
        getFileSize(address) {
          // 实际应用中这里应该是真实的文件大小获取逻辑
          const sizeMap = {
            'system-default-1': 50,    // 50M
            'system-default-2': 150,   // 150M
            'user-upload-1': 80,       // 80M
            'user-upload-2': 200       // 200M
          };
          return sizeMap[address] || 0;
        }
      },
    }
</script>

<style scoped>
  /*.dynamic-form {*/
  /*  max-width: 800px;*/
  /*  margin: 20px auto;*/
  /*  padding: 20px;*/
  /*  background-color: #fff;*/
  /*  border-radius: 4px;*/
  /*  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
  /*}*/

  .tip {
    color: #faad14;
    font-size: 12px;
    margin-top: 5px;
    line-height: 1.5;
  }

  .error-tip {
    color: #f5222d;
    font-size: 12px;
    margin-top: 5px;
    line-height: 1.5;
  }

  /*.source-item {*/
  /*  padding-bottom: 15px;*/
  /*  margin-bottom: 15px;*/
  /*  border-bottom: 1px dashed #e8e8e8;*/
  /*}*/

  .source-item:last-child {
    border-bottom: none;
  }

  .delete-btn {
    margin-left: 120px;
    margin-top: -10px;
  }

  .add-btn {
    margin-left: 120px;
  }

  .command-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .command-item .el-input {
    flex: 1;
    margin-right: 10px;
  }

  .command-btn {
    white-space: nowrap;
  }
</style>
