<template>
  <div>
    <!--新增时间节点-->
    <div v-if="!isStandedTemplate">
      <el-button
        size="small"
        type="primary"
        @click="addNewNode()"
      >新增时间节点
      </el-button>
    </div>

    <div class="add-time-content">
      <div class="time-line-scroll">
        <el-tabs v-model="activeTab" type="card" @tab-remove="deleteTimeNode" :closable="tabClosable()">

          <el-tab-pane
            v-for="(itemTimeForm, index) in setTimeNodeList"
            :key="index"
            :label="showTabLabel(itemTimeForm)"
            :name="index+''"
          >
            <div
              v-show="index == activeTab"
              class="form-div"
            >
              <el-form :ref="itemTimeForm.formRef" :model="itemTimeForm" :rules="timeFormRules" label-suffix=":" label-width="140px" :inline-message="false" size="small">
                <el-form-item label="本次随访时间" required>
                  <div style="display: flex;">
                    <el-form-item prop="timeNo">
                      <el-input
                        style="width:200px;"
                        v-model="itemTimeForm.timeNo"
                        type="text"
                        size="small"
                        placeholder="请输入"
                        :disabled="itemIsDisabled(itemTimeForm)"
                        @blur="timeNoBlur(itemTimeForm)"
                        maxlength="2"
                        clearable />
                    </el-form-item>
                    <el-form-item prop="timeUnit" class="ml20">
                      <el-select style="width:200px;" v-model="itemTimeForm.timeUnit" placeholder="请选择" @change="choseTimeUit" :disabled="itemTimeForm.isDisabled">
                        <el-option
                          v-for="(item,index) in markOptions"
                          :key="index"
                          :label="item.value"
                          :value="item.no">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </el-form-item>
                <el-form-item label="随访方式" prop="type">
                  <el-radio-group v-model="itemTimeForm.type" size="small">
                    <el-radio v-for="(item,index) in followTypeList" :key="index" :label="item.no" :disabled="itemIsDisabled(itemTimeForm)">{{item.value}}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="提醒医生预约居民">
                  <el-select
                    v-if="planId || itemTimeForm.remindDay"
                    v-model="itemTimeForm.remindDay"
                    multiple
                    :multiple-limit=3
                    :disabled="itemIsDisabled(itemTimeForm)"
                    @change="changeRemindDay"
                    placeholder="请选择">
                    <el-option
                      v-for="(item_sub,index) in remindOptions"
                      :key="index"
                      :label="item_sub.value"
                      :value="item_sub.no">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="推送患教">
                  <div style="display: flex">
                    <el-select
                      v-model="itemTimeForm.pushDay"
                      placeholder="选择推送时间"
                      clearable
                      @change="changePushDay"
                      :disabled="itemIsDisabled(itemTimeForm)"
                    >
                      <el-option
                        v-for="(item_sub,index) in pushTimeOptions"
                        :key="index"
                        :label="item_sub.value"
                        :value="item_sub.no">
                      </el-option>
                    </el-select>

                    <el-button  plain class="ml20" @click="goSelectCartoon"  v-if="showChoseComtent(itemTimeForm)">选择健康漫画</el-button>
                    <div class="selected-div ml20" v-if="itemTimeForm.hasSelected">
                      <h5>《{{itemTimeForm.comentMsg.header_name}}》</h5>
                      <el-button type="text" @click="goSelectCartoon" v-if="showRechoseDelete(itemTimeForm)">重选</el-button>
                      <el-button type="text" @click="deleteClick(index)" v-if="showRechoseDelete(itemTimeForm)">删除</el-button>
                    </div>
                  </div>
                </el-form-item>
                <div class="tips-contnt" v-if="itemTimeForm.hasSelected">
                  <p class="yellow-font">当前计划中共{{totalNumber}}位居民（微信：{{wechatPatientNum}}位，短信：{{messagePatientNum}}位），本次定时推送任务在发送当日预计需要{{messagePatientNum}}条短信额度（微信推送不消耗额度，建议您让居民关注云鹊健康微信公众号），务必提前确保短信额度的充足。</p>
                  <p>需要更多额度，请前往「云鹊医App-个人中心-啾啾币中心」兑换短信额度后再进行预约，您也可以联系云鹊医客服购买短信额度，客服电话：400-920-8877</p>
                </div>
                <el-form-item label="随访登记表">
                  <el-select
                    v-if="planId || itemTimeForm.followResourceId"
                    v-model="itemTimeForm.followResourceId"
                    multiple
                    :multiple-limit=3
                    @change="changeFollowId"
                    :disabled="itemIsDisabled(itemTimeForm)"
                    placeholder="请选择">
                    <el-option
                      v-for="(item_sub,index) in formOptions"
                      :key="index"
                      :label="item_sub.name"
                      :value="item_sub.scaleNo">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <select-cartoon
      :isSelectCartoon="isSelectCartoon"
      :activeComentId="activeComentId"
      @closeSelectCartoon="closeSelectCartoon"
      @confirmSelectComent="confirmSelectComent"
    />

  </div>
