<template>
  <div class="strategy-manage-wrap">
    <bread-crumb :curmbFirst="curmbFirst"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <!-- 顶部输入框 -->
      <div>
         <el-form label-width="80px" style="overflow: hidden;">
          <el-form-item label="策略名称" style="width: 300px; float: left;">
            <el-input v-model="stratetyRequest.name" placeholder="请输入名称" ></el-input>
          </el-form-item>
          <el-button type="primary" style="margin-left: 50px;" @click="handleSearchClick">搜索</el-button>
        </el-form>
      </div>
      <!-- 策略列表 -->
      <div class="table-wrap">
        <el-button type="primary" style="float: right;" @click="handleCreateStrategy">创建策略</el-button>
        <el-table
          :data="tableData"
          border
          style="width: 100%; margin-top: 70px;">
          <el-table-column
            align="center"
            prop="name"
            label="策略名称"
            >
          </el-table-column>
          <el-table-column
            align="center"
            prop="code"
            label="策略编码"
            >
            <template slot-scope="scope">
              <span :id="returnCopyClass(scope.$index)">{{scope.row.code}}</span>
              <span style="color: #409EFF; cursor:pointer;" @click="copyCode(scope.row.code, scope.$index)">复制</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="APP系统推送">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="editTemplate(scope)"
                type="text">
                {{ scope && scope.row && scope.row.templateCode ? '编辑模板' : '新建模板' }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="修改时间"
            >
            <template slot-scope="scope">
              {{ returnModifyTime(scope.row.modifyTime) }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="modifyName"
            label="操作人"
           >
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            >
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="editRow(scope.$index, tableData)"
                type="text">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="stratetyRequest.pageNo"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="stratetyRequest.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows">
        </el-pagination>
      </div>
      </div>
      
      <!-- 创建/编辑策略 弹窗 -->
      <el-dialog
        :visible.sync="stragetyDialogVisible"
        width="700px"
        :close-on-click-modal="false"
        @close="handleCancelCreateOrEdit"
        center>
        <el-form :model="createOrEditRequest" :rules="rules" ref="createOrEditRequest" label-width="100px" class="demo-ruleForm">
          <el-form-item label="策略名称" prop="name" style="width: 600px;">
            <el-input
              type="text"
              placeholder="请输入"
              v-model="createOrEditRequest.name"
              maxlength="30"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancelCreateOrEdit">取 消</el-button>
          <el-button type="primary" @click="handleConfirmCreateOrEdit('createOrEditRequest')">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 新增/编辑模板 弹窗 -->
      <el-dialog
        class="template-modal-wrap"
        title="APP推送"
        :visible.sync="templateDialogVisible"
        :close-on-click-modal="false"
        width="800px"
        @close="handleCloseTemplateModal"
        center>
        <el-form :model="templateRuleForm" :rules="templateRules" ref="templateRuleForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="APP" prop="channel" class="app-channel-item">
            <el-radio-group v-model="templateRuleForm.channel">
              <el-radio label="4">云鹊医</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="APP接收窗口" prop="parentPushType">
            <el-radio-group v-model="templateRuleForm.parentPushType">
              <el-radio label="01">系统消息</el-radio>
              <el-radio label="02">居民管理</el-radio>
              <el-radio label="03">活动提醒</el-radio>
              <el-radio label="04">内容提醒</el-radio>
              <el-radio label="05">直播</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="系统通知" prop="noticeFlag">
            <el-radio-group v-model="templateRuleForm.noticeFlag">
              <el-radio :label="2">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- pushtype 4位数字，需写校验***************************************************************************** -->
          <el-form-item label="PushType" prop="pushType" style="width: 650px;">
            <el-input
              type="text"
              placeholder="请输入"
              v-model="templateRuleForm.pushType"
              maxlength="4"
              show-word-limit
            >
            </el-input>
            <p style="position: absolute; right:-70px; top: 0; color: #449284; cursor: pointer;" @click="showPushTypeRule(true)">填写规则</p>
          </el-form-item>
          <el-form-item label="标题" prop="title" style="width: 650px;">
            <el-input
              type="text"
              placeholder="请输入"
              v-model="templateRuleForm.title"
              maxlength="30"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="摘要" style="width: 650px;">
            <el-input
              type="textarea"
              placeholder="请输入"
              v-model="templateRuleForm.summary"
              maxlength="60"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item  label="内容" prop="content" style="width: 650px;">
            <el-input
              type="textarea"
              placeholder="请输入"
              v-model="templateRuleForm.content"
              maxlength="60"
              show-word-limit
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div class="bottom-tips">变量占位符用%s标识<span>示例：您的管理者权限，已从【%s】更改至【%s】</span></div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseTemplateModal">关闭</el-button>
          <el-button type="primary" @click="submitForm('templateRuleForm')">确 认</el-button>
        </span>
      </el-dialog>

      <!-- 填写规则 弹窗 -->
      <el-dialog
        class="input-rule-wrap"
        title="填写规则"
        :visible.sync="inputRuleTableVisible"
        :close-on-click-modal="false"
        width="800px"
        center>
        <el-table
          :data="inputRuleTableData"
          border
          style="width: 100%; margin-top: 70px;">
          <el-table-column
            align="center"
            label="系统提醒"
            >
            <template slot-scope="scope">
              <span :class="isCurrentExist(scope.row.activityTips, existPushTypeList) ? 'active' : 'not-active'">
                {{ scope.row.activityTips }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="居民管理提醒"
            >
            <template slot-scope="scope">
              <span :class="isCurrentExist(scope.row.contentTips, existPushTypeList) ? 'active' : 'not-active'">
                {{ scope.row.contentTips }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="活动提醒"
          >
            <template slot-scope="scope">
              <span :class="isCurrentExist(scope.row.patientsManager, existPushTypeList) ? 'active' : 'not-active'">
                {{ scope.row.patientsManager }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="内容提醒"
          >
            <template slot-scope="scope">
              <span :class="isCurrentExist(scope.row.systemInfo, existPushTypeList) ? 'active' : 'not-active'">
                {{ scope.row.systemInfo }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="直播提醒"
          >
            <template slot-scope="scope">
              <span :class="isCurrentExist(scope.row.liveVideo, existPushTypeList) ? 'active' : 'not-active'">
                {{ scope.row.liveVideo }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <p class="input-bottom-tips">
            说明：01、02、03、04、05开头的编码分别表示消息落地的接收窗为：系统提醒、居民管理提醒、活动提醒、内容提醒、直播提醒，高亮的编码表示已经被使用的编码，黑色表示可以使用的编码
          </p>
          <!-- <el-button @click="inputRuleTableVisible = false">关闭</el-button>
          <el-button type="primary">确 认</el-button> -->
          <div style="width:100%; height: 40px;"></div>
        </span>
        
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { openLoading, closeLoading } from "../../utils/utils";
  let vm = null;

  import BreadCrumb from "../../components/breadcrumb.vue";
  export default {
    components: {
      BreadCrumb,
    },
    data() {
      var checkPushType = (rule, value, callback) => {
        // debugger;
        if (!value) {
          return callback(new Error('PushType不能为空'));
        }else{
          if(value.length != 4){ // 必须长度为4
            callback(new Error('必须是以 01/02/03/04/05 开头的四位纯数字'));
          }else{
            let arr = value.split('');
            let beginReg = /[1-5]/g
            if( arr[0] != '0' || !beginReg.test( parseInt(arr[1]) ) ){  // 判断是以01-05开头
              callback(new Error('必须是以 01/02/03/04/05 开头的四位纯数字'));
            }
            for(let i=0; i<arr.length; i++){  // 必须四位都是纯数字
              let reg = /\d/g;
              if( !reg.test( parseInt(arr[i]) ) ){
                callback(new Error('必须是以 01/02/03/04/05 开头的四位纯数字'));
              }
            }
            callback();
          }
        }
      };
      return {
        curmbFirst: "策略管理",
        tableData: [],
        stragetyDialogVisible: false,
        // 创建/编辑 策略 请求参数
        createOrEditRequest: {
          name: '',
        },
        rules: {
          name: [
            { required: true, message: '请输入策略名称', trigger: 'blur' },
          ],
        },
        // 模板弹窗
        templateDialogVisible: false,
        initTemplateRuleForm: {
          channel: '4',
          parentPushType: '',
          noticeFlag: '',
          pushType: '',
          title:'',
          summary: '',
          content: '',
          strategyId: null,  //策略id
          id: null,  // 模板id
        },
        templateRuleForm: {
          channel: '4',
          parentPushType: '',
          noticeFlag: '',
          pushType: '',
          title:'',
          summary: '',
          content: '',
          strategyId: null,  //策略id
          id: null,  // 模板id
        },
        // 分页
        totalRows: 0,

        templateRules: {
          channel: [
            { required: true, message: '请选择APP', trigger: 'blur' },
          ],
          parentPushType: [
            { required: true, message: '请选择APP接收窗口', trigger: 'blur' },
          ],
          noticeFlag: [
            { required: true, message: '请选择系统通知', trigger: 'blur' },
          ],
          pushType: [
            { required: true, message: '请输入PushType值' },    
            { validator: checkPushType}
          ],
          title: [
            { required: true, message: '请填写标题', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '请填写内容', trigger: 'blur' },
          ],
        },
        stratetyRequest: {   // 策略列表 请求参数
          pageNo: 1,
          pageSize: 10,
          name: '',
        },
        isCreate: true,
        rowData: {},
        inputRuleTableVisible: false,   // 填写规则 弹窗
        inputRuleTableData: [
          // {  //demo
          //   activityTips: 0100,
          //   contentTips: 0200,
          //   patientsManager: 0300,
          //   systemInfo: 0400,
          //   liveVideo: 0500,
          // },
        ],
        existPushTypeList: [],  // 已存在的 pushType list (高亮回显用)
      }
    },
    created() {
      vm = this;
      this.getStrategyList();
    },
    methods: {
      returnCopyClass(index) {
        // console.log('>>>>>>>>>index ', index)
        return 'copyCode_' + index;
      },
      returnModifyTime(modifyTime){
        if( modifyTime ){
          return modifyTime.year + '-' + modifyTime.monthValue + '-' + modifyTime.dayOfMonth ;
        }else{
          return '-';
        }
      },
      handleCreateStrategy() {
        this.isCreate = true;
        this.createOrEditRequest.name = '';  // 清空input
        this.stragetyDialogVisible = true;
      },
      handleCancelCreateOrEdit() {
        this.resetForm('createOrEditRequest');
        this.stragetyDialogVisible = false
      },
      handleSizeChange(val){
        this.stratetyRequest.pageSize = val;
        this.getStrategyList();
      },
      handleCurrentChange(val) {
        this.stratetyRequest.pageNo = val;
        this.getStrategyList();
      },
      handleConfirmCreateOrEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let req = {};
            if(this.isCreate == true){  // 创建策略时
              req = {
                bizCode: '',
                channel: '',
                code: '',
                name: this.createOrEditRequest.name,
                sysCode: '',
                templateCode: '',
              };
              this.goToSaveStrategy(req, () => {
                this.getStrategyList()
              });
            }else{  // 编辑时
              req.id = this.rowData.id;
              req.name = this.createOrEditRequest.name;
              this.goToEditStrategy(req, () => {
                this.getStrategyList()
              })
            }
            
            this.stragetyDialogVisible = false;  // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  success 才关闭？？？？？
            // empty input value
          } else {
            console.log('error submit!!');
            return false;
          }
        });

        

      },
      // 创建 策略
      goToSaveStrategy(req, cb) {
        openLoading(this);
        this.POST('raytheon/strategy/save', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              // console.log('>>>>>> 新增 编辑 OK ', req)
              cb && cb();
            }else{
              this.$message({
                message: '接口请求失败',
                type: 'warning'
              });
            }
        })
      },

      goToEditStrategy(req, cb) {
        openLoading(this);
        this.POST('raytheon/strategy/update', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              // console.log('>>>>>> 新增 编辑 OK ', req)
              cb && cb();
            }else{
              this.$message({
                message: '接口请求失败',
                type: 'warning'
              });
            }
        })
      },

      editRow(index, list) {
        this.rowData = {};
        this.isCreate = false;
        this.createOrEditRequest.name = list[index].name;
        this.stragetyDialogVisible = true;
        this.rowData = list[index];
      },
      editTemplate(scope) {
        this.templateRuleForm = JSON.parse(JSON.stringify(this.initTemplateRuleForm));
        this.templateDialogVisible = true;
        // console.log('scope.row >>>> ', scope.row)
        this.templateRuleForm.strategyId = scope.row.id;
        if( scope.row.templateCode ){ // 编辑,请求接口回显
          let req = {
            templateCode: scope.row.templateCode
          };
          this.getTemplateDetail(req);

        }else{ // 新增
          this.templateRuleForm.id = null;
        }  
        // 获取填写规则
        this.getInputRuleData();
      },
      // 搜索
      handleSearchClick() {
        this.stratetyRequest.pageNo = 1; 
        this.getStrategyList();
      },
      // 复制功能
      copyCode(code, index) {
        let elementID = 'copyCode_' + index;
        var text = document.getElementById(elementID);
        // debugger;
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        }else{
          this.$message({
            message: '策略编码 复制失败',
            type: 'warning'
          });
          return;
        }
        document.execCommand('Copy');
        this.$message({
          message: '策略编码 复制成功！',
          type: 'success'
        });
      },
      // 获取 模板详细 回显
      getTemplateDetail(req) {
        openLoading(this);
        this.GET("raytheon/msgTemplateInfo/getByCode", req).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            // console.log('>>>>> g获取模板详细 ', res)
            if(res.data){
              let data = res.data;
              // 回显处理 其他key

              // channel: 4,
              // parentPushType: '',
              // noticeFlag: '',
              // pushType: '',
              // title:'',
              // summary: '',
              // content: '',
              // strategyId: null,  //策略id
              // id: null,  // 模板id
              this.templateRuleForm.channel = data.channel;
              this.templateRuleForm.parentPushType = data.parentPushType;
              this.templateRuleForm.noticeFlag = data.noticeFlag;
              this.templateRuleForm.pushType = data.pushType;
              this.templateRuleForm.title = data.title;
              this.templateRuleForm.summary = data.summary;
              this.templateRuleForm.content = data.content;
              this.templateRuleForm.id = data.id;
            }
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },

      // 获取 策略列表
      getStrategyList() {
        let req = this.stratetyRequest;
        openLoading(this);
        this.GET("raytheon/strategy/list", req).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            // console.log('get 策略列表>>>>> ', res);  
            if (res.data ) {
              this.totalRows = res.data.total;
            }
            if(res.data && res.data.list && res.data.list.length > 0){
              this.tableData = res.data.list;
            }else{
              this.tableData = [];
            }
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },

      showPushTypeRule(status) {
        // 计算出 table 列表
        this.inputRuleTableVisible = true;
        

      },
      getInputRuleData() {
        let tempArr = [];
        for( let i=0; i<100; i++ ) {  // 行 0-99
          let index = i<10 ? '0'+i : i;
          let obj = {
            activityTips: '01' + index,
            contentTips: '02' + index,
            patientsManager: '03' + index,
            systemInfo: '04' + index,
            liveVideo: '05' + index,
          };
           tempArr.push(obj);
        }
        this.inputRuleTableData = tempArr;
        // 请求已存在的 pushType list
        this.getExistPushTypeList()
      },
      // 获取 策略列表
      getExistPushTypeList(req) {
        req = req || {};
        openLoading(this);
        this.GET("raytheon/msgTemplateInfo/pushTypelist", req).then(res => {
          closeLoading(this);
          if(res && res.code && res.code == '000000'){
            if(res.data && res.data.length > 0){
              this.existPushTypeList = res.data;
            }
          }else{
            this.$message({
              message: '接口请求失败',
              type: 'warning'
            });
          }
        });
      },

      // 是否存在
      isCurrentExist(item, arr) {
        let has = false;
        if(arr && arr.length>0){
          for(let i=0; i<arr.length; i++){
            if(arr[i].pushType == item){
              return true;
            }
          }
          return false;
        }else{
          return false;
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let req = this.templateRuleForm;
            this.goToSaveTemplate(req, () => {
              // 恢复 模板默认传参 && 关闭弹窗
              this.templateRuleForm = JSON.parse(JSON.stringify(this.initTemplateRuleForm));
              this.templateDialogVisible = false;

              this.getStrategyList()
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      // 模板 保存
      goToSaveTemplate(req, cb) {
        openLoading(this);
        this.POST('raytheon/msgTemplateInfo/save', req).then((res) => {
            closeLoading(this);
            if( res && res.code && res.code == '000000') {
              cb && cb();
            }else{
              this.$message({
                message: res.message || '接口请求失败',
                type: 'warning'
              });
            }
        })
      },

      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleCloseTemplateModal() {
        this.resetForm('templateRuleForm');
        this.templateDialogVisible = false;


      }
      
    }
  }
</script>  
<style lang="scss">
  .strategy-manage-wrap{
    .pagination{
      margin: 20px 0;
      text-align: right;
    }
    .el-form-item .el-form-item__label{
      font-size: 14px;
    }
    .component-content{
      margin-top: 60px;
      padding: 10px;
      background: #fff;
    }
    .table-wrap{
      padding: 0 80px; overflow: hidden;
    }
    .template-modal-wrap{
      .el-dialog--center{
        margin-top: 3vh !important;
      }
      .el-dialog__header{
        text-align: left;
      }
      .el-dialog__body{
        padding-top: 0;
        padding-bottom: 15px;
        .app-channel-item{
          margin-bottom: 0;
        }
        .el-textarea__inner{
          padding: 5px 42px 5px 15px;
        }
      }
    }
    .bottom-tips{
      text-indent: 120px;
      margin-top: 28px;
      span{
        color: #449284;
        margin-left: 20px;
      }
    }
    .input-rule-wrap{
      .el-dialog--center{
        margin-top: 3vh !important;
      }
      .el-dialog__body{
        height: 400px;
        overflow: hidden;
        overflow-y: scroll;
        padding-bottom: 0;
        .el-table{
          margin-top: 0 !important;
          .el-table__row{
            .active{
              color: #409EFF;
            }
            .not-active{
              color: #606266;
            }
          }
        }
      }
      .el-dialog__footer{
        .input-bottom-tips{
          color: red;
          text-align: left;
          margin: 12px 0;
        }
      }
    }
  }
</style>