<template>
  <ele-modal
    :title="dialogType == 'add' ? '新增' : 'edit' ? '修改' : '详情'"
    :visible.sync="addWarningDialog"
    width="60%"
    :close-on-click-modal="true"
    :close-on-press-escape="false"
    :before-close="handleClose"
    :maxable="true"
  >
    <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"
          :disabled="dialogType == 'view'"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="告警级别：" prop="level">
                <el-select filterable v-model="baseInfoForm.level" size="small">
                  <el-option label="提示" :value="1"></el-option>
                  <el-option label="一般" :value="2"></el-option>
                  <el-option label="严重" :value="3"></el-option>
                  <el-option label="紧急" :value="4"></el-option>
                  <el-option label="致命" :value="5"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="告警设备："
                prop="deviceName"
                style="width: 90%"
              >
                <el-input
                  v-model="baseInfoForm.deviceName"
                  style="width: 80%"
                  placeholder="请选择"
                  readonly
                  @click.native="
                    $refs.materialAddRef.open(
                      null,
                      null,
                      false,
                      null,
                      null,
                      true
                    )
                  "
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="告警名称：" prop="name">
                <el-input
                  v-model="baseInfoForm.name"
                  style="width: 80%"
                  placeholder="请输入告警名称"
                  size="small"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择生成单据：">
                <el-radio-group
                  v-model="baseInfoForm.generateDocumentType"
                  @change="isCreateChange"
                >
                  <el-radio :label="3">维修</el-radio>
                  <el-radio :label="1">巡点检</el-radio>
                  <el-radio :label="2">保养</el-radio>
                  <el-radio :label="5">量具送检</el-radio>
                </el-radio-group>
              </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.description"
                  placeholder="请输入告警描述"
                  style="width: 85%"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="触发条件：" prop="triggerLogic">
                <el-select
                  filterable
                  v-model="baseInfoForm.triggerLogic"
                  size="small"
                >
                  <el-option
                    label="当满足以下所有条件时"
                    :value="1"
                  ></el-option>
                  <el-option
                    label="当满足以下任一条件时"
                    :value="2"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" class="table_wrapper">
              <el-table :data="baseInfoForm.conditions" style="width: 100%">
                <el-table-column label="">
                  <template slot-scope="scope">
                    <el-select
                      filterable
                      v-model="scope.row.attributeCode"
                      size="small"
                      style="width: 100%"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in temperatureList"
                        :key="item.identifier"
                        :value="item.identifier"
                        :label="item.name"
                        @click.native="attributeChange(item, scope.$index)"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="">
                  <template slot-scope="scope">
                    <DictSelection
                      dictName="告警触发条件"
                      clearable
                      v-model="scope.row.operator"
                    >
                    </DictSelection>
                  </template>
                </el-table-column>
                <el-table-column label="">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.thresholdValue"
                      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.conditions.length - 1"
                      >
                        <span v-if="baseInfoForm.triggerLogic === 1">且</span>
                        <span v-if="baseInfoForm.triggerLogic === 2">或</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-form>

        <el-button
          v-if="[1, 2, 5].includes(baseInfoForm.generateDocumentType)"
          type="primary"
          size="small"
          style="margin-bottom: 10px"
          @click="handleAddTab"
          >添加规则</el-button
        >
        <div
          class="el-tab_box"
          v-if="[1, 2, 5].includes(baseInfoForm.generateDocumentType)"
        >
          <div class="ruleMatters_box">
            <header-title title="规则事项">
              <div>
                <el-button
                  size="small"
                  icon="el-icon-plus"
                  class="ele-btn-icon"
                  type="primary"
                  @click="addPostscript"
                  >新增</el-button
                >
              </div>
            </header-title>
            <el-table :data="baseInfoForm.workItems" border>
              <el-table-column label="序号" width="50">
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="零部件编码"
                prop="categoryCode"
                width="100"
              >
                <template slot-scope="scope">
                  <div>
                    <el-input
                      v-model="scope.row.categoryCode"
                      placeholder="请输入零部件编码"
                    ></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="零部件名称"
                prop="categoryName"
                width="100"
              >
                <template slot-scope="scope">
                  <div>
                    <el-input
                      v-model="scope.row.categoryName"
                      placeholder="请输入零部件名称"
                    ></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="事项" prop="name" width="100">
                <template slot-scope="scope">
                  <div>
                    <el-input
                      v-model="scope.row.name"
                      placeholder="请输入内容"
                    ></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="内容" prop="content" width="200">
                <template slot-scope="scope">
                  <div>
                    <el-input
                      v-model="scope.row.content"
                      placeholder="请输入内容"
                    ></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作指导" prop="operationGuide">
                <template slot-scope="scope">
                  <div
                    class="operationGuide_box"
                    @click="
                      openOperationGuideDialogDialog(
                        scope.row.operationGuide,
                        scope.$index
                      )
                    "
                  >
                    <div class="left_content">
                      <template v-if="scope.row.operationGuide">
                        <div
                          v-for="(item, index) in scope.row.operationGuide
                            .toolList"
                          :key="item.id"
                          >{{ index + 1 }}.{{ item.name }}</div
                        >
                      </template>
                    </div>
                    <div class="right_content">
                      <template v-if="scope.row.operationGuide">
                        <div
                          v-for="(item, index) in scope.row.operationGuide
                            .procedureList"
                          :key="item.id"
                          >{{ index + 1 }}.{{ item.content }}</div
                        >
                      </template>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="标准" prop="norm" width="100">
                <template slot-scope="scope">
                  <div>
                    <el-input
                      v-model="scope.row.norm"
                      placeholder="请输入内容"
                    ></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button type="text" @click="deleteItem(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </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.notices" 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.receiverIds"
                size="small"
              >
                <el-option
                  v-for="item in alarmNotifierList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                  @click.native="receiver(item, scope.$index)"
                ></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"
        v-if="dialogType != 'view'"
        >确 定</el-button
      >
    </span>
    <MaterialAdd ref="materialAddRef" @chooseEquipment="chooseEquipment">
    </MaterialAdd>

    <!-- 添加规则 -->
    <ele-modal
      width="800px"
      :visible="addDialog"
      :append-to-body="true"
      title="规则配置"
      :close-on-click-modal="true"
      :maxable="true"
    >
      <el-select v-model="ruleId" size="small" style="width: 100%" filterable>
        <el-option
          v-for="item in ruleNameList"
          :key="item.id"
          :value="item.id"
          :label="item.code + '-' + item.name"
        ></el-option>
      </el-select>
      <template v-slot:footer>
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="addRule"> 添加 </el-button>
      </template>
    </ele-modal>
  </ele-modal>