</template>
<script>
  import _ from 'lodash';
  import SelectCartoon from '@/views/followup/plan-manage/dialog/select-cartoon';
//  import SetTimeForm from '@/views/followup/plan-manage/dialog/set-time-form';
  import {getFormOptions, getPatientNumber, getBasicData} from '@/utils/followup/followapis'

  import { mapState,mapActions } from 'vuex'


  export default {
    components: {
      SelectCartoon,
//      SetTimeForm
    },
    data() {
      const checkDay = (rule, value, callback)=>{
        const num = parseFloat(value);
        if(num < 0 || num > 100){
          return callback(new Error('数字范围0-99'));
        }
        if(!Number.isInteger(num) || String(value).indexOf('.') > 0){
          return callback(new Error('数字必须为整数'));
        }
        callback();
      }
      return {
        setTimeNodeList: [],
        isValied: false,
        timeUnit: '',
        timeUnitStr: '',
        timeFormRules: {
          timeNo: [{ required: true, message: '请添加随访时间', trigger: 'change' },{ validator: checkDay, trigger: 'blur' }],
          timeUnit: [{ required: true, message: '请添加随访时间', trigger: 'change' }],
          type: [{ required: true, message: '请选择随访方式', trigger: 'change' }],
        },
        isSelectCartoon: false,
        activeTab: 0,
        activeComentId: '',
        markOptions: [],
        followTypeList: [],
        remindOptions: [],
        pushTimeOptions: [],
        formOptions: [],
        wechatPatientNum: 0,
        messagePatientNum: 0,
        totalNumber: 0,
        activeResourceId: '',
        errMsg: '',
        timeIsRepeat: false,
      }
    },
    props: {
      resourceId: String,
      standedTimeNodeList: Array,
      patientIdList: Array,
      checkForm: Boolean,
      isStandedTemplate: Boolean,
      planId: String,
    },
    created() {
      this.getConstData();
    },
    mounted(){
      console.log(this.resourceId)
      if(!this.planId){//新建计划
        this.initNewForm();
      }
    },
    watch: {
      // 初始化 固定模板或者修改计划 的时间节点
      standedTimeNodeList(val){
        if(this.isStandedTemplate || this.planId){
          this.activeTab = 0 + '';
          this.setTimeNodeList = val;
          this.$forceUpdate();
        }
      },
      resourceId(val){
        console.log('props=',val)
        console.log('activeResourceId=',this.activeResourceId)
        if(parseFloat(val) >= 0){
          if(val!==this.activeResourceId){
            this.activeTab = 0 + '';
            this.setTimeNodeList = this.standedTimeNodeList;
            this.$forceUpdate();
            if(this.isStandedTemplate){// 系统固定模板

            }else{//自定义模板
              this.initNewForm();
            }

          }
        }
      },
      setTimeNodeList(val){
        this.setTimeNodeList = val;
        if(this.setTimeNodeList.length > 0){
          this.timeUnit = this.setTimeNodeList[0].timeUnit
          // 这里操作时间节点的数据
          this.setTimeNodeList.forEach((item,index)=>{
            if((index > 0 && !this.isStandedTemplate) || this.isStandedTemplate){
              item.isDisabled = true;
              item.timeUnit = this.timeUnit;
            }else{
              item.isDisabled = false;
            }
            if(item.remindList.length > 0){// remindDay 提醒医生预约提前天数
              item.remindDay = []
              item.remindList.forEach((kkk)=>{
                item.remindDay.push(kkk.startDays)
              })
            }
            if(item.pushContentList.length > 0){//pushDay 推送患教提前天数
              let pushData = item.pushContentList[0]
              item.hasSelected = pushData.resourceId ? true : false;
              item.pushDay = pushData.startDays
              item.comentMsg = {
                id: pushData.resourceId,
                header_name: pushData.sendContent
              }
            }
            if(item.followupList.length > 0){ //followResourceId 随访量表
              item.followResourceId = []
              item.followupList.forEach((kkk)=>{
                if(this.isStandedTemplate){
                  this.formOptions  = [
                    {
                      scaleNo: kkk.resourceId,
                      name: kkk.sendContent
                    }
                  ]
                }
                item.followResourceId.push(kkk.resourceId)
              })
            }
            this.setTimeNodeList[index].formRef = 'form' + index;
          });
          this.$forceUpdate();
          this.choseTimeUit(this.setTimeNodeList[0].timeUnit);
          this.activeTab = this.setTimeNodeList.length - 1 + '';
        }

      },
      patientIdList(val){
        // 获取微信和短信用户数量
        if(val.length > 0){
          getPatientNumber({
            patientIdList: val
          }).then(res=>{
            if(res.code=='000000'){
              this.wechatPatientNum = res.data.wechatPatientNum;
              this.messagePatientNum = res.data.messagePatientNum;
              this.totalNumber = this.wechatPatientNum + this.messagePatientNum
            }else{
              this.$message({
                message: '提交失败',
                type: 'error'
              });
            }
          })
        }
      },
      // 保存
      checkForm(val){
        if(val){// 触发了 保存 校验
          this.saveData();
        }
      },
      markOptions(val){
        //设置单位
        val.forEach((ob)=>{
          if(this.timeUnit == ob.no){
            this.timeUnitStr = ob.value
          }
        })
      }
    },
    methods: {
      // 初始化新的表单
      initNewForm(){
        this.setTimeNodeList.push({
          formRef: 'form' + this.setTimeNodeList.length,
          type: '',//随访方式
          timeNo: '',//随访时间
          timeUnit: '',//随访时间单位
          remindList: [],//提醒医生预约提前天数
          pushContentList: [],//推送患教提前天数 漫画id
          followupList: [],//随访量表id
          hasSelected: false,
          isDisabled: false,
          remindDay: [],
          pushDay: '',
          followResourceId: [],
          comentMsg: {},
          totalNumber: 0,
          wechatPatientNum: 0,
          messagePatientNum: 0,
          change: true
        });
      },
      // 一次性获取常量接口数据
      getConstData(){
        // 随访时间节点单位
        getBasicData({numList: 'P017'}).then(res=>{
          this.markOptions = res.data.P017
        })
        // 随访方式
        getBasicData({numList: 'P212'}).then(res=>{
          this.followTypeList = res.data.P212
        })
        // 提醒医生天数
        getBasicData({numList: 'P213'}).then(res=>{
          this.remindOptions = res.data.P213
        })
        // 推送患教提醒天数
        getBasicData({numList: 'P214'}).then(res=>{
          this.pushTimeOptions = res.data.P214
        })
        // 获取量表
        getFormOptions().then(res=>{
          this.formOptions = res.data
        })
      },
      // 保存按钮
      saveData(){
        if(this.isStandedTemplate){//固定模板
          // 固定模板，无法修改
          this.$emit('addListenSave',{
            status: true,
            setTimeNodeList: this.setTimeNodeList
          })
        }else{
          if(!this.checkHasChoseComent('save')){
            return;
          }
          // 如果直接点击保存，需要进行对当前填写的表单进行校验
          this.checkStart();
          if(this.isValied){
            // 保存 校验通过后，排序 + 发送请求
            // 新增成功之后
            this.setTimeNodeList = this.sortKey(this.setTimeNodeList,'timeNo',this.setTimeNodeList[this.activeTab].timeNo);
            this.$emit('addListenSave',{
              status: true,
              setTimeNodeList: this.setTimeNodeList
            })
          }else{
            this.$message({
              message: this.errMsg,
              type: 'error'
            });
            this.$emit('addListenSave',{
              status: false,
              setTimeNodeList: this.setTimeNodeList,
              message: this.errMsg
            })
          }
        }
      },
      // 新增时间节点
      addNewNode() {
        if(!this.checkHasChoseComent()){
          return;
        }
        //开始校验
        this.checkStart();
        if(this.isValied){
          // 校验通过后，切换tab并且增加初始化list一个item
          let newTabName = ++this.activeTab + '';
          this.initNewForm();
          this.activeTab = newTabName;
          // 新增成功之后
          this.setTimeNodeList = this.sortKey(this.setTimeNodeList,'timeNo',this.setTimeNodeList[this.activeTab].timeNo);
        }else{
          this.$message({
            message: this.errMsg,
            type: 'error'
          });
        }
      },
      // 删除时间节点
      deleteTimeNode(index) {
        let listLen = this.setTimeNodeList.length;
        if(listLen<=1){
          this.errMsg = '至少选择一个时间节点';
          this.$message({
            message: this.errMsg,
            type: 'error'
          });
          return;
        }else{
          this.$confirm('是否删除该时间节点?', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.setTimeNodeList.splice(parseFloat(index), 1);
            this.activeTab = this.setTimeNodeList.length -1 + '';
            this.$forceUpdate();
          })
        }
      },
      // 校验漫画是否选择
      checkHasChoseComent(type){
        let pushData = this.setTimeNodeList[this.activeTab].pushContentList;
        const len = pushData.length;
        const startDays = len ? pushData[0].startDays : null;
        const resourceId = len ? pushData[0].resourceId : null;
        console.log(pushData)
        // 如果选了推送时间，没选漫画
        if(len && (startDays!==''&&startDays >= 0) && !resourceId){
          this.errMsg = '请选择推送的患教漫画';
          this.$message({
            message: this.errMsg,
            type: 'error'
          });
          if(type=='save'){
            this.$emit('addListenSave',{
              status: false,
              setTimeNodeList: this.setTimeNodeList,
              message: this.errMsg
            })
          }
          return false;
        }else if(len && startDays === '' && resourceId){
          //如果选了漫画，没选推送时间
          this.errMsg = '请选择推送时间';
          this.$message({
            message: this.errMsg,
            type: 'error'
          });
          if(type=='save'){
            this.$emit('addListenSave',{
              status: false,
              setTimeNodeList: this.setTimeNodeList,
              message: this.errMsg
            })
          }
          return false;
        }else{
          return true;
        }
      },
      // 校验开始
      checkStart(){
        // 如果选择了患教推送时间，则必须选择漫画，否则过不了校验
        let len = this.setTimeNodeList.length;
        for(let i=0;i<len;i++){
          let isValied = this.valiedForm(this.setTimeNodeList[i].formRef);
          if(!isValied){
            this.activeTab = i + '';
            this.isValied = false;
            this.errMsg = '请填写完整表单';
            return;
          }else{
            this.isValied = true
            this.timeIsRepeat = false;
          }
        }
        let timeNo = this.setTimeNodeList[this.activeTab].timeNo;
        this.checkIsRepeat(timeNo);
      },
      // 检查是否重复
      checkIsRepeat(val){
        for(let i=0;i<this.setTimeNodeList.length;i++){
          if(this.activeTab!=i && val==this.setTimeNodeList[i].timeNo){
            this.isValied = false;
            this.errMsg = '时间节点重复';
            this.timeIsRepeat = true;
            this.$message({
              message: this.errMsg,
              type: 'error'
            });
            this.setTimeNodeList[this.activeTab].timeNo = '';
            return;
          }
          this.isValied = true;
          this.errMsg = '';
          this.timeIsRepeat = false;
        }
      },
      // 表单验证
      valiedForm(form){
        let validback;
        if(this.$refs[form].validate){
          this.$refs[form].validate((valid) => {
            validback = valid
          });
        }else{
          this.$refs[form][0].validate((valid) => {
            validback = valid
          });
        }
        return validback
      },
      // 时间失去焦点
      timeNoBlur(itemTimeForm){
        setTimeout(()=>{
          // 这里设置定时器是因为，如果填完时间，直接点击随访方式radio，会立即出发排序和重复事件
          this.checkIsRepeat(itemTimeForm.timeNo);
//          // 新增成功之后
//          this.setTimeNodeList = this.sortKey(this.setTimeNodeList,'timeNo');
        },300)
      },
      // 是否禁用按钮
      itemIsDisabled(item){
        let flag;
        if(this.isStandedTemplate){
          flag = true;
        }else{
          if(item.change){
            flag = false;
          }else{
            flag = true;
          }
        }
        return flag;
      },
      // 是否可以删除时间节点
      tabClosable(){
        let flag;
        if(this.isStandedTemplate){//固定模板，不可关闭
          flag = false;
        }else{
          this.setTimeNodeList.forEach((item)=>{
            if(item.change){
              flag = true;
            }else{
              flag = false;
            }
          })
        }
        return flag;
      },
      // 是否显示选择添加漫画按钮
      showChoseComtent(timeObj){
        let flag;
        if(this.isStandedTemplate){
          flag = false
        }else{
          if(this.planId && !timeObj.change){
            flag = false;
          }else{
            if(timeObj.comentMsg && timeObj.comentMsg.id){
              flag = false;
            }else{
              flag = true;
            }
          }
        }
        return flag
      },
      // 是否显示删除重选漫画按钮
      showRechoseDelete(timeObj){
        let flag;
        if(this.isStandedTemplate){
          flag = false
        }else{
          if(this.planId && timeObj.change && timeObj.comentMsg.id){
            flag = true
          }else{
            if(timeObj.comentMsg.id){
              flag = true
            }else{
              flag = false
            }
          }
        }
        return flag
      },
      goSelectCartoon() {
        this.isSelectCartoon = true;
      },
      //关闭漫画
      closeSelectCartoon() {
        this.isSelectCartoon = false;
      },
      // 确认选择漫画
      confirmSelectComent(val){
        this.isSelectCartoon = false;
        console.log('当前的漫画选择组件的信息',val)
        console.log('当前的tab是',this.activeTab)
        console.log('当前是否固定模板',this.isStandedTemplate)
        console.log('当前的时间list',this.setTimeNodeList)
        this.activeComentId = String(val.id);
        this.setTimeNodeList[this.activeTab].hasSelected = true;
        this.setTimeNodeList[this.activeTab].comentMsg = val;
        const comdata = this.setTimeNodeList[this.activeTab];
        const obj = {
          startDays: comdata.pushDay,
          resourceId: comdata.comentMsg.id,
          sendContent: comdata.comentMsg.header_name
        }
        this.setTimeNodeList[this.activeTab].pushContentList[0] = obj

      },
      deleteClick(index) {
        this.setTimeNodeList[index].hasSelected = false;
        this.setTimeNodeList[index].comentMsg = {};
//        this.setTimeNodeList[index].pushContentList.splice(0,1);
        this.setTimeNodeList[index].pushContentList[0].resourceId = null
        this.setTimeNodeList[index].pushContentList[0].sendContent = null
        this.activeComentId = '';
        this.$forceUpdate();
      },
      // 选择提醒医生预约天数
      changeRemindDay(val){
        this.setTimeNodeList[this.activeTab].remindList = []
        val.forEach((item)=>{
          this.setTimeNodeList[this.activeTab].remindList.push({
            startDays: item
          })
        })
        this.$forceUpdate();
      },
      // 选择推送患教提前天数
      changePushDay(val){
        let obj = {
          startDays: val,
          resourceId: this.setTimeNodeList[this.activeTab].comentMsg.id,
          sendContent: this.setTimeNodeList[this.activeTab].comentMsg.header_name
        }
        this.setTimeNodeList[this.activeTab].pushContentList[0] = obj
        this.$forceUpdate();
      },
      // 选择随访量表
      changeFollowId(val){
        this.setTimeNodeList[this.activeTab].followupList = []
        val.forEach((item)=>{
          this.formOptions.forEach((item2)=>{
            if(item2.scaleNo==item){
              this.setTimeNodeList[this.activeTab].followupList.push({
                resourceId: item,
                sendContent: item2.name
              })
            }
          })
        })
        this.$forceUpdate();
      },
      // 对时间节点进行排序
      sortKey(array,key,timeNo) {
        let newList = array.sort((a,b)=>{
          const x = parseFloat(a[key]);
          const y = parseFloat(b[key]);
          return ((x<y) ? -1 : (x>y) ? 1 : 0)
        })
        array.forEach((item,index)=>{
          if(timeNo == item.timeNo){
            this.activeTab = index;
          }
        })
        return newList
      },
      //新建计划，根据第一个时间节点选择单位
      choseTimeUit(val){
        //设置单位
        this.markOptions.forEach((ob)=>{
          if(val == ob.no){
            this.timeUnitStr = ob.value
          }
        })
      },
      // 显示tab文字
      showTabLabel(item){
        let str;
//        if(this.isStandedTemplate || this.planId){
//          if(item.timeNo){
//            str = '开始后' + String(item.timeNo) + this.timeUnitStr
//          }else{
//            str = '设置时间节点'
//          }
//        }else{
//
//        }
        if(item.timeNo){
          str = '开始后' + String(item.timeNo) + this.timeUnitStr
        }else{
          str = '设置时间节点'
        }
        return str
      },
    },
  }
