<template>
  <div class="supervision-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="提醒名称">
          <el-input
            v-model="searchForm.rulesName"
            placeholder="请输入项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="提醒类型">
          <el-select
            v-model="searchForm.alertType"
            placeholder="全部"
            clearable
          >
            <el-option label="全部" value="" />
            <el-option label="申报任务即将结束" value="3" />
            <el-option label="项目即将建设完成" value="2" />
            <el-option label="全局自定义通知" value="1" />
            <el-option label="项目自定义通知" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tablebox">
      <div class="operation-area">
        <el-button
          type="primary"
          @click="handleAdd"
          icon="el-icon-circle-plus-outline"
          >添加规则</el-button
        >
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
       >
        <!-- <el-table-column type="selection" align="center" /> -->
        <el-table-column label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="rulesName"
          label="提醒名称"
          min-width="200"
          align="center"
        />
        <el-table-column
          prop="alertType"
          label="提醒类型"
          min-width="150"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.alertType === 1">全局自定义通知</span>
            <span v-if="scope.row.alertType === 2">项目即将结束(企业)</span>
            <span v-if="scope.row.alertType === 3">项目即将建设完成(政务)</span>
            <span v-if="scope.row.alertType === 4">项目自定义通知</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="alertRecipients"
          label="提醒对象"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.alertRecipients === 2">政务用户</span>
            <span v-if="scope.row.alertRecipients === 1">企业用户</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="alertManner"
          label="提醒方式"
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.alertManner == 1">定期提醒</span>
            <span v-if="scope.row.alertManner == 2">不定期提醒</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="alertTime"
          label="提醒时间"
          min-width="180"
          align="center"
        />

        <!-- <el-table-column
          prop="createBy"
          label="创建人"
          min-width="120"
          align="center"
        /> -->
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
              style="color: #67c23a"
              >编辑</el-button
            >
            <el-button
              type="text"
              @click="handleDelete(scope.row)"
              style="color: red"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="pagination.total > 0"
        :total="pagination.total"
        :page.sync="pagination.current"
        :limit.sync="pagination.size"
        @pagination="handleSearch"
      />
    </div>

    <!-- 添加规则弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        size="small"
      >
        <el-form-item label="提醒规则标题" prop="rulesName">
          <el-input
            v-model="ruleForm.rulesName"
            placeholder="请输入提醒规则标题"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="提醒对象" prop="alertRecipients">
          <el-radio-group v-model="ruleForm.alertRecipients" :disabled="isView">
            <el-radio label="2">政务用户</el-radio>
            <el-radio label="1">企业用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提醒方式" prop="alertManner">
          <el-radio-group v-model="ruleForm.alertManner" disabled>
            <el-radio label="1">定期提醒</el-radio>
            <el-radio label="2">不定期提醒</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="提醒方法" prop="method">
          <el-radio-group v-model="ruleForm.method" disabled>
            <el-radio label="短信提醒">短信提醒</el-radio>
            <el-radio label="邮件提醒">邮件提醒</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="提醒时间" prop="alertTime" v-if="isReminder == 1">
          <el-date-picker
            v-model="ruleForm.alertTime"
            type="datetime"
            placeholder="请选择提醒时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="提醒内容" prop="alertType" required v-else>
          <el-radio-group v-model="ruleForm.alertType" :disabled="isView">
            <el-radio label="2">申报任务即将结束（企业）</el-radio>
            <el-radio label="3">项目即将建设完成（政府）</el-radio>
          </el-radio-group>
          <el-form-item
            prop="reminderDays"
            class="reminder-days-item"
            :rules="[
              { required: true, message: '请输入提醒天数', trigger: 'blur' },
            ]"
          >
            <div style="display: flex; align-items: center">
              <span style="color: #f56c6c; margin-right: 4px">*</span>
              <span>提前</span>
              <el-input
                v-model="ruleForm.daysAdvance"
                type="number"
                :min="1"
                :max="30"
                size="small"
                style="width: 80px; margin: 0 8px"
                :disabled="isView"
              />
              <span>天提醒</span>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="提醒内容" prop="alertContent">
          <el-input
            v-model="ruleForm.alertContent"
            type="textarea"
            :rows="4"
            placeholder="请输入提醒内容"
            :disabled="isView"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button v-if="!isView" type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSmartReminderPage,
  deleteSmartReminder,
  addSmartReminder,
  getSmartReminderDetail,
  updateSmartReminder,
} from "@/api/ManageApi/index";
export default {
  name: "Supervision",
  components: {
    Pagination: () => import("@/components/Pagination"),
  },
  props: {
    projectId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      searchForm: {
        rulesName: "",
        alertType: "",
      },
      tableData: [],
      pagination: {
        total: 0,
        current: 1,
        size: 10,
      },
      selectedRows: [],
      dialogVisible: false,
      ruleForm: {
        rulesName: "",
        alertRecipients: "政务用户",
        alertManner: "1",
        method: "短信提醒",
        alertTime: "",
        alertContent: "",
        alertType: "1",
      },
      dialogTitle: "",
      rules: {
        rulesName: [
          { required: true, message: "请输入提醒规则标题", trigger: "blur" },
        ],
        alertRecipients: [
          { required: true, message: "请选择提醒对象", trigger: "change" },
        ],
        alertManner: [
          { required: true, message: "请选择提醒方式", trigger: "change" },
        ],
        method: [
          { required: true, message: "请选择提醒方法", trigger: "change" },
        ],
        alertTime: [
          { required: true, message: "请选择提醒时间", trigger: "change" },
        ],
        alertContent: [
          { required: true, message: "请输入提醒内容", trigger: "blur" },
        ],
      },
      isView: false,
      editData: {},
      isReminder: 1,
    };
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      const params = {
        current: this.pagination.current,
        size: this.pagination.size,
      };
      getSmartReminderPage(params).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.pagination.total = res.data.total;
        }
      });
    },
    // 处理弹框关闭
    handleClose(done) {
      this.dialogVisible = false;
      this.isView = false;
      this.isReminder = 1; // 重置为默认值
      // 完整重置表单数据
      this.ruleForm = {
        rulesName: "",
        alertRecipients: "2",
        alertManner: "1",
        method: "短信提醒",
        alertTime: "",
        alertContent: "",
        alertType: "1",
        daysAdvance: "",
      };

      // 清除验证
      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
        if (typeof done === "function") {
          done();
        }
      });
    },
    // 搜索方法
    handleSearch() {
      const params = {
        current: this.pagination.current,
        size: this.pagination.size,
        rulesName: this.searchForm.rulesName || "",
        alertType: this.searchForm.alertType || "",
      };

      // 移除空字符串的参数
      Object.keys(params).forEach((key) => {
        if (params[key] === "") {
          delete params[key];
        }
      });

      getSmartReminderPage(params).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.pagination.total = res.data.total;
        }
      });
    },
    // 重置方法
    handleReset() {
      this.searchForm.rulesName = "";
      this.searchForm.alertType = "";
      this.initData();
    },
    // 查看详情
    handleDetail(row) {
      getSmartReminderDetail(row.id).then((res) => {
        if (res.code === 200) {
          this.isReminder = res.data.alertManner;
          this.ruleForm = {
            rulesName: res.data.rulesName,
            alertRecipients: res.data.alertRecipients.toString(),
            alertManner: res.data.alertManner.toString(),
            method: "短信提醒",
            alertTime: res.data.alertTime,
            alertContent: res.data.alertContent,
            alertType: res.data.alertType.toString(),
            daysAdvance: res.data.daysAdvance,
          };

          this.isView = true;
          this.dialogVisible = true;
          this.dialogTitle = "查看流程提醒规则";
          // 清除验证
          this.$nextTick(() => {
            this.$refs.ruleForm.clearValidate();
          });
        }
      });
    },
    // 打开添加规则弹框
    handleAdd() {
      this.isView = false;
      this.dialogVisible = true;
      this.dialogTitle = "新增流程提醒规则";
      this.isReminder = 1; // 明确设置默认值

      // 完整重置表单数据
      this.ruleForm = {
        rulesName: "",
        alertRecipients: "2",
        alertManner: "1",
        method: "短信提醒",
        alertTime: "",
        alertContent: "",
        alertType: "1",
        daysAdvance: "", // 确保这个字段也被重置
      };

      // 清除验证
      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.dialogTitle = "编辑流程提醒规则";
      this.isView = false;

      this.ruleForm = {
        rulesName: "",
        alertRecipients: "2",
        alertManner: "1",
        method: "短信提醒",
        alertTime: "",
        alertContent: "",
        alertType: "1",
      };

      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate();
        }
      });

      getSmartReminderDetail(row.id).then((res) => {
        if (res.code === 200) {
          this.isReminder = res.data.alertManner;
          this.ruleForm = {
            rulesName: res.data.rulesName,
            alertRecipients: res.data.alertRecipients.toString(),
            alertManner: res.data.alertManner.toString(),
            method: "短信提醒",
            alertTime: res.data.alertTime,
            alertContent: res.data.alertContent,
            alertType: res.data.alertType.toString(),
            daysAdvance: res.data.daysAdvance,
          };
          this.editData = res.data;
        }
      });
    },
    // 删除
    handleDelete(row) {
      this.$confirm("确认删除该提醒吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteSmartReminder(row.id).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.initData();
            }
          });
        })
        .catch(() => {});
    },
    // 取消按钮
    cancelAdd() {
      this.dialogVisible = false;
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
        this.ruleForm = {
          rulesName: "",
          alertRecipients: "2",
          mode: "定期提醒",
          method: "短信提醒",
          alertTime: "",
          alertContent: "",
          alertType: "1",
        };
        this.isView = false;
      });
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {};
          if (this.dialogTitle == "新增流程提醒规则") {
            param = {
              rulesName: this.ruleForm.rulesName,
              alertRecipients: Number(this.ruleForm.alertRecipients),
              alertTime: this.ruleForm.alertTime,
              alertContent: this.ruleForm.alertContent,
              alertType: 1,
              projectId: this.xmId,
            };
            addSmartReminder(param).then((res) => {
              if (res.code === 200) {
                this.$message.success("添加成功");
                this.dialogVisible = false;
                this.$refs.ruleForm.resetFields();
                this.initData();
              }
            });
          } else if (this.dialogTitle == "修改流程提醒规则") {
            param = {
              ...this.editData,
            };
            (param.rulesName = this.ruleForm.rulesName),
              (param.alertRecipients = Number(this.ruleForm.alertRecipients)),
              (param.alertTime = this.ruleForm.alertTime),
              (param.alertContent = this.ruleForm.alertContent),
              (param.alertType = 1),
              Reflect.deleteProperty(param, "daysAdvance");
            updateSmartReminder(param).then((res) => {
              if (res.code === 200) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
                this.$refs.ruleForm.resetFields();
                this.initData();
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.supervision-container {
  padding: 8px 0 8px 8px;

  .search-area {
    background-color: #fff;
    padding: 16px 16px 0px 16px;
    margin-bottom: 20px;
    border-radius: 0.5rem;
    border: 1px solid #eee;
  }

  .tablebox {
    background-color: #fff;
    border-radius: 0.5rem;
    padding: 1rem;
    border: 1px solid #eee;

    .operation-area {
      margin-bottom: 20px;
    }
  }

  .el-table {
    .el-button {
      padding: 2px 0;
      margin: 0 5px;

      &.el-button--text {
        color: #409eff;

        &:hover {
          color: #66b1ff;
        }
      }
    }
  }

  .reminder-days-item {
    margin-bottom: 0;

    // 去掉嵌套表单项的label
    :deep(.el-form-item__label) {
      display: none;
    }

    // 去掉嵌套表单项的外边距
    :deep(.el-form-item__content) {
      margin-left: 0 !important;
    }
  }
}

.el-dialog {
  .el-form {
    padding: 0 20px;

    .el-form-item {
      margin-bottom: 20px;

      .el-radio-group {
        .el-radio {
          margin-right: 20px;
          line-height: 32px;
        }
      }

      .el-date-picker {
        width: 100%;
      }

      .el-textarea {
        .el-textarea__inner {
          min-height: 80px;
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding: 10px 20px 20px;

    .el-button {
      padding: 9px 20px;

      & + .el-button {
        margin-left: 10px;
      }
    }
  }
}
</style>