</template>

<script>
  import MaterialAdd from '@/views/maintenance/components/MaterialAdd.vue';
  import { getDetail } from '@/api/ruleManagement/matter';
  import { getRule } from '@/api/ruleManagement/plan';
  import { getUserPage } from '@/api/system/organization';
  import { getPhysicalModel } from '@/api/ledgerAssets/equipment';
  import { save, update, getById } from '@/api/warning/index.js';
  const defaultForm = {
    level: '', // 告警级别
    deviceId: '',
    deviceName: '',
    deviceCode: '',
    iotId: '',
    ruleId: '',
    name: '', // 告警名称
    generateDocumentType: null, // 是否生成保修工单
    description: '', // 告警描述
    triggerLogic: 1, // 告警触发条件类型选择
    alarmMode: '', // 告警方式
    conditions: [
      // {
      //   attributeCode: 'identifier',
      //   attributeName: '温度'
      // }
      {}
    ], // 基本信息触发条件表格
    notices: [
      {
        receiverIds: '', // 告警通知人id
        receiverName: '', // 告警通知人name
        noticeTypes: '3'
      }
    ] // 通知设置表格
  };

  export default {
    components: { MaterialAdd },
    props: {},
    data() {
      return {
        addWarningDialog: false,
        dialogType: 'add',
        addDialog: false,
        tabActiveName: 'baseInfo',
        ruleNameList: [],
        workItems: [],
        ruleId: '',
        saveLoading: false,
        baseInfoForm: { ...defaultForm },
        baseInfoFormRules: {
          level: [
            { required: true, message: '请选择告警级别', trigger: 'change' }
          ],
          deviceName: [
            { required: true, message: '请选择告警名称', trigger: 'blur' },
            { required: true, message: '请选择告警名称', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入告警名称', trigger: 'blur' }
          ],
          triggerLogic: [
            { required: true, message: '请选择触发条件', trigger: 'change' }
          ]
        },
        alarmNotifierList: [], // 通知人用户列表
        temperatureList: []
      };
    },
    watch: {},
    methods: {
      async chooseEquipment(data) {
        this.baseInfoForm.deviceId = data.id;
        this.baseInfoForm.deviceName = data.name;
        this.baseInfoForm.deviceCode = data.code;
        this.baseInfoForm.deviceCode = data.code;
        this.baseInfoForm.iotId = data.iotId;
        this.baseInfoForm.conditions = [];
        getPhysicalModel(data.id).then((res) => {
          this.temperatureList = res.properties;
        });
      },
      // 获取通知人列表数据
      async getUserList() {
        try {
          let data = { pageNum: 1, size: -1 };
          const res = await getUserPage(data);
          this.alarmNotifierList = res.list;
        } catch (error) {}
      },
      async isCreateChange(val) {
        const res = await getRule({
          status: 1,
          type: val,
          pageNum: 1,
          size: -1
        });
        if (res.list) {
          this.ruleNameList = res.list || [];
        }
      },
      // tab栏切换
      handleTabClick(tab) {
        // 获取通知人下拉数据
        if (tab.name === 'notice') {
          this.getUserList();
        }
      },
      handleAddTab() {
        this.ruleId = '';
        this.addDialog = true;
      },
      async addRule() {
        const data = await getDetail(this.ruleId);
        this.baseInfoForm.ruleId = this.ruleId;
        this.baseInfoForm.workItems = data.ruleItems;
        this.addDialog = false;
      },
      /* 打开操作手册编辑款 */
      openOperationGuideDialogDialog(row, index) {
        if (this.dialogTitle !== '派单') {
          this.$refs.operationGuideDialog.open(row, index);
        }
      },
      attributeChange(item, index) {
        this.$set(
          this.baseInfoForm.conditions[index],
          'attributeName',
          item.name
        );
      },
      receiver(item, index) {
        console.log(index, 'index');
        this.$set(this.baseInfoForm.notices[index], 'receiverName', item.name);
      },

      deleteItem(index) {
        if (this.baseInfoForm.workItems.length > 1) {
          this.baseInfoForm.workItems.splice(index, 1);
        } else {
          this.$message.error('至少要有一个规则事项！');
        }
      },
      addPostscript() {
        if (!this.baseInfoForm?.workItems?.length) {
          this.$message.error('请先添加规则！');
          return;
        }
        this.baseInfoForm.workItems.push({
          sort: null,
          name: '',
          content: '',
          norm: '',
          isNew: true,
          operationGuide: {
            procedureList: [],
            toolList: []
          }
        });
      },
      // 关闭新增弹窗
      handleClose() {
        this.addWarningDialog = false;
        this._resetDialogInfo();
      },
      async open(type, row) {
        this.tabActiveName = 'baseInfo';
        this.addWarningDialog = true;
        this.dialogType = type;
        if (row) {
          this.baseInfoForm = await getById(row.id);
          if (this.baseInfoForm.deviceId) {
            getPhysicalModel(this.baseInfoForm.deviceId).then((res) => {
              this.temperatureList = res.properties;
            });
          }
        }
      },
      // 增加触发条件
      handleAddTriggerCondition() {
        this.baseInfoForm.conditions.push({});
      },
      // 删除触发条件
      handleDeleteTriggerCondition(index) {
        this.baseInfoForm.conditions.splice(index, 1);
      },
      // 通知设置 - 添加表格一行
      handleAddNoticeRow() {
        this.baseInfoForm.notices.push({
          receiverIds: '', // 告警通知人id
          receiverName: '', // 告警通知人name
          noticeTypes: '3'
        });
      },
      // 通知设置 - 删除表格一行
      handleDeleteNoticeRow(index) {
        this.baseInfoForm.notices.splice(index, 1);
      },
      // 验证手机号
      checkPhone(index, phone) {
        const phoneReg = /^1[345789]\d{9}$/;
        if (phone && !phoneReg.test(phone)) {
          this.baseInfoForm.notices[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.notices[index].alarmNotifierMailbox = '';
          return this.$message.error('邮箱格式错误，请重新输入！');
        }
      },

      // 保存
      async saveWarningSetting() {
        let is = false;
        if (
          [1, 2, 5].includes(this.baseInfoForm.generateDocumentType) &&
          !this.baseInfoForm?.workItems?.length
        ) {
          this.$message.error('规则不能为空！');
          return;
        }
        if (!this.baseInfoForm?.conditions?.length) {
          this.$message.error('触发条件不能为空');
          return;
        } else {
          this.baseInfoForm?.conditions.forEach((item, index) => {
            console.log(item, 'item');
            if (!item.attributeCode || !item.operator || !item.thresholdValue) {
              is = true;
            }
          });
        }
        if (is) {
          this.$message.error('触发条件内容没填写完整，前检查！');
          return;
        }
        this.$refs.baseInfoFormRef.validate(async (valid) => {
          if (valid) {
            this.saveLoading = true;
            let api = this.baseInfoForm.id ? update : save;
            api(this.baseInfoForm)
              .then((res) => {
                this._resetDialogInfo();
                this.saveLoading = false;
                this.addWarningDialog = false;
                this.$emit('refreshList');
                this.$message.success('操作成功！');
              })
              .finally(() => {
                this.saveLoading = false;
              });
          }
        });
      },
      // 重置弹窗信息
      _resetDialogInfo() {
        this.baseInfoForm = {
          ...defaultForm
        };
        this.tabActiveName = 'baseInfo';
        this.$refs.baseInfoFormRef.resetFields();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .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>
