<template>
  <div class="app-container">
    <div class="card-change">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="" prop="notificationName">
          <el-input
            v-model="queryParams.notificationName"
            placeholder="请输入通知名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" prop="notificationType">
          <el-select v-model="queryParams.notificationType" placeholder="请选择通知类型" clearable style="width: 240px;">
            <el-option label="到期提醒" value="到期提醒"></el-option>
            <el-option label="系统升级" value="系统升级"></el-option>
            <!-- 添加其他选项 -->
          </el-select>
        </el-form-item>
<!--        <el-form-item label="" prop="recipientRoles">-->
<!--          <el-input-->
<!--            v-model="queryParams.recipientRoles"-->
<!--            placeholder="请选择接收角色"-->
<!--            clearable-->
<!--            style="width: 240px;"-->
<!--            @keyup.enter.native="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="" prop="templateStatus">
          <el-select v-model="queryParams.templateStatus" placeholder="请选择通知状态" clearable style="width: 240px;">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
            <!-- 添加其他选项 -->
          </el-select>
        </el-form-item>

        <el-form-item style="float: right">
          <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
          <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['system:notify:addTemplate']"
          >新增通知模板</el-button>
        </el-form-item>
      </el-form>
<!--    </el-card>-->
<!--    &lt;!&ndash;    列表信息&ndash;&gt;-->
<!--    <el-card style="margin-top: 20px" >-->
      <div >

      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column align="center" type="index" label="序号"></el-table-column>
        <el-table-column align="center" prop="notificationName" label="通知名称"></el-table-column>
        <el-table-column align="center" prop="notificationType" label="通知类型"></el-table-column>
        <el-table-column align="center" prop="templateContent" label="模板内容"></el-table-column>
        <el-table-column align="center" prop="recipientRolesName" label="接收角色">
        </el-table-column>
        <el-table-column align="center" prop="templateStatus" label="模板状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.templateStatus" @change="clickSwitch(scope.row)" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createName" label="创建人"></el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
        <el-table-column align="center" label="操作"  width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="edit(scope.row)"
              v-hasPermi="['system:notify:editTemplate']"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="del(scope.row)"
              v-hasPermi="['system:notify:deleteTemplate']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </div>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="32%" append-to-body>
      <el-form :model="form" label-width="120px">
        <!-- 通知名称 -->
        <el-form-item label="通知名称" :required="true">
          <el-input v-model="form.notificationName" placeholder="请输入通知名称" style="width: 300px" ></el-input>
        </el-form-item>

        <!-- 通知类型 -->
        <el-form-item label="通知类型" :required="true">
          <el-select v-model="form.notificationType" placeholder="请选择通知类型" style="width: 300px">
            <el-option label="到期提醒" value="到期提醒"></el-option>
            <el-option label="系统升级" value="系统升级"></el-option>
            <!-- 添加其他选项 -->
          </el-select>
        </el-form-item>

        <!-- 通知模板 -->
        <el-form-item label="通知模板" :required="true">
          <el-input type="textarea" v-model="form.templateContent"  :rows="3" placeholder="请输入通知内容" :maxlength="200" show-word-limit style="width: 300px"></el-input>
          <div>
            <span @click = "insertText('{系统到期日期}')">{系统到期日期}</span>
            <span @click = "insertText('{剩余交易流量}')">{剩余交易流量}</span>
            <span @click = "insertText('{系统服务费统计}')">{系统服务费统计}</span>
          </div>

        </el-form-item>

        <!-- 接收角色 -->
        <el-form-item label="接收角色" :required="true">
          <el-select v-model="form.recipientRoles" multiple placeholder="请选择角色" style="width: 300px">
            <el-option v-for="item in dutyList1" :label="item.dutyName" :value="item.dutyId" ></el-option>
          </el-select>
        </el-form-item>

        <!-- 模板状态 -->
        <el-form-item label="模板状态" :required="true">
          <el-switch v-model="form.templateStatus" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>

        <!-- 发送条件 -->
        <el-form-item label="发送条件" style="margin-bottom: 10px"  :required="true">
          <div v-for="(condition, index) in form.conditions" :key="index" class="condition-group" style="margin-bottom: 10px">
            <el-select v-model="condition.field" placeholder="请选择条件" style="width: 150px;margin-right: 10px" @change="changeField(index)">
              <el-option label="系统到期日期" value="系统到期日期"></el-option>
              <el-option label="剩余交易量" value="剩余交易量"></el-option>
              <el-option label="系统服务费统计" value="系统服务费统计"></el-option>
              <!-- 添加其他选项 -->
            </el-select>
