<template>
  <div class="create-push">
    <bread-crumb :curmbFirst="curmbFirst"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <div class="header-title"></div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="ruleForm"
      >
        <el-form-item label="推送应用" prop="resource">
          <el-radio-group v-model="ruleForm.appId">
            <el-radio label="yunqueyi">云鹊医app</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="目标人群" prop="people">
          <el-col :span="24">
          <el-radio-group v-model="ruleForm.isAll" @change="handleTargetChoose">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="2">导入推送名单</el-radio>
            <el-radio :label="3">用户筛选</el-radio>
            <div class="user-select" v-if="ruleForm.isAll == 3">
              <div class="select-btn" @click="showUserChooseModal">选择用户名单</div>
              <div class="numbers"><span class="choosed">{{userChooseCount}}</span> | {{allUserCount}}</div>
            </div>
          </el-radio-group>
          </el-col>
          <!-- <el-col :span="14">
          <el-upload
              v-if="ruleForm.isAll == 2"
              class="upload-demo"
              accept=".xlsx"
              :action="actionUrl"
              :headers = "headers"
              v-model="fileName"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :disabled="ruleForm.isAll == 1"
              >
              <el-input class="update-input" placeholder="文件大小不能超过10M" :disabled="true" v-model="fileName" autocomplete="off"></el-input>
              <el-button class="update-item" size="small" type="primary">选择文件</el-button>
              <div slot="tip" class="el-upload__tip" @click="download">模板.xlsx</div>
              <div slot="tip" class="tip-text" >备注：单次任务建议不要超过10w行</div>
          </el-upload>
          </el-col> -->
        </el-form-item>
        <el-form-item label="">
          <el-upload
              v-if="ruleForm.isAll == 2"
              class="upload-demo"
              accept=".xlsx"
              :action="actionUrl"
              :headers = "headers"
              v-model="fileName"
              :http-request="httpRequest"
              :before-upload="beforeUpload"
              :disabled="ruleForm.isAll == 1"
              >
              <el-input class="update-input" placeholder="文件大小不能超过10M" :disabled="true" v-model="fileName" autocomplete="off"></el-input>
              <el-button class="update-item" size="small" type="primary">选择文件</el-button>
              <div slot="tip" class="el-upload__tip" @click="download">模板.xlsx</div>
              <div slot="tip" class="tip-text" >备注：单次任务建议不要超过10w行</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="推送标题" prop="title">
          <el-input v-model="ruleForm.title" maxlength="30" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="推送介绍" prop="content">
          <el-input type="textarea" maxlength="60" :rows="3" v-model="ruleForm.content" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="页面去向" prop="url">
          <el-input type="textarea" :rows="3" v-model="ruleForm.url" maxlength="250" placeholder="H5链接" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="系统通知" prop="noticeFlag">
          <el-radio-group v-model="ruleForm.noticeFlag">
            <el-radio :label="2">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="APP接收窗口" prop="pushType">
          <el-radio-group v-model="ruleForm.pushType">
            <el-radio label="03">活动提醒</el-radio>
            <el-radio label="04">内容提醒</el-radio>
            <el-radio label="02">居民管理</el-radio>
            <el-radio label="01">系统消息</el-radio>
            <el-radio label="05">直播</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交预览</el-button>
        </el-form-item>
      </el-form>
      <el-dialog title="推送预览" :visible.sync="dialogFormVisible">
        <div>
          <span>主题： {{ ruleForm.title }} </span>
           <p style="display: inline-block; float: right;">
            <span style="margin-left: 0px">目标对象：</span>
            <span v-if="ruleForm.isAll == 2" style="color: #449284"> {{ objNum }} </span>
            <span v-if="ruleForm.isAll == 3" style="color: #449284"> {{ userChooseCount }} </span>
            <span v-else>全部</span>
          </p>
        </div>
        
        <hr>
        <el-form :model="ruleForm" class="rule-form">
          <el-form-item label="APP推送：" >
            云鹊医
          </el-form-item>
          <el-form-item label="推送标题：" >
            {{ ruleForm.title }}
          </el-form-item>
          <el-form-item label="推送介绍：" >
            <p style="white-space: pre-line">{{ ruleForm.content }}</p>
          </el-form-item>
          <!-- <p style="white-space: pre-line">{{ ruleForm.content }}</p> -->
          <el-form-item label="页面去向：" >
            {{ ruleForm.url }}
          </el-form-item>
          <el-form-item label="系统通知：" >
            {{ ruleForm.noticeFlag | getNotice }}
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="pushSend()">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="用户筛选" :visible.sync="isUserChooseModalShow" class="user-choose-modal">
        <el-form :inline="true" :model="userChooseForm">
          <el-form-item label="行政区划：">
            <el-select 
              class="select-choose" 
              v-model="finalChooseData.provinceId" placeholder="省"  
              @change="handleProvinceChange(finalChooseData.provinceId)"
              clearable 
            >
              <el-option
                v-for="item in userChooseForm.address.provinceList"
                :key="item.provinceId"
                :label="item.provinceName"
                :value="item.provinceId">
              </el-option>
            </el-select>
            <el-select 
              class="select-choose" 
              v-model="finalChooseData.cityId" placeholder="市" 
              @change="handleCityChange(finalChooseData.cityId)"
              clearable
            >
              <el-option
                v-for="item in userChooseForm.address.cityList"
                :key="item.cityId"
                :label="item.cityName"
                :value="item.cityId">
              </el-option>
            </el-select>
            <el-select 
              class="select-choose" 
              v-model="finalChooseData.countyId" placeholder="区"  
              @change="handleCountyChange"
              clearable
            >
              <el-option
                v-for="item in userChooseForm.address.countyList"
                :key="item.countyId"
                :label="item.countyName"
                :value="item.countyId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="技术职称：" class="block-item">
            <el-select v-model="finalChooseData.doctorTitle" multiple placeholder="不限"  @change="handleDoctorTitleChange">
              <el-option
                v-for="item in userChooseForm.techTitleList"
                :key="item.titleId"
                :label="item.name"
                :value="item.titleId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属机构等级：" class="block-item">
            <el-select v-model="finalChooseData.hospitalLevel" multiple placeholder="不限" @change="handleHospitalLevelChange">
              <el-option
                v-for="item in userChooseForm.hospitalLevelList"
                :key="item.no"
                :label="item.value"
                :value="item.no">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="user-number">
            <p class="title">目标用户 | 用户总量</p>
            <p class="number">
              <el-button v-if="!isSeeUserNumBtnClicked" class="target-num"  type="primary" @click="getCurrentUserCount" size="mini">查看目标数</el-button>
              <template v-else>
                <span class="choosed">{{userChooseCount}}</span> <el-button class="target-num"  type="primary" @click="getCurrentUserCount" size="mini">刷新目标数</el-button>
              </template>
              | {{allUserCount}}
            </p>
          </div>
          <p class="click-refresh-tips" >
            <template v-if="isSeeUserNumBtnClicked">筛选条件变更后，需重新点击"刷新目标数"按钮获取最新数据</template></p>
          <el-button class="user-choose-submit" type="primary" @click="handleChooseSubmit">确认筛选</el-button>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import BreadCrumb from "../../components/breadcrumb.vue";
