<template>
  <ele-modal
    :visible.sync="visible"
    :title="isEdit ? '编辑告警配置' : '新增告警配置'"
    width="70%"
    append-to-body
    :maxable="true"
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
    >
      <!-- 第一部分：基本信息 -->
      <header-title title="基本信息"></header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="告警级别：" prop="alarmLevel">
            <el-select v-model="form.alarmLevel" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in options.alarmLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="告警名称：" prop="alarmName">
            <el-input v-model="form.alarmName" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="告警对象：" prop="alarmTarget">
            <el-select v-model="form.alarmTarget" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in options.alarmTarget"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="告警设备类型：" prop="deviceType">
            <el-select v-model="form.deviceType" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in options.deviceType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="告警描述：" prop="alarmDesc">
            <el-input v-model="form.alarmDesc" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="状态：" prop="status">
            <el-switch v-model="form.status" active-color="#409EFF"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 添加设备表格 -->
      <div class="table-header">
        <el-button type="primary" size="small" @click="addDevice">添加设备</el-button>
      </div>
      <el-table :data="form.deviceList" border style="width: 100%; margin-bottom: 20px" max-height="250">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="meterCode" label="表计编码" min-width="120" align="center"></el-table-column>
        <el-table-column prop="meterNumber" label="表计编号" min-width="120" align="center"></el-table-column>
        <el-table-column prop="meterName" label="表计名称" min-width="120" align="center"></el-table-column>
        <el-table-column prop="meterType" label="表计类型" min-width="100" align="center"></el-table-column>
        <el-table-column prop="energyType" label="用能分类" min-width="100" align="center"></el-table-column>
        <el-table-column prop="energyArea" label="用能分区" min-width="100" align="center"></el-table-column>
        <el-table-column prop="useDept" label="使用部门" min-width="100" align="center"></el-table-column>
        <el-table-column prop="ownerDept" label="权属部门" min-width="100" align="center"></el-table-column>
        <el-table-column prop="areaManager" label="片区负责人" min-width="100" align="center"></el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="danger-text" @click="removeDevice(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 第二部分：触发条件 -->
      <header-title title="触发条件"></header-title>
      <el-row>
        <el-col :span="8">
          <el-form-item label="触发条件：" prop="triggerCondition">
            <el-select v-model="form.triggerCondition" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in options.triggerCondition"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 条件列表 -->
      <div class="condition-list">
        <div v-for="(item, index) in form.conditions" :key="index" class="condition-row">
          <div class="condition-item">
            <el-select v-model="item.field" placeholder="请选择">
              <el-option
                v-for="field in options.conditionField"
                :key="field.value"
                :label="field.label"
                :value="field.value"
              ></el-option>
            </el-select>
          </div>
          <div class="condition-item">
            <el-select v-model="item.operator" placeholder="=">
              <el-option
                v-for="op in options.conditionOperator"
                :key="op.value"
                :label="op.label"
                :value="op.value"
              ></el-option>
            </el-select>
          </div>
          <div class="condition-item value-item">
            <template v-if="item.field === 'energyType' || item.field === 'energyArea'">
              <el-select v-model="item.value" placeholder="请选择">
                <el-option
                  v-for="val in options.energyValue"
                  :key="val.value"
                  :label="val.label"
                  :value="val.value"
                ></el-option>
              </el-select>
            </template>
            <template v-else>
              <el-input type="number" v-model="item.value" placeholder="请输入">
                <template slot="append">{{ getUnitLabel(item.unit) }}</template>
              </el-input>
            </template>
          </div>
          <span class="condition-link">且</span>
          <el-button type="text" class="danger-text" @click="removeCondition(index)">删除</el-button>
        </div>
        <el-button type="text" class="add-condition-btn" @click="addCondition">
          <i class="el-icon-plus"></i> 增加条件
        </el-button>
      </div>

      <!-- 第三部分：通知设置 -->
      <header-title title="通知设置"></header-title>
      <div class="table-header">
        <el-button type="primary" size="small" @click="addNotifyPerson">添加</el-button>
      </div>
      <el-table :data="form.notifyList" border style="width: 100%" max-height="250">
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column label="通知人" min-width="150" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.person" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="person in options.notifyPerson"
                :key="person.value"
                :label="person.label"
                :value="person.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" min-width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.phone" placeholder="请输入手机号码" />
          </template>
        </el-table-column>
        <el-table-column label="邮箱" min-width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.email" placeholder="请输入邮箱" />
          </template>
        </el-table-column>
        <el-table-column label="通知方式" min-width="200" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.notifySms">短信</el-checkbox>
            <el-checkbox v-model="scope.row.notifyEmail">邮件</el-checkbox>
            <el-checkbox v-model="scope.row.notifySystem">系统</el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="danger-text" @click="removeNotifyPerson(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template v-slot:footer>
      <el-button type="primary" @click="save()" v-loading="loading">确定</el-button>
      <el-button @click="cancel">取消</el-button>
    </template>
  </ele-modal>
</template>

