<template>
  <div class="matter-add">
    <ele-modal
      :title="dialogTitle"
      :visible.sync="addMatterDialog"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="100%"
      :maxable="true"
    >
      <el-form
        :model="formData"
        v-loading="dialogLoading"
        ref="contentConfigForm"
        label-width="100px"
        :show-message="false"
        :rules="contentConfigFormRules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="规则编码" prop="ruleCode">
              <el-input
                v-model="formData.ruleCode"
                size="small"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input
                v-model="formData.ruleName"
                placeholder="请输入"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预警对象" prop="ruleObjCode">
              <el-select
                v-model="formData.ruleObjCode"
                size="small"
                :disabled="isBindPlan == 'edit'"
                style="width: 100%"
              >
                <el-option
                  v-for="(value, key) in allRulesData"
                  :key="key"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="周期" prop="alertCycleValue">
              <el-col :span="16">
                <el-input
                  v-model="formData.alertCycleValue"
                  placeholder="请输入"
                  size="small"
                  @input="handleInput"
                />
              </el-col>
              <el-col :span="8">
                <el-form-item prop="alertCycleUnit" label-width="0px">
                  <el-select v-model="formData.alertCycleUnit" size="small">
                    <el-option
                      v-for="(value, key) in cycleUnitOpt"
                      :key="key"
                      :label="value"
                      :value="key"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col> -->

          <el-col :span="8">
            <el-form-item label="状态" prop="enabled">
              <el-select
                v-model="formData.enabled"
                size="small"
                style="width: 100%"
              >
                <el-option label="生效" :value="1">生效</el-option>
                <el-option label="失效" :value="0">失效</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table
          ref="multipleTable"
          :data="formData.actionList"
          tooltip-effect="dark"
          style="width: 95%; margin: auto"
          border
          :header-cell-style="{ background: '#F0F3F3' }"
        >
          <el-table-column type="index" width="50" align="left">
            <template slot="header">
              <el-button type="text" @click="addItem" style="padding: 0"
                >新增</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="targetAddressName" label="通知人" width="240">
            <template slot-scope="scope">
              <el-form-item
                :prop="'actionList.' + scope.$index + '.targetAddressName'"
                label-width="0"
                :rules="contentConfigFormRules.targetAddressName"
              >
                <el-input
                  placeholder="请选择"
                  v-model="scope.row.targetAddressName"
                  @focus="handleAddInfo(scope.row, scope.$index)"
                >
                  <template #suffix>
                    <el-badge :value="NumberOfPeople"></el-badge>
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="alertLevel" label="预警级别" width="120">
            <template slot-scope="scope">
              <el-form-item
                :prop="'actionList.' + scope.$index + '.alertLevel'"
                label-width="0"
                :rules="contentConfigFormRules.alertLevel"
              >
                <el-select size="small" v-model="scope.row.alertLevel">
                  <el-option
                    v-for="(value, key) in allAlertLevelData"
                    :key="key"
                    :label="value"
                    :value="key"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="matterRuleId" label="事项规则" width="260">
            <template slot-scope="scope">
              <el-form-item
                :prop="'actionList.' + scope.$index + '.matterRuleId'"
                label-width="0"
                :rules="contentConfigFormRules.matterRuleId"
              >
                <el-link
                  type="primary"
                  :underline="false"
                  @click="
                    detailsDialog = true;
                    currentId = scope.row.matterRuleId;
                  "
                >
                  {{ scope.row.matterRuleName }}
                </el-link>
                <el-button
                  type="primary"
                  size="mini"
                  @click="
                    currentIndex = scope.$index;
                    addDialog = true;
                  "
                >
                  选择
                </el-button>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="thresholdValue" label="阈值" width="100">
            <template slot-scope="scope">
              <el-form-item
                :prop="'actionList.' + scope.$index + '.thresholdValue'"
                label-width="0"
                :rules="contentConfigFormRules.thresholdValue"

              >
                <el-input
                  v-model="scope.row.thresholdValue"
                  placeholder="请输入"
                  type="number"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="actionType" label="操作类型" width="120">
            <template slot-scope="scope">
              <el-form-item
                :prop="'actionList.' + scope.$index + '.actionType'"
                label-width="0"
                :rules="contentConfigFormRules.actionType"
              >
                <el-select size="small" v-model="scope.row.actionType">
                  <el-option
                    v-for="(value, key) in operationTypeData"
                    :key="key"
                    :label="value"
                    :value="key"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            prop="alertMessageTempateCode"
            label="模板编码"
            width="500"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="
                  'actionList.' + scope.$index + '.alertMessageTempateCode'
                "
                style="width: 100%"
                label-width="0"
                :rules="contentConfigFormRules.alertMessageTempateCode"
              >
                <el-select
                  style="width: 100%"
                  placeholder="请选择"
                  v-model="scope.row.alertMessageTempateCode"
                  @change="changeTemplate(scope.row, scope.$index)"
                  filterable
                >
                  <el-option
                    v-for="item in templateData"
                    :key="item.code"
                    :label="item.name + '-' + item.code"
                    :value="item.code"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容">
            <template slot-scope="scope">
              <el-input
                type="textarea"
                size="small"
                placeholder="请输入"
                v-model="scope.row.content"
                disabled
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="delItem(scope.$index)"
                size="small"
                :disabled="isBindPlan == 'clone'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template v-slot:footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="dataKeep"> 保存 </el-button>
      </template>
    </ele-modal>
    <select-person-dialog
      ref="selectPersonDialogRef"
      @changeParent="changeParent"
    ></select-person-dialog>

    <!-- 添加规则 -->
    <ele-modal
      width="800px"
      :visible="addDialog"
      :append-to-body="true"
      title="规则配置"
      :close-on-click-modal="false"
      @update:visible="addDialog = false"
      :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"
          @click.native="ruleChange(item)"
        ></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
      width="80%"
      :visible="detailsDialog"
      :append-to-body="true"
      title="规则详情"
      :close-on-click-modal="false"
      @update:visible="detailsDialog = false"
      :maxable="true"
    >
      <ruleDetails
        :isModal="true"
        :id="currentId"
        v-if="detailsDialog"
      ></ruleDetails>
    </ele-modal>
    <!-- ruleDetails -->
  </div>