<!--            <el-select v-if="condition.field == '系统到期日期'" v-model="condition.operator" placeholder="请选择" style="width: 100px;margin-right: 10px">-->
<!--              <el-option label="当日日期" value="当日日期"></el-option>-->
<!--              <el-option label="大于" value="大于"></el-option>-->
<!--              <el-option label="小于" value="小于"></el-option>-->
<!--              &lt;!&ndash; 添加其他选项 &ndash;&gt;-->
<!--            </el-select>-->
            <el-input v-model="condition.value" placeholder="请输入数值" style="width: 200px;margin-right: 10px">
              <template slot="append">{{ condition.field === '剩余交易量' || condition.field === '系统服务费统计' ? '万元' : '天' }}</template>
            </el-input>
            <el-button @click="removeCondition(index)" type="danger" icon="el-icon-delete" circle></el-button>
          </div>
          <el-button @click="addCondition(index)" type="primary" icon="el-icon-plus">添加条件</el-button>
        </el-form-item>

        <!-- 操作按钮 -->
<!--        <el-form-item>-->

<!--        </el-form-item>-->
      </el-form>
      <div style="display: flex; justify-content: center; align-items: center;margin-top: 30px">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleReset">取消</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>


import {deleteAppApi, getAppListApi, saveAppApi, updateAppApi} from "@/api/sys/app";
import {dutyList, selectyDutyIdsApi} from "@/api/duty/duty";
import {getSysNotifyList, saveSysNotifyApi, updateSysNotifyApi} from "@/api/sys/sysNotify";
import {deleteSysNotifyApi} from "../../../../api/sys/sysNotify";