<script>
  const defForm = {
    alarmLevel: '',
    alarmName: '',
    alarmTarget: 'device',
    deviceType: '',
    alarmDesc: '',
    status: true,
    deviceList: [
      { meterCode: 'D-1008#', meterNumber: '090809', meterName: '08#电表', meterType: '电表', energyType: '用电', energyArea: '生产区', useDept: '', ownerDept: '', areaManager: '' },
      { meterCode: 'D-1007#', meterNumber: '070707', meterName: '07#电表', meterType: '电表', energyType: '用电', energyArea: '生活区', useDept: '', ownerDept: '', areaManager: '' },
      { meterCode: 'D-1006#', meterNumber: '060606', meterName: '06#电表', meterType: '电表', energyType: '用电', energyArea: '办公区', useDept: '', ownerDept: '', areaManager: '' }
    ],
    triggerCondition: 'all',
    conditions: [
      { field: 'energyType', operator: 'eq', value: 'water' },
      { field: 'energyArea', operator: 'eq', value: '' },
      { field: 'dailyUsage', operator: 'gte', value: '1000', unit: 'm³' },
      { field: 'monthlyUsage', operator: 'gte', value: '30000', unit: 'm³' }
    ],
    notifyList: [
      { person: '', phone: '', email: '', notifySms: false, notifyEmail: false, notifySystem: false },
      { person: '', phone: '', email: '', notifySms: false, notifyEmail: false, notifySystem: false },
      { person: '', phone: '', email: '', notifySms: false, notifyEmail: false, notifySystem: false }
    ]
  };

  // 选项配置数据
  const optionsConfig = {
    alarmLevel: [
      { label: '紧急', value: 'urgent' },
      { label: '重要', value: 'important' },
      { label: '一般', value: 'normal' },
      { label: '提示', value: 'info' }
    ],
    alarmTarget: [
      { label: '数采设备', value: 'device' },
      { label: '用能统计', value: 'energy' }
    ],
    deviceType: [
      { label: '电表', value: 'electric' },
      { label: '水表', value: 'water' },
      { label: '气表', value: 'gas' }
    ],
    triggerCondition: [
      { label: '当满足以下所有条件时', value: 'all' },
      { label: '当满足以下任一条件时', value: 'any' }
    ],
    conditionField: [
      { label: '用能分类', value: 'energyType' },
      { label: '用能分区', value: 'energyArea' },
      { label: '日用量', value: 'dailyUsage' },
      { label: '月用量', value: 'monthlyUsage' }
    ],
    conditionOperator: [
      { label: '=', value: 'eq' },
      { label: '>', value: 'gt' },
      { label: '<', value: 'lt' },
      { label: '>=', value: 'gte' },
      { label: '<=', value: 'lte' }
    ],
    energyValue: [
      { label: '用水', value: 'water' },
      { label: '用电', value: 'electric' },
      { label: '用气', value: 'gas' }
    ],
    notifyPerson: [
      { label: '张三', value: '1' },
      { label: '李四', value: '2' },
      { label: '王五', value: '3' }
    ]
  };

  export default {
    data() {
      return {
        visible: false,
        loading: false,
        isEdit: false,
        form: JSON.parse(JSON.stringify(defForm)),
        options: optionsConfig,
        rules: {
          alarmLevel: [
            { required: true, message: '请选择告警级别', trigger: 'change' }
          ],
          alarmName: [
            { required: true, message: '请输入告警名称', trigger: 'blur' }
          ],
          alarmTarget: [
            { required: true, message: '请选择告警对象', trigger: 'change' }
          ],
          deviceType: [
            { required: true, message: '请选择告警设备类型', trigger: 'change' }
          ],
          triggerCondition: [
            { required: true, message: '请选择触发条件', trigger: 'change' }
          ]
        }
      };
    },
    methods: {
      open(row) {
        this.visible = true;
        if (row && row.id) {
          this.isEdit = true;
          this.form = {
            ...JSON.parse(JSON.stringify(defForm)),
            ...row
          };
        } else {
          this.isEdit = false;
          this.form = JSON.parse(JSON.stringify(defForm));
        }
      },
      cancel() {
        this.form = JSON.parse(JSON.stringify(defForm));
        this.visible = false;
        this.$refs.form && this.$refs.form.clearValidate();
      },
      addDevice() {
        this.$message.info('添加设备功能待实现');
      },
      removeDevice(index) {
        this.form.deviceList.splice(index, 1);
      },
      addCondition() {
        this.form.conditions.push({ field: '', operator: 'eq', value: '', unit: 'm³' });
      },
      getUnitLabel(unit) {
        const unitMap = {
          'm3': 'm³',
          'kwh': 'kWh',
          't': 't',
          'm³': 'm³'
        };
        return unitMap[unit] || unit;
      },
      removeCondition(index) {
        this.form.conditions.splice(index, 1);
      },
      addNotifyPerson() {
        this.form.notifyList.push({ person: '', phone: '', email: '', notifySms: false, notifyEmail: false, notifySystem: false });
      },
      removeNotifyPerson(index) {
        this.form.notifyList.splice(index, 1);
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true;
            setTimeout(() => {
              this.loading = false;
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功');
              this.cancel();
              this.$emit('reload');
            }, 500);
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .el-form-box {
    max-height: calc(100vh - 300px);
    overflow-y: auto;
  }
  .table-header {
    margin-bottom: 10px;
  }
  .condition-list {
    margin-bottom: 20px;
    .condition-row {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .condition-item {
        flex-shrink: 0;
        &:first-child {
          width: 200px;
        }
        &:nth-child(2) {
          width: 120px;
          margin: 0 10px;
        }
        &.value-item {
          flex: 1;
          max-width: 250px;
        }
        ::v-deep .el-select,
        ::v-deep .el-input {
          width: 100%;
        }
      }
      .condition-link {
        margin: 0 15px;
        color: #606266;
        flex-shrink: 0;
      }
    }
    .add-condition-btn {
      color: #409EFF;
    }
  }
  .danger-text {
    color: #F56C6C;
  }
</style>
