<template>
  <div class="resident-list">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
      :curmbThird="curmbThird"
      :jumPathThird="jumPathThird">
    </bread-crumb>
    <div class="new-plan-content f-main-content screenSet">
      <div class="header">
        <div class="title">
          <span :class="{ 'active-class' : activeTab === 'second' }">①基本信息</span>
          <i class="el-icon-arrow-right" style="color: #C0C4CC"></i>
          <span :class="{ 'active-class' : activeTab === 'first' }">②履约时间节点</span>
        </div>
        <div class="plan-btns-group" v-if="activeTab === 'first'">
          <el-button class="button-white" size="small" plain @click="cancelEdit" >取 消</el-button>
          <el-button type="primary" size="small" @click="nextClick('baseInfo')">下一步</el-button>
        </div>
        <div class="plan-btns-group" v-if="activeTab === 'second'">
          <el-button class="button-white" size="small" plain @click="preClick">上一步</el-button>
          <el-button type="primary" size="small" @click="saveEdit">保 存</el-button>
        </div>
      </div>

      <div class="edit-plan-content" v-if="activeTab === 'first'">
        <el-form ref="baseInfo" :model="baseInfo" :rules="rules" label-suffix=":" label-width="140px" :inline-message="true" size="small">
          <el-form-item label="履约计划名称" prop="name">
            <el-input v-model="baseInfo.name" maxlength="20" style="width: 30%" clearable></el-input>
          </el-form-item>
          <el-form-item label="履约居民" required prop="hasSelectedNum">
            <div style="display: flex">
              <div>
                <el-button plain icon="el-icon-plus" :style="noChoice?'border:1px solid red;':''" @click="selectPatientHandler">{{baseInfo.hasSelectedNum ? '继续添加' : '选择居民'}}</el-button><br>
                <el-button type="text" class="mt10" @click="seeSelectedHandler" v-if="baseInfo.hasSelectedNum">已选{{baseInfo.hasSelectedNum}}人<i class="el-icon-arrow-right"></i></el-button>
              </div>
              <p class="err-tips" v-if="noChoice">请添加履约居民</p>
            </div>
          </el-form-item>
          <el-form-item label="履约模板" prop="resourceId">
            <el-select
              v-model="baseInfo.resourceId"
              placeholder="请选择履约模板"
              clearable>
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <p class="tips">履约计划创建成功后，模板不可更换，请谨慎选择。</p>
          <el-form-item label="履约开始时间" prop="time">
            <el-date-picker
              v-model="baseInfo.time"
              type="date"
              ref="beginDate"
              placeholder="请选择履约开始时间"
              :picker-options="pickerOptions"
              value-format="timestamp"
              clearable
              @blur="handleDateInputConfirm"
              style="width:380px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-select
              v-model="baseInfo.remarksStatus"
              placeholder="请选择履约种类"
              clearable>
              <el-option
                v-for="item in remarkOption"
                :key="item.no"
                :label="item.value"
                :value="item.no">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div class="edit-plan-content" v-show="activeTab === 'second'">
        <set-time-node
          :resourceId="resourceId"
          :standedTimeNodeList="standedTimeNodeList"
          :isStandedTemplate="isStandedTemplate"
          :patientIdList="baseInfo.patientIdList"
          :checkForm="checkForm"
          @addListenSave="addListenSave"
        />
      </div>
    </div>

    <select-patient
      :isShowSelectPatient="isShowSelectPatient"
      :selectPatientDialogTitle="baseInfo.hasSelectedNum ? '继续添加' : '选择居民'"
      :patientIdList="baseInfo.patientIdList"
      @closeSelectPatient="closeSelectPatient"
      @sureSelectPatient="sureSelectPatient(arguments)"
      :selectPatientType="selectPatientType"
    />
    <has-selected-patient
      v-if="isShowSelectedDialog"
      :hasSelectedList="hasSelectedList"
      @closeSelectedDialog="closeSelectedDialog"
      @continueAdd="continueAdd"
    />
    <!-- 敏感词及协议校验 -->
    <el-dialog class="prot-dialog" title="" :visible.sync="isShowProtocolDialog" width="30%" center :show-close=false>
      <p class="prot-dialog-tips-1">由于该居民尚未同意《云鹊平台隐私协议》，将导致履约量表部分信息无法录入，为了方便您的工作开展，请您发送短信提醒居民完成授权</p>
      <p v-show="!isSentedProt" class="prot-dialog-tips-2">若您选择暂不发送，您只能录入量表的非敏感信息</p>
      <p v-show="isSentedProt" class="prot-dialog-tips-3">为避免打扰居民，7天内只能发送1次，您已发送过短信，请尽快联系居民同意授权</p>
      <span v-show="!isSentedProt" slot="footer" class="dialog-footer">
        <el-button size="small" @click="isShowProtocolDialog = false"> 暂不发送 </el-button>
        <el-button size="small" type="primary" @click="sendMsgToPatients"> 发送短信 </el-button>
      </span>
      <span v-show="isSentedProt" slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="isShowProtocolDialog = false"> 我知道了 </el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import BreadCrumb from '@/components/breadcrumb'
  // import SelectPatient from '@/views/followup/plan-manage/dialog/select-patient';
  import SelectPatient from '@/views/patients/labels-manage/dialog/select-patitents';
  import HasSelectedPatient from '@/views/followup/plan-manage/dialog/has-selected-patient';
  import SetTimeNode from '@/views/followup/plan-manage/dialog/set-time-node';
  import { createFollowPlan, getFollowupTableTemplate, uniteValidate, authMessage } from '@/utils/followup/followapis'

  import { mapState, mapActions } from 'vuex'
  export default {
    name: "addNewPlan",
    components: {
      BreadCrumb,
      SelectPatient,
      HasSelectedPatient,
      SetTimeNode,
    },
    data() {
      return {
        setTimeNodeList: [],//重写后的setTimeNodeList
        isStandedTemplate: false, // 是否是固定的履约模板
        standedTimeNodeList: [], // 如果是国定履约模板，获取固定数据后不可更改，只读
        checkForm: false,
        /*面包屑配置*/
        curmbFirst: '履约管理',
        curmbSecond: '计划管理',
        curmbThird: '新建履约计划',
        jumPathThird: '/followUp/plan-manage',
        activeTab: 'first',
        resourceId: '',//当前选择的履约模板id
        noName: false,
        noResourceId: false,
        noTime: false,
        noChoice: false,
        baseInfo: {
          name: '',//履约计划名称
          patientIdList: [],//履约居民列表
          resourceId:'',//履约模板ID
          time:'',//履约开始时间
          remarksStatus: '',
          fPlanTimeReqList: [],//时间节点列表
          hasSelectedNum: 0,
        },
        isShowSelectPatient: false,
        isShowSelectedDialog: false,
        selectPatientType: 1,
        hasSelectedList: [],
        rules: {
          name: [{ required: true, message: '请输入履约计划名称', trigger: 'blur' }],
          hasSelectedNum: [{ required: true, message: '请添加履约居民', trigger: 'change' }],
          resourceId: [{ required: true, message: '请选择履约模板', trigger: 'change' }],
          time: [{ required: true, message: '请选择履约开始时间', trigger: 'change' }],
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        isShowProtocolDialog: true,
        isSentedProt: false,
        patientIds: [],
        sendMsgPatientIds: []
      }
    },
    created() {
      // 获取备注
      this.getRemarkOption()
      // 获取履约计划模板列表
      this.getFollowupTemplate()
    },
    computed: {
      ...mapState('planManage',{
        remarkOption: state => state.remarkOption,
        templateOptions: state => state.templateOptions,
      })
    },
    methods: {
       ...mapActions('planManage', ['getTimeNodeList','getRemarkOption','getFollowupTemplate']),
      
      // Add by Anndy Yang
      // 统一验证：量表内是否存在敏感字段、居民是否签署隐私协议、7天内是否发送过授权短信
      async  uniteValidateAction() {
        let validParams = {
          scaleNo: '',
          patientIds: this.patientIds, // pc端只传这个字段
          // planPatientsTimesId: planPatientsTimesId,  // app端只传这个字段
          protocolType: 5,
          userType: 1,
          validateType: 2
        };

        let r = await uniteValidate(validParams).then(res => {
          let result = res;
          // 请求成功
          if (result.code === '000000') {
            let levelType = result.data.levelType;
            // 没有敏感字段或者居民已经签订过协议，则直接返回
            if (levelType === 1 || levelType === 2) {
              return 0;
            } else if (levelType === 3) {
              this.isShowProtocolDialog = true;
              this.isSentedProt = false;
              return 1;
            } else if (levelType === 4) {
              this.isShowProtocolDialog = true;
              this.isSentedProt = true;
              this.sendMsgPatientIds = result.data.ids;
              return 1;
            }
          }
        });
      },

      // 发送协议授权短信给居民
      sendMsgToPatients() {
        authMessage({ patientIds: this.sendMsgPatientIds }).then(res => {
          if (res.code === '000000') {
            this.$message({
              message: '已发送，请尽快联系居民同意授权',
              type: 'success'
            });
          }
        });
        this.isShowDialog = false;
      },

      // 点击保存
      saveEdit() {
        // 点击保存，先进行校验，表单字段是否通过验证
        this.checkForm = true
      },
      handleDateInputConfirm(e){
        if(!this.baseInfo.time){
          this.$refs.beginDate.picker.date = new Date();
        }
      },
      // 监听保存校验结果
      addListenSave(val){
        // console.log('监听保存校验结果',val)
        this.checkForm = false
         if(val.status){
            this.baseInfo.fPlanTimeReqList = val.setTimeNodeList
            // this.baseInfo.time = (new Date(this.baseInfo.time).getTime())
            // console.log(this.baseInfo.time)
            // 提交
            createFollowPlan(this.baseInfo).then(res=>{
             if(res.code=='000000'){
               //  各种校验通过后，提交编辑内容，toast提示
               this.$message({
                 message: '创建成功',
                 type: 'success'
               });
               setTimeout(()=>{
                 this.$router.push({
                   path: '/followup/plan-manage/plan-list'
                 })
               },2000)
             }else{
               this.$message({
                 message: '创建失败,' + res.message,
                 type: 'error'
               });
             }
           })
         }else{
           this.$message({
             message: val.message,
             type: 'error'
           });
         }
      },
      selectPatientHandler() {
        this.isShowSelectPatient = true;
      },
      closeSelectPatient(val) {
        this.isShowSelectPatient = val;
      },
      seeSelectedHandler() {
        this.isShowSelectedDialog = true;
      },
      closeSelectedDialog(val) {
        this.isShowSelectedDialog = val;
      },
      sureSelectPatient() {
        let getArguments = arguments[0];
        this.isShowSelectPatient = getArguments[0];
        const selectPatients = getArguments[1]; // 每次选中获取的人
        this.hasSelectedList = selectPatients;
        this.patientIds = selectPatients.map( item => {
          return item.patientId
        })
//        console.log('呵呵呵呵',arguments)
        this.baseInfo.patientIdList = [];
        selectPatients.forEach((item)=>{
          this.baseInfo.patientIdList.push(item.patientId);
        })
        this.baseInfo.hasSelectedNum = this.hasSelectedList.length;
        if(this.baseInfo.hasSelectedNum > 0){
          this.noChoice = false;
        }
      },
      continueAdd(val) {
        this.isShowSelectedDialog = val;
        this.isShowSelectPatient = true;
      },
      cancelEdit() {
        this.$confirm('是否放弃本次创建，放弃后数据不能被保存', '', {
          confirmButtonText: '继续创建',
          cancelButtonText: '确定放弃',
          type: 'warning'
        }).then(() => {
        //  关闭弹层，继续创建
        }).catch(() => {
        //  确定放弃，跳出当前编辑页面
          this.$router.push({path: '/followup/plan-manage/plan-list'})
        });
      },

      nextClick(formName) {
        // 创建/修改履约计划
        // 4、校验居民/医生是否签署协议
        alert('创建/修改履约计划')
        console.log(this.hasSelectedList)
        if(this.uniteValidateAction() == 1) {
          return;
        };

        // return
        //  为方便调试，不做校验
        //  this.activeTab = 'second';
        this.$refs[formName].validate((valid) => {
          //用作校验
          if(!this.baseInfo.hasSelectedNum) {
            this.noChoice = true
            return;
          }else {
            this.noChoice = false
          }
          if (valid) {
//            console.log('当前选择的履约模板id为',this.baseInfo.resourceId)
            this.resourceId = String(this.baseInfo.resourceId)
//            console.log( this.baseInfo.resourceId)
            if(this.baseInfo.resourceId){
              if(this.uniteValidateAction() == 1) {
                return;
              };
              getFollowupTableTemplate(this.baseInfo.resourceId).then(res=>{
                this.isStandedTemplate = true
                this.standedTimeNodeList = res.data
                this.activeTab = 'second';
              })
            }else{
              this.isStandedTemplate = false
              this.standedTimeNodeList = [];
              this.activeTab = 'second';
            }
          } else {
            return false;
          }
        });
      },
      preClick() {
        this.activeTab = 'first';
      },
    },
  }
</script>
<style lang="scss" scoped>
  @import '../../../style/followup/followup-common';
  @import '../../../style/followup/element-reset.css';

  .new-plan-content{
    .header{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 20px;
      border-bottom: $borderBottomStyle;
      .title{
        .active-class{
          color: #9B9997;
        }
      }
    }
    .edit-plan-content{
      padding: 30px 0;

      .add-time-content{
        padding-top: 20px;
        .time-line-scroll{
          width: 100%;
          height: 50px;
          box-sizing: border-box;
          background-color: #F0F2F5;
          padding: 8px 10px;
          /*display: flex;*/
          /*align-items: center;*/
          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;
          }
        }
        .form-div{
          padding-top: 30px;
        }
      }


    }
    .err-tips{
      color: #F56C6C;
      font-size: 12px;
      margin-left: 10px;
    }
    .tips{
      font-size: 12px;
      color: #9B9997;
      padding-left: 140px;
      margin-top: -10px;
      padding-bottom: 15px;
    }
    .el-message-box__content{
      padding: 20px 15px;
    }
  }
  .mt10{
    margin-top: 10px;
  }
  .ml20{
    margin-left: 20px;
  }
</style>