export default {
  name: "notify-mode",

  data() {
    return {
      tableData: [],
      dutyList1: [],

      form: {
        id: null,
        notificationName: '',
        notificationType: '',
        templateContent: '',
        recipientRoles: [],
        dutyList: [],
        templateStatus: true,
        type: 0,
        conditions: [
        ]
      },
    // { field: '', operator: '', value: '' }

    deviceInfo: {
        id: null,            // 自增id
        notificationName: '',//通知名称，字符长度最多100，不能为空
        notificationType: '',//通知类型
        templateContent: '',//模板内容
        recipientRoles: '', // 接收角色，字符长度最多255，不能为空
        templateStatus: true //模板状态
      },
      dutyNames: {}, // 用于存储每行的 dutyNames
      // 是否显示弹出层
      open: false,
      title:"",
      total:0,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        orgName:'',
        legalRepresentativeContact:'',
        appStatus:'',
      },
    };
  },
  created() {
    this.getList()
  },
  methods: {
    getList(){
      getSysNotifyList(this.queryParams).then(res=>{
        this.tableData = res.data.records;
        this.total = res.data.total
      })
    },
    changeField(index){
      console.log("123",this.form.conditions)
      console.log("123",index)
      let field = this.form.conditions[index].field
      let sum = 0
      this.form.conditions.forEach(res=>{
        if (res.field === field) {
          sum++
        }
      })
      if (sum > 1) {
        this.form.conditions.splice(index, 1)
        this.$message({
          type: 'info',
          message: '条件不允许重复!'
        });
      }
    },

    // submitForm(formName) {
    //   this.$refs[formName].validate(valid => {
    //     if (valid) {
    //       // 表单验证通过，可以提交数据
    //       // 示例：调用 API 提交数据
    //       this.submitDeviceInfo();
    //     } else {
    //       // 表单验证失败，不执行任何操作
    //       return false;
    //     }
    //   });
    // },

    handleSubmit() {
      this.open = false

      // 在这里调用接口提交设备信息数据
      console.log('提交设备信息数据:', this.form);
      if ( this.form.conditions.length === 0 || this.form.conditions[0].field == '') {
        this.form.conditions = ''
        this.$message({
          type: 'info',
          message: '请选择发送条件!'
        });
        return
      } else {
        this.form.conditions = JSON.stringify(this.form.conditions)
      }
      this.form.recipientRoles = JSON.stringify(this.form.recipientRoles)

      if (this.form.id) {
        updateSysNotifyApi(this.form).then(res=>{
          if(res.code === 200) {
            this.getList()
            this.open = false
          }
        })
      }else {
        saveSysNotifyApi(this.form).then(res=>{
          if(res.code === 200) {
            this.getList()
            this.open = false
          }
        })
      }
    },
    handleReset() {
      this.open = false

    },
    handleQuery(){
      this.getList()
    },
    resetQuery(){
      this.queryParams = {
        page: 1,
        pageSize: 10,
        deviceName:'',
      },
      this.getList()
    },
    handleAdd(e) {
      this.clean()
      this.open = true;
      this.getDutyList()

      this.title = "增加通知模板"
    },
    edit(e) {
      this.clean()
      this.open = true;
      this.title = "编辑通知模板"
      this.getDutyList()

      this.form = e
      this.form.conditions = JSON.parse(this.form.conditions)
      if (!this.form.conditions) {
        this.form.conditions = []
      }
      this.form.recipientRoles = JSON.parse(this.form.recipientRoles)
      console.log('提交设备信息数据:', this.deviceInfo);

    },
    del(e) {

      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSysNotifyApi(e.id).then(res=>{
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    insertText(data) {
      this.form.templateContent = this.form.templateContent+data
    },
    addCondition() {
      if (this.form.conditions.length > 2) {
        this.$message({
          type: 'info',
          message: '最多添加3个条件!'
        });
        return
      }else {
        if (!this.form.conditions) {
          this.form.conditions = []
        }
        this.form.conditions.push({ field: '', operator: '', value: '' });
      }
    },
    removeCondition(index) {
      this.form.conditions.splice(index, 1);
    },
    getDutyList(){
      // this.loading = true;
      let queryParams1={
        page: 1,
        pageSize: 10000
      }
      dutyList(queryParams1).then(res => {
        this.dutyList1 = res.data.records;
        // this.total1 = res.data.total;
        // this.loading = false;
      })
    },
    xunhuanbanduan() {
      this.dutyList.forEach(item => {
        this.form.recipientRoles.forEach(res=>{
          if(item.id === this.form.dutyId) {
            this.form.dutyName = item.dutyName
          }
        })

      })
    },


    clickSwitch(data){
      updateSysNotifyApi(data).then(res=>{
        if(res.code === 200) {
          this.$message({
            type: 'info',
            message: '修改成功'
          });
          this.getList()
          this.open = false
        }
      })
    },
    clean() {
      this.deviceInfo= {
        id: null,            // 自增id
        notificationName: '',
        notificationType: '',
        templateContent: '',
        recipientRoles: [],
        dutyList1: [],
        templateStatus: true,
        conditions: [
          { field: '', operator: '', value: '' }
        ]
      },
        this.form= {
        id: null,
          notificationName: '',
          notificationType: '',
          templateContent: '',
          recipientRoles: [],
          dutyList: [],
          templateStatus: true,
          type: 0,
          conditions: [
          { field: '', operator: '', value: '' }
        ]
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.common-dialog >>> .el-upload--picture-card {
  width: 60px;
  height: 50px;
  line-height: 60px;
}
</style>