import { create } from "domain";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../utils/utils";
import * as commonUtil from "../../utils/utils";
import axios from 'axios';
import { getBaseUrl , getExcel } from '@/utils/index';
let vm = null;
export default {
  components: {
    BreadCrumb
  },
  data() {
    return {
      // curmbFirst: "APP推送",
      // curmbSecond: "创建APP推送",
      curmbFirst: "创建APP推送",
      ruleForm: {
        appId: "yunqueyi",
        isAll: 1,
        title: "",
        content: "",
        url: "",
        noticeFlag: 2,
        pushType: '03',
      },
      actionUrl: getBaseUrl('raytheon/excel/upload'),
      fileName: '',
      objNum: 0,
      sendKey: '',
      dialogFormVisible: false,
      headers: {
        sysCode: 12,
        token: localStorage.getItem('storageToken'),
      },
      rules: {
        appId: [
          { required: true, message: "请选择推送应用", trigger: "change" }
        ],
        title: [
          { required: true, message: "请输入推送标题", trigger: "blur" },
          { min: 0, max: 30, message: "长度在 0 到 30 个字符", trigger: "blur" }
        ],
        content: [
          { required: true, message: "请输入推送介绍", trigger: "blur" },
          { min: 0, max: 250, message: "长度在 0 到 250 个字符", trigger: "blur" }
        ]
      },
      isUserChooseModalShow: false,
      userChooseCount: 0,  // 用户筛选的最终num
      allUserCount: 0, // 总num
      userChooseForm: {
        address: {
          provinceList: [],
          cityList: [],
          countyList: [],
        },
        techTitleList: [],
        hospitalLevelList: [],
      },
      finalChooseData: {
        provinceId: '',
        cityId: '',
        countyId: '',
        doctorTitle: [],
        hospitalLevel: [],
      },
      isSeeUserNumBtnClicked: false,
    };
  },
  computed: {
    ...mapGetters(["_token"])
  },
  created() {
    vm = this;
    vm.idType = localStorage.getItem("storageIdType");
    console.log("idType:", vm.idType);
    
  },
  // 挂载到Dom完成时
  mounted: function() {
    // commonUtil.resizeHeight();
  },
  methods: {
    submitForm(formName) {
      if(this.ruleForm.isAll == 3 && this.userChooseCount == 0){
        vm.$message('请先选择用户');
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // vm.pushSend();
          if(vm.ruleForm.isAll == 2) {
            if(vm.fileName == '') {
              vm.$message('请先导入名单');
            } else {
              vm.dialogFormVisible = true;
            }
          } else {
            vm.dialogFormVisible = true;
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    pushSend() {
      let req = {};
      req = this.ruleForm;
      if(req.isAll == 2 || req.isAll == 3) {
        req.key = vm.sendKey;
      }
      req.createdName = localStorage.getItem('user_name');
      // openLoading(vm);
      vm.POST("raytheon/push/send", req).then(res => {
        // closeLoading(vm);
        vm.$message(res.message);
        if(res.code == '000000') {
          vm.ruleForm = {
            appId: "yunqueyi",
            isAll: 1,
            title: "",
            content: "",
            url: "",
            noticeFlag: 2,
            pushType: '03',
          };
        }
      });
      vm.dialogFormVisible = false;
      vm.fileName = '';
      vm.sendKey = '';
    },
    download() {
      let xlsxUrl = getExcel();
      console.log('下载模板'+xlsxUrl);
        setTimeout(() => {
          window.open(xlsxUrl);
      }, 500);
    },
    beforeUpload(file) {
      // console.log(file);
      let self = this;
      const isLt = file.size / 1024 / 1024 < 10;
      if(!isLt) {
        this.$message.error("文件大小不能超过10M");
        return;
      } else {
        vm.fileName = file.name;
      }
    },
    httpRequest (options) {
      // console.log(options,options.file)
      let file = options.file
      let reader = new FileReader()
      if (file) {
          reader.readAsDataURL(file)
      }          
      reader.onload = (e) => {
        let base64Str = e.target.result.split(',')[1]
        // console.log('e的值',e);
        // let base64Str = e.target.result.substr(e.target.result.indexOf("base64,") + 7)
        // vm.POST("raytheon/excel/upload", base64Str).then(res => {
        //   console.log(res);
        // })
        openLoading(vm);
        axios({
            headers: {
              sysCode: 12,
              token: localStorage.getItem('storageToken'),
              'content-type': 'text/html'
            },
            url: getBaseUrl('raytheon/excel/upload'),
            method: 'post',
            data: base64Str,
        }).then(function (response) {
          // console.log(response);
          closeLoading(vm);
          vm.objNum = response.data.data.count;
          vm.sendKey = response.data.data.key;
          console.log('vm.objNum ',vm.objNum);
        })
      }
    },
    handleTargetChoose() {
      if( this.ruleForm.isAll == 3 ){
        // 初始化
        this.isSeeUserNumBtnClicked = false;
        this.userChooseCount = 0;  
        this.allUserCount = 0; 
        this.userChooseForm = {
          address: {
            provinceList: [],
            cityList: [],
            countyList: [],
          },
          techTitleList: [],
          hospitalLevelList: [],
        };
        this.finalChooseData = {
          provinceId: '',
          cityId: '',
          countyId: '',
          doctorTitle: [],
          hospitalLevel: [],
        };
        // 获取总数量
        this.getCurrentUserCount({ getAll: true });
      }
    },
    getCurrentUserCount(params) {
      if(!(params && params.getAll)){
        if(this.finalChooseData.provinceId == '' 
          && this.finalChooseData.cityId == '' 
          && this.finalChooseData.countyId == '' 
          && this.finalChooseData.doctorTitle.length == 0 
          && this.finalChooseData.hospitalLevel.length == 0
        ){
          this.isSeeUserNumBtnClicked = true;
          this.userChooseCount = 0;
          return;
        }
      }

      openLoading(vm, 'topIndex');
      let req = this.finalChooseData;
      vm.POST("raytheon/push/screenUserCount", req).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          if(params && params.getAll){
            this.allUserCount = res.data;
          }else{
            this.isSeeUserNumBtnClicked = true;  
            this.userChooseCount = res.data;
          }
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    showUserChooseModal() {
      
      this.isUserChooseModalShow = true;

      this.getProvinceList();
      this.getTechTitleList();
      this.getHospitalLevelList();
    },
    getProvinceList() {
      let req = {};
      openLoading(vm);
      vm.GET("raytheon/constants/region", req).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          this.userChooseForm.address.provinceList = res.data.provinceList;
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    getCityList(params) {
      openLoading(vm);
      vm.GET("raytheon/constants/region", params).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          this.userChooseForm.address.cityList = res.data.cityList;
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    getCountyList(params) {
      openLoading(vm);
      vm.GET("raytheon/constants/region", params).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          this.userChooseForm.address.countyList = res.data.countyList;
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    handleProvinceChange(id) {
      this.finalChooseData.cityId = '';
      this.finalChooseData.countyId = '';
      // 清空省，则移除市、区列表
      if( id == '' ){
          this.userChooseForm.address.cityList = [];
          this.userChooseForm.address.countyList = [];
          return;
      }
      let params = { provinceId: id };
      this.getCityList(params);
      // this.getCurrentUserCount();
    },
    handleCityChange(id) {
      this.finalChooseData.countyId = '';
      // 清空市，则移除区列表
      if( id == '' ){
          this.userChooseForm.address.countyList = [];
          return;
      }
      let params = { cityId: id };
      this.getCountyList(params);
      // this.getCurrentUserCount();
    },
    handleCountyChange() {
      // this.getCurrentUserCount();
    },
    handleDoctorTitleChange() {
      // this.getCurrentUserCount();
    },
    handleHospitalLevelChange() {
      // this.getCurrentUserCount();
    },
    getTechTitleList() {
      openLoading(vm);
      vm.GET("raytheon/constants/doctor/title", {}).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          this.userChooseForm.techTitleList = res.data;
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    getHospitalLevelList() {
      openLoading(vm);
      vm.GET("raytheon/constants/hospital/level", {}).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          this.userChooseForm.hospitalLevelList = res.data;
        }else{
          vm.$message.info(res.message)
        }
      });
    },
    // 确认筛选
    handleChooseSubmit() {
      this.getCurrentUserCount();
      openLoading(vm);
      vm.sendKey = '';
      let req = this.finalChooseData;
      vm.POST("raytheon/push/screenUser", req).then(res => {
        closeLoading(vm);
        if(res.code == '000000'){
          vm.isUserChooseModalShow = false;
          vm.sendKey = res.data;
        }else{
          vm.$message.info(res.message)
        }
      });
    },

  }
};
</script>
<style lang="scss">
.topIndex{
    z-index: 10000 !important;
  }
.create-push {
  .component-content {
    margin-top: 20px;
    padding: 10px;
    background: #fff;
    .header-title {
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .ruleForm {
        width: 70%;
        margin-left: 50px;
    }
    .rule-form {
      margin-top: 20px;
      margin-left: 30px;
      .el-form-item__content {
        font-size: 12px;
      }
    }
    .update-input {
      width: 200px;
    }
    .update-item {
      /* float: left; */
      margin-right: 5px;
    }
    .el-upload__tip {
      // margin-top: -10px;
      // margin-left: 205px;
      margin-top: -40px;
      margin-left: 290px;
      cursor: pointer;
      width: 60px;
      color: #449284;
    }
    .tip-text {
      margin-top: -40px;
      margin-left: 380px;
      width: 260px;
      color: red;
    }
    .el-upload-list {
      display: none;
    }
    .table-empty {
      img {
        width: 100px;
      }
      p {
        margin-top: -50px;
      }
    }
    .user-select{
      display: inline-block;
      height: auto;
      padding: 5px 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      .select-btn{
        display: inline-block;
        font-size: 14px;
        padding: 5px;
        border-radius: 4px;
        background: #449284 !important;
        border: 1px solid #449284 !important;
        color: #FFF;
        cursor: pointer;
      }
      .numbers{
        font-size: 14px;
        margin-left: 10px;
        display: inline-block;
        .choosed{
          color: #449284;
        }
      }
    }
    .user-choose-modal{
      .el-form-item__label{
        width: 120px;
        font-size: 14px;
      }
      .select-choose{
        width: 150px;
      }
      .block-item{
        display: block;
      }
      .user-number{
        margin: 40px auto 0;
        text-align: center;
        width: 70%;
        height:34px;
        line-height: 34px;
        border-radius: 4px;
        border: 1px solid #DCDFE6;
        .title{
          display: inline-block;
        }
        .number{
          display: inline-block;
          margin-left: 50px;
          .target-num{
            padding: 7px;
          }
          .choosed{
            color: #449284;
          }
        }
      }
      .click-refresh-tips{
        text-align: center;
        margin: 5px auto 20px;
        height: 20px;
        color: #e6a23c;
      }
      .user-choose-submit{
        margin: 0 auto;
        display: block;
      }
    }

  }
}
</style>