</template>
<script>
  import { deepClone } from '@/utils/index';
  import {
    rulesSave,
    rulesUpdate,
    getCode,
    getDetail,
    listAllRulesObj,
    listAllDateUnit,
    listAllActionType,
    listAllAlertLevel
  } from '@/api/ruleManagement/earlyWarning';
  import { notifyTemplatePageAPI } from '@/api/notifyManage';
  import { getUserPage } from '@/api/system/organization';
  import selectPersonDialog from './user-select/user-select.vue';
  import ruleDetails from '@/views/rulesManagement/matterRules/details.vue';
  import { getRule } from '@/api/ruleManagement/plan';

  export default {
    components: { selectPersonDialog, ruleDetails },
    props: {
      dialogTitle: {
        type: String,
        default: '新建规则'
      },
      dialogLoading: {
        type: Boolean,
        default: () => {
          return false;
        }
      }
    },
    data() {
      return {
        addMatterDialog: false,
        addDialog: false,
        detailsDialog: false,
        ruleId: '',
        ruleName: '',
        currentIndex: '',
        ruleNameList: [],
        currentId: '',
        formData: {
          ruleCode: '',
          ruleName: '',
          ruleObjCode: '',
          alertCycleValue: '1',
          alertCycleUnit: '',
          enabled: 1,
          actionList: [
            {
              targetAddress: '',
              targetAddressName: '',
              actionType: '',
              alertLevel: '',
              thresholdValue: '',
              alertMessageTempateCode: '',
              content: ''
            }
          ]
        },
        contentConfigFormRules: {
          ruleCode: [
            { required: true, message: '请输入规则编码', trigger: 'blur' }
          ],
          ruleName: [
            { required: true, message: '请输入规则名称', trigger: 'blur' }
          ],
          ruleObjCode: [
            { required: true, message: '请选择预警对象', trigger: 'blur' }
          ],
          // matterRuleId: [
          //   { required: true, message: '请选择预警规则', trigger: 'blur' }
          // ],

          alertCycleUnit: [
            { required: true, message: '请输入周期单位', trigger: 'blur' }
          ],
          alertCycleValue: [
            { required: true, message: '请输入周期', trigger: 'blur' }
          ],
          alertLevel: [
            { required: true, message: '请选择紧急程度', trigger: 'blur' }
          ],
          targetAddressName: [
            { required: true, message: '请选择通知人', trigger: 'blur' }
          ],
          actionType: [
            { required: true, message: '请选择操作类型', trigger: 'blur' }
          ],
          thresholdValue: [
            { required: true, message: '请输入阈值', trigger: 'blur' }
          ],
          alertMessageTempateCode: [
            { required: true, message: '请选择模板编码', trigger: 'blur' }
          ]
        },
        isBindPlan: '',
        managerData: [],
        templateData: [],
        NumberOfPeople: '',

        allRulesData: {},
        cycleUnitOpt: {},
        operationTypeData: {},
        allAlertLevelData: {}
      };
    },
    watch: {},
    created() {
      this.getAllData();
      this.gettemplateList();
      this.getInfo();
      this.getRule();
    },

    methods: {
      async getRule() {
        const res = await getRule({
          status: 1,
          type: 8,
          pageNum: 1,
          size: -1
        });
        this.ruleNameList = res?.list || [];
      },
      ruleChange(item) {
        this.ruleId = item.id;
        this.ruleName = item.name;
      },
      addRule() {
        this.$set(
          this.formData.actionList[this.currentIndex],
          'matterRuleId',
          this.ruleId
        );
        this.$set(
          this.formData.actionList[this.currentIndex],
          'matterRuleName',
          this.ruleName
        );
        this.addDialog = false;
      },
      handleInput(value) {
        this.formData.alertCycleValue = this.$handleInputPublic(value);
      },
      handleInputByTable(value, index) {
        // 表内限制输入框 只保留数字和小数点
        const filteredValue = value.replace(/[^0-9.]/g, '');
        let finalValue = '';
        const dotIndex = filteredValue.indexOf('.');
        if (dotIndex !== -1) {
          finalValue = filteredValue.slice(0, dotIndex + 3);
        } else {
          finalValue = filteredValue;
        }
        this.formData.actionList[index].thresholdValue = finalValue;
      },
      async getAllData() {
        try {
          const res1 = await listAllRulesObj();
          this.allRulesData = res1;
          const res2 = await listAllDateUnit();
          this.cycleUnitOpt = res2;
          const res3 = await listAllActionType();
          this.operationTypeData = res3;
          const res4 = await listAllAlertLevel();
          this.allAlertLevelData = res4;
        } catch (error) {
          console.error('Failed to load data:', error);
          throw error;
        }
      },
      handleAddInfo(row, index) {
        this.NumberOfPeople = '';
        this.formData.actionList[index].targetAddress = '';
        this.formData.actionList[index].targetAddressName = '';
        this.$refs.selectPersonDialogRef.open(row, index);
      },
      changeParent(list, index) {
        if (list.length > 10) {
          this.$message.warning('最多选择10个通知人！');
          return;
        }
        this.NumberOfPeople = list.length;
        console.log(list.length, 'list', this.isBindPlan);
        let ids = list
          .map((item) => {
            return item.id;
          })
          .join(',');
        let names = list
          .map((item) => {
            return item.name;
          })
          .join(',');
        this.formData.actionList[index].targetAddress = ids;
        this.formData.actionList[index].targetAddressName = names;
      },
      changeTemplate(row, index) {
        console.log(row, index);
        this.formData.actionList[index].alertMessageTempateCode =
          row.alertMessageTempateCode;
        this.templateData.filter((item) => {
          if (item.code == row.alertMessageTempateCode) {
            this.formData.actionList[index].content = item.content;
          }
        });
      },
      async gettemplateList() {
        const res = await notifyTemplatePageAPI({
          pageNum: 1,
          size: 999
        });
        if (res?.list) {
          this.templateData = res.list;
        }
      },
      async getInfo() {
        getUserPage({
          size: 999
        }).then((res) => {
          this.managerData = res.list;
        });
      },
      async openDialog(row, type) {
        this.isBindPlan = type;
        if (type == 'edit') {
          this.getRuleInfo(row.id, type);
        }
        if (type == 'add') {
          this.getOrderCode();
        }
        if (type == 'clone') {
          this.getOrderCode();
          this.getRuleInfo(row.id, type);
        }

        this.addMatterDialog = true;
      },

      async getRuleInfo(id, type) {
        const data = await getDetail(id);
        this.formData = deepClone(data);
        if (this.isBindPlan == 'clone') {
          this.formData.ruleObjCode = '';
        }

        if (data.actionList && data.actionList.length > 0) {
          for (let i = 0; i < data.actionList.length; i++) {
            const ele = data.actionList[i].alertMessageTempateCode;
            const template = this.templateData.find(
              (item) => item.code === ele
            );
            if (template) {
              data.actionList[i].content = template.content + '';
            }
            data.actionList.map((item) => {
              item.actionType = item.actionType + '';
              item.alertLevel = item.alertLevel + '';
            });
          }
          this.formData.actionList = data.actionList;
        }

        if (type == 'clone') {
          delete this.formData.id;
        }
      },

      async getOrderCode() {
        const data = await getCode('warn_rule_code');
        this.$set(this.formData, 'ruleCode', data);
      },

      handleClose() {
        this.NumberOfPeople = '';
        this.formData = {
          ruleCode: '',
          ruleName: '',
          ruleObjCode: '',
          alertCycleUnit: ''
        };
        this.formData.actionList = [];
        this.addMatterDialog = false;
      },
      addItem() {
        if (this.formData.actionList) {
          this.formData.actionList.push({
            targetAddress: '',
            targetAddressName: '',
            actionType: '',
            alertLevel: '',
            thresholdValue: '',
            alertMessageTempateCode: '',
            content: ''
          });
        } else {
          let arr = [
            {
              targetAddress: '',
              targetAddressName: '',
              actionType: '',
              alertLevel: '',
              thresholdValue: '',
              alertMessageTempateCode: '',
              content: ''
            }
          ];
          this.$set(this.formData, 'actionList', arr);
        }
      },
      delItem(index) {
        this.formData.actionList.splice(index, 1);
      },

      // 保存
      dataKeep() {
        console.log(this.isBindPlan, 'dsdsds');
        let form = deepClone(this.formData);
        console.log(form, 'form');
        if (form.actionList.length < 1) {
          this.$message.error('请添加预警内容！');
          return;
        }
        let actionListLen = form.actionList.filter((item) => item.matterRuleId);
        if (actionListLen?.length != form.actionList.length) {
          this.$message.error('预警规则不能为空！');
          return;
        }
        this.$refs.contentConfigForm.validate(async (valid) => {
          if (valid) {
            let request =
              this.isBindPlan != 'add' && this.isBindPlan != 'clone'
                ? rulesUpdate
                : rulesSave;

            let res = await request(form);
            if (res) {
              this.$message.success('操作成功！');
              this.handleClose();
              this.$emit('done');
            }
          }
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .operationGuide_box {
    width: 100%;
    height: 50px;
    display: flex;
    overflow: hidden;
    cursor: pointer;

    .left_content {
      flex: 0 0 200px;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #c0c4cc;
      border-radius: 10px;
      margin-right: 10px;
      overflow-y: auto;
    }

    .right_content {
      flex: 1;
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid #c0c4cc;
      border-radius: 10px;
      overflow-y: auto;
    }
  }

  .form-ipt {
    width: 310px;
  }

  .details-div {
    font-size: 14px;
    padding-left: 40px;

    .details-div-title {
      display: flex;
      justify-content: space-between;

      span {
        padding-top: 8px;
      }
    }
  }

  .zw-container {
    height: 450px;
  }

  .page-footer-btn {
    margin: 20px 0;
    text-align: center;
  }

  // .app-container {
  ::v-deep .el-form-item {
    margin-bottom: 14px;
  }

  ::v-deep .el-table__body-wrapper {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  ::v-deep .el-form-item__error {
    padding-top: 0;
  }

  .cycle_value {
    ::v-deep .el-input__inner {
      text-align: center;
    }
  }

  ::v-deep .el-table .cell {
    display: flex;
  }
  ::v-deep .el-input-number .el-input__inner {
    text-align: left !important;
  }

  ::v-deep .el-badge__content {
    font-size: 10px;
  }
</style>
