<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="addWarningDialog"
    width="60%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
  >
    <el-tabs
      type="border-card"
      v-model="tabActiveName"
      v-loading="saveLoading"
      @tab-click="handleTabClick"
    >
      <el-tab-pane label="基本信息" name="baseInfo">
        <el-form
          :model="baseInfoForm"
          :rules="baseInfoFormRules"
          ref="baseInfoFormRef"
          label-width="120px"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="告警级别：" prop="alarmLevel">
				<DictSelection dictName="告警级别" clearable v-model="baseInfoForm.alarmLevel" style="width: 80%">
				</DictSelection>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="告警设备类型：" prop="alarmEquipmentName" style="width: 90%">
				 <equipmentSelect v-model="baseInfoForm.alarmEquipmentName"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="告警名称：" prop="alarmName">
                <el-input
                  v-model="baseInfoForm.alarmName"
                  style="width: 80%"
                  placeholder="请输入告警名称"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="生成报修记录：">
                <el-switch
                  v-model="baseInfoForm.isCreate"
                  active-color="#13ce66"
                  inactive-color="#989898"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="状态：">
                <el-switch
                  v-model="baseInfoForm.status"
                  active-color="#13ce66"
                  inactive-color="#989898"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="告警描述：">
                <el-input
                  type="textarea"
                  :rows="3"
                  resize="none"
                  size="small"
                  v-model="baseInfoForm.alarmDescribe"
                  placeholder="请输入告警描述"
                  style="width: 85%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="触发条件：" prop="alarmTrigger">
                <el-select
                  filterable
                  v-model="baseInfoForm.alarmTrigger"
                  size="small"
                >
                  <el-option
                    label="当满足以下所有条件时"
                    :value="0"
                  ></el-option>
                  <el-option
                    label="当满足以下任一条件时"
                    :value="1"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="table_wrapper">
              <el-table
                :data="baseInfoForm.alarmTriggerList"
                style="width: 100%"
              >
                <el-table-column label="">
                  <template slot-scope="scope">
                    <el-select
                      filterable
                      v-model="scope.row.alarmType"
                      size="small"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in temperatureList"
                        :key="item.identifier"
                        :value="item.identifier"
                        :label="item.name"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="">
                  <template slot-scope="scope">
					<DictSelection dictName="告警触发条件" clearable v-model="scope.row.alarmCondition">
					</DictSelection>
                  </template>
                </el-table-column>
                <el-table-column label="">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.alarmValue"
                      oninput="value=value.replace(/[^\d.]/g,'')"
                      size="small"
                      placeholder="请输入值"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="" width="70">
                  <template slot-scope="scope">
                    <div class="alarm_trigger_handler">
                      <div
                        v-if="
                          scope.$index <
                          baseInfoForm.alarmTriggerList.length - 1
                        "
                      >
                        <span v-if="baseInfoForm.alarmTrigger === 0">且</span>
                        <span v-if="baseInfoForm.alarmTrigger === 1">或</span>
                      </div>
                      <el-button
                        v-if="scope.$index > 0"
                        type="text"
                        @click="handleDeleteTriggerCondition(scope.$index)"
                        >删除</el-button
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="handleAddTriggerCondition"
                >增加条件</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="告警方式：">
				  <DictSelection dictName="告警方式" clearable v-model="baseInfoForm.alarmMode">
				  </DictSelection>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="短信设置" name="shortMessage" disabled
        >短信设置</el-tab-pane
      >
      <el-tab-pane label="邮箱设置" name="email" disabled>邮箱设置</el-tab-pane>
      <el-tab-pane label="通知设置" name="notice">
        <div class="add_notice_table_row">
          <el-button type="primary" size="small" @click="handleAddNoticeRow"
            >添加</el-button
          >
        </div>
        <el-table
          :data="baseInfoForm.alarmNoticeSetList"
          style="width: 100%"
          border
        >
          <el-table-column label="" align="center" width="60">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="通知人" align="center">
            <template slot-scope="scope">
              <el-select
                filterable
                v-model="scope.row.alarmNotifierId"
                size="small"
              >
				<el-option
				  v-for="item in alarmNotifierList"
				  :key="item.id"
				  :value="item.id"
				  :label="item.name"
				></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.alarmNotifierPhone"
                size="small"
                placeholder="请输入手机号码"
                @blur="checkPhone(scope.$index, scope.row.alarmNotifierPhone)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.alarmNotifierMailbox"
                size="small"
                placeholder="请输入邮箱"
                @blur="checkMailbox(scope.$index, scope.row.mailbox)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="通知方式" width="260px" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.shortMessage">短信</el-checkbox>
              <el-checkbox v-model="scope.row.mail">邮件</el-checkbox>
              <el-checkbox v-model="scope.row.system">系统</el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="70px" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleDeleteNoticeRow(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button size="small" type="primary" @click="saveWarningSetting"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
	import equipmentSelect from '@/components/CommomSelect/equipment-select.vue';
	import { getUserPage } from '@/api/system/organization';
export default {
  components: { equipmentSelect  },
  props: {
    equipmentList: {
      type: Array,
      default: () => {
        return []
      }
    },
    viewForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogTitle: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      addWarningDialog: false,
      tabActiveName: 'baseInfo',
      saveLoading: false,
      baseInfoForm: {
        alarmLevel: '', // 告警级别
        alarmEquipmentId: '', // 告警设备类型id
        alarmEquipmentName: '', // 告警设备类型name
        alarmName: '', // 告警名称
        status: false, // 状态
        isCreate: false, // 是否生成保修工单
        alarmDescribe: '', // 告警描述
        alarmTrigger: 0, // 告警触发条件类型选择
        alarmMode: '', // 告警方式
        alarmTriggerList: [{}], // 基本信息触发条件表格
        alarmNoticeSetList: [
          {
            alarmNotifierId: '', // 告警通知人id
            alarmNotifierName: '', // 告警通知人name
            alarmNotifierMailbox: '', // 邮箱
            alarmNotifierPhone: '', // 电话
            mail: false, // 邮件
            shortMessage: false, // 短信
            system: false // 系统
          }
        ] // 通知设置表格
      },
      baseInfoFormRules: {
        alarmLevel: [
          { required: true, message: '请选择告警级别', trigger: 'change' }
        ],
        alarmEquipmentName: [
          { required: true, message: '请选择告警设备类型', trigger: 'change' }
        ],
        alarmName: [
          { required: true, message: '请输入告警名称', trigger: 'blur' }
        ],
        alarmTrigger: [
          { required: true, message: '请选择触发条件', trigger: 'change' }
        ]
      },
      alarmNotifierList: [], // 通知人用户列表
      temperatureList: [],
    }
  },
  watch: {
    viewForm (val) {
      console.log('shujval', val)
      this.baseInfoForm = val
      this.getTemperatureList(val.alarmEquipmentId)
    }
  },
  methods: {
    getTemperatureList (val) {
      warningSetting.getAlarmTermType(val).then(res => {
        if (res?.success) {
          this.temperatureList = res.data
        }
      })
    },

    // 告警设备类型变更
    async handleEquipmentChange (val) {
      this.baseInfoForm.alarmEquipmentId = val
      warningSetting
        .getAlarmTermType(this.baseInfoForm.alarmEquipmentId)
        .then(res => {
          if (res?.success) {
            this.temperatureList = res.data
            console.log('列表数据', this.temperatureList)
            this.baseInfoForm.alarmTriggerList.forEach(item => {
              if (item.alarmType) {
                item.alarmType = ''
              }
            })
          }
        })
        .catch(err => {
          this.temperatureList = []
          this.baseInfoForm.alarmTriggerList.forEach(item => {
            if (item.alarmType) {
              item.alarmType = ''
            }
          })
        })
    },
    // 获取通知人列表数据
	async getUserList() {
	  try {
	    let data = { pageNum: 1, size: -1 };
	    const res = await getUserPage(data);
	    this.alarmNotifierList = res.list;
	  } catch (error) {}
	},
	
    // tab栏切换
    handleTabClick (tab) {
      // 获取通知人下拉数据
      if (tab.name === 'notice') {
        this.getUserList()
      }
    },
    // 关闭新增弹窗
    handleClose () {
      this.addWarningDialog = false
      this._resetDialogInfo()
    },
    // 增加触发条件
    handleAddTriggerCondition () {
      this.baseInfoForm.alarmTriggerList.push({})
    },
    // 删除触发条件
    handleDeleteTriggerCondition (index) {
      this.baseInfoForm.alarmTriggerList.splice(index, 1)
    },
    // 通知设置 - 添加表格一行
    handleAddNoticeRow () {
      this.baseInfoForm.alarmNoticeSetList.push({
        alarmNotifierId: '', // 告警通知人id
        alarmNotifierName: '', // 告警通知人name
        alarmNotifierMailbox: '', // 邮箱
        alarmNotifierPhone: '', // 电话
        mail: false, // 邮件
        shortMessage: false, // 短信
        system: false // 系统
      })
    },
    // 通知设置 - 删除表格一行
    handleDeleteNoticeRow (index) {
      this.baseInfoForm.alarmNoticeSetList.splice(index, 1)
    },
    // 验证手机号
    checkPhone (index, phone) {
      const phoneReg = /^1[345789]\d{9}$/
      if (phone && !phoneReg.test(phone)) {
        this.baseInfoForm.alarmNoticeSetList[index].alarmNotifierPhone = ''
        return this.$message.error('手机号码格式错误，请重新输入！')
      }
    },
    // 验证邮箱
    checkMailbox (index, mailbox) {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (mailbox && !mailReg.test(mailbox)) {
        this.baseInfoForm.alarmNoticeSetList[index].alarmNotifierMailbox = ''
        return this.$message.error('邮箱格式错误，请重新输入！')
      }
    },
    // 保存
    async saveWarningSetting () {
      this.$refs.baseInfoFormRef.validate(async valid => {
        if (valid) {
          try {
            this.saveLoading = true
            const res = await warningSetting.saveWarningSetting(
              this.baseInfoForm
            )
            // console.log('新增告警结果：', res)
            this.addWarningDialog = false
            this._resetDialogInfo()
            this.saveLoading = false
            this.$emit('refreshList')
            this.$message.success('新增成功！')
          } catch (error) {
            this.saveLoading = false
          }
        }
      })
    },
    // 重置弹窗信息
    _resetDialogInfo () {
      this.baseInfoForm = {
        alarmLevel: '', // 告警级别
        alarmEquipmentId: '', // 告警设备类型id
        alarmEquipmentName: '', // 告警设备类型name
        alarmName: '', // 告警名称
        status: false, // 状态
        isCreate: false, // 是否生成保修工单
        alarmDescribe: '', // 告警描述
        alarmTrigger: 0, // 告警触发条件类型选择
        alarmMode: '', // 告警方式
        alarmTriggerList: [{}], // 基本信息触发条件表格
        alarmNoticeSetList: [
          {
            alarmNotifierId: '', // 告警通知人id
            alarmNotifierName: '', // 告警通知人name
            alarmNotifierMailbox: '', // 邮箱
            alarmNotifierPhone: '', // 电话
            mail: false, // 邮件
            shortMessage: false, // 短信
            system: false // 系统
          }
        ] // 通知设置表格
      }
      this.tabActiveName = 'baseInfo'
      this.$refs.baseInfoFormRef.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
  font-weight: 700;
  font-size: 20px;
}
.table_wrapper {
  padding-left: 120px;
  padding-right: 8vw;
  ::v-deep .el-table__header-wrapper {
    display: none;
  }
  ::v-deep .el-table .cell {
    padding-left: 0;
  }
}
.add_notice_table_row {
  text-align: right;
  padding-bottom: 8px;
}
.alarm_trigger_handler {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
::v-deep .el-form-item {
  margin-bottom: 14px;
}
::v-deep .el-form-item__error {
  padding-top: 0;
}
</style>