</script>
<style scoped lang="scss">
  .add-time-content{
    padding-top: 20px;
    .deletelist{
      position: absolute;
      right: -3px;
      top: -3px;
    }
    .time-line-scroll{
      width: 100%;
      /*height: 60px;*/
      box-sizing: border-box;
      /*background-color: #F0F2F5;*/
      padding: 10px;
      overflow-x: scroll;
      overflow-y: hidden;
      white-space: nowrap;
      position: relative;
      cursor: pointer;
      &::-webkit-scrollbar{
        height: 6px;
      }
      &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: rgba(0,0,0,0.1);
      }
      span{
        display: inline-block;
        background-color: #449284;
        border-radius: 20px;
        height: 28px;
        line-height: 28px;
        padding: 0 8px;
        color: #ffffff;
        font-size: 12px;
        width: 95px;
      }
      .blur-btn{
        background-color: #fff!important;
        color: #606266;
        border: 1px solid #DCDFE6!important;
      }
    }
    .form-div{
      padding-top: 30px;
      .tips-contnt{
        margin-top: -10px;
        padding-left: 140px;
        padding-bottom: 30px;
        font-size: 12px;
        color: #9B9997;
        width: 55%;
        p{
          line-height: 18px;
          &.yellow-font{
            color: #e6a23c;
            padding-bottom: 10px;
          }
        }
      }
    }
  }
  .ml20{
    margin-left: 20px;
  }
</style>
