<template>
  <div id="appointmentChild">
    <div class="header">
      <p>{{hospitalName}}</p>
      <div class="btns">
        <Button type="success" icon="md-add" @click="add" class="addbtn">新增预约规则</Button>
        <Button type="primary" icon="ios-undo" @click="back" style="margin-left:20px;" class="addbtn">返回</Button>
      </div>
    </div>
    <div class="content">
      <Table border :columns="columns" :data="data"></Table>
    </div>
    <!-- 新增和编辑模态框 -->
    <div class="warrant" v-show="addModel">
      <div class="warrantBox">
        <p class="modelTitle">
          <span>{{showTitle}}</span>
          <span class="exit" @click="cancelBtn"><Icon type="md-close" /></span>
        </p>
        <div class="content">
          <p>{{hospitalName}}</p>
          <div style="display:flex;justify-content: space-between;">
            <div>
              <span class="red">*</span>
              <span>名称:</span>
              <Input type="text" :disabled="dis" placeholder="请输入名称" style="width:220px" v-model="icon.name" />
            </div>
            <div>
              <span class="red">*</span>
              <span>允许:</span>
              <Input type="text" :disabled="dis" placeholder="请输入整数" style="width:95px" v-model="icon.num" />
              <span>（天）开放预约</span>
            </div>
          </div>
          <!-- <div style="margin:15px 0;">
            <span>启用状态：</span>
            <i-switch v-model="switch1" @on-change="change" />
          </div> -->
          <div style="display:flex;justify-content: space-between;margin-top:10px;">
            <div>
              <span class="red">*</span>
              <span>时间段:</span>
            </div>
            <div style="display:flex;justify-content: space-between;width:170px;">
              <div>
                <span class="red">*</span>
                <span>总预约人数:</span>
              </div>
              <Button type="primary" :disabled="dis" size="small" @click="add2">新增</Button>
            </div>
          </div>
          <div style="display:flex;justify-content: space-between;margin-bottom:5px;" v-for="(item,i) in icon2" :key="i">
            <div>
              <TimePicker format="HH:mm" :disabled="dis" v-model="item.appointmentBeginTime" placeholder="请选择" style="width: 168px"></TimePicker>
              ~
              <TimePicker format="HH:mm" :disabled="dis" v-model="item.appointmentEndTime" placeholder="请选择" style="width: 168px"></TimePicker>
            </div>
            <div style="display:flex;justify-content: space-between;width:170px;">
              <Input v-model="item.appointmentNumber" :disabled="dis" type="text" style="width:100px;" placeholder="请输入整数" />
              <div class="redbox" @click="detail(i)">一</div>
            </div>
          </div>
        </div>
        <div class="buttons">
          <Button type="primary" ghost @click="cancelBtn">取消</Button>
          <Button type="primary" v-if="this.changname=='新增'" @click="confirmBtn">确定</Button>
          <!-- <Button type="primary" v-if="this.changname=='查看'" @click="confirmBtn2">确定</Button> -->
        </div>
      </div>
      <!--删除确认框-->
      <Modal v-model="delMsg" :closable="false" :mask-closable="false" width="400" scrollable>
        <p slot="header" style="height:40px;lineHeight:40px;backgroundColor:#ED4014;color:#fff;text-align:center">
          <span>删除</span>
        </p>
        <p>确定删除 <b>"{{delMsgName}}"</b> 吗？</p>
        <div slot="footer">
          <Button type="error" ghost @click="cancel">关闭</Button>
          <Button type="error" @click="ok">确定</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import axios from './../../assets/js/axios'
export default {
  data(){
    return{
      dis:false,
      delMsg:false,
      delMsgName:'',
      delId:'',
      changname:'新增',
      hospitalName:'余杭区第二附属医院',
      addModel:false,
      showTitle:'',
      page:1,
      size:10,
      total:0,
      icon:{
        name:'',
        num:'',
      },
      icon2:[
        {
          appointmentBeginTime:'',
          appointmentEndTime:'',
          appointmentNumber:''
        }
      ],
      switch1:false,
      columns:[
        {title:'名称',key:'name',align:'left'},
        {title:'预约时间天数',key:'appointmentDay',align:'left'},
        // {title:'预约开始时间',key:'appointmentBeginTime',align:'left'},
        // {title:'预约结束时间',key:'appointmentEndTime',align:'left'},
        {title:'启用状态',key:'status',
          render: (h,params) => {
            return h('i-switch',{
              props: {
                value:params.row.enabled==1?true:false,//设置开还是关  true   false
                beforeChange:this.handleBeforeChange
              },
              on:{
                'on-change':(value)=>{
                  this.changesta(params.row.id,value)
                }
              }
            })
          }
        },
        {title:'操作',key:'action',align:'left',
          render: (h,params) => {
            return h('div',[
              h('Button',{
                props: {
                  type:'primary',
                  size:'small'
                },
                style:{
                  marginRight:'5px',
                },
                on: {
                  click: () => {
                    this.dis = true
                    this.edit(params.row.id)
                  }
                }
              },'查看'),
              h('Button',{
                props: {
                  type:'error',
                  size:'small'
                },
                on: {
                  click: () => {
                    this.del(params.row.id)
                  }
                }
              },'删除'),
            ])
          }
        },
      ],
      data:[],
    }
  },
  mounted(){
    this.id = this.$route.query.id;
    this.hospitalName = this.$route.query.hosName
    this.getpage()
  },
  methods:{
    getpage(){
      let _this = this
      axios.post('platform-upms/hospitalManage/listByHospitalAppointmentRule',{
        current: _this.page,
        hospitalId: _this.id,
        size: _this.size
      }).then(res=>{
        _this.total = res.data.data.total
        _this.data = res.data.data.records
      })
    },
    add(){
      this.changname = '新增'
      this.addModel = true;
      this.dis = false;
      this.showTitle = '新增预约规则'
    },
    add2(){
      this.icon2.push({
          appointmentBeginTime:'',
          appointmentEndTime:'',
          num2:''
        })
    },
    back(){
      this.$router.push({path:'/index/hospital/appointment/101/1'})
    },
    edit(id){
      this.addModel = true;
      this.changname = '查看'
      this.showTitle = '查看预约规则'
      axios.post('platform-upms/hospitalManage/hospitalAppointmentRuleById',{
        id:id
      }).then(res=>{
        this.icon.name = res.data.data.name;
        this.icon.num = res.data.data.appointmentDay;
        let date1 = res.data.data.appointmentBeginTime;
        let date2 = res.data.data.appointmentEndTime; 
        // var sArr = date2.split("-");
        // var eArr = date1.split("-");
        // var sRDate = new Date(sArr[0], sArr[1], sArr[2]);
        // var eRDate = new Date(eArr[0], eArr[1], eArr[2]);
        // var days = (sRDate-eRDate)/(24*60*60*1000);
        // this.icon.num = days
        var arr = [] 
        arr = res.data.data.hospitalAppointmentRuleDetailVos
        this.icon2 = arr
        // for(let i in arr){
        //   this.icon2.time1 = arr[i].appointmentBeginTime
        //   this.icon2.time2 = arr[i].appointmentEndTime
        //   this.icon2.num2 = arr[i].appointmentNumber
        // }
        // console.log(this.icon2)
      })
    },
    cancelBtn(){
      this.addModel=false;
      this.icon.name = '';
      this.icon.num = '';
      this.switch1 = false;
      this.icon2 = [{
        appointmentBeginTime:'',
        appointmentEndTime:'',
        appointmentNumber:''
      }]
    },
    change (status) {
      console.log(status)
      // this.$Message.info('开关状态：' + status);
    },
    //切换开关
    handleBeforeChange () {
        return new Promise((resolve) => {
            this.$Modal.confirm({
                title: '您确认要切换开关状态吗？',
                content: '<p>切换当前开关会开启或者关闭此条规则。</p><p>如果开启此条规则，其他已开启的规则将会被关闭。</p>',
                onOk: () => {
                    resolve();
                }
            });
        });
    },
    //开关确认
    changesta(id,value){
      //var i = this.data.findIndex((c) => c.enabled==1)
      // if(i!=-1){
      //   this.$Message.warning('只能有一条预约规则被启用')
      //   value = false
      //   console.log(value)
      //   return false
      // }
      axios.post('platform-upms/hospitalManage/hospitalByAppointmentRuleEnabled',{
        id:id
      }).then(res=>{
        this.$Message.info(res.data.data)
        this.getpage()
      })
    },
    detail(i){
      if(this.changname!='查看'){
        this.icon2.splice(i,1);
      }
    },
    confirmBtn(){
      let _this = this;
      let num = /^[0-9]*$/
      if(_this.icon.name.length>16){
        _this.$Message.warning('名称最大长度为16位')
        return false
      }
      if(!num.test(_this.icon.num) && _this.icon.num.length>5){
        _this.$Message.warning('天数只能为纯数字且最大位数为4位')
        return false
      }
      if(this.icon.num<=0){
        _this.$Message.warning('预约天数只能是大于0的整数')
        return false
      }
      // var day2 = new Date();
      // day2.setTime(day2.getTime());
      // var s2 = day2.getFullYear()+"-" + (day2.getMonth()+1) + "-" + day2.getDate();
      // console.log(s2)
      // //日期，在原有日期基础上，增加days天数
      // function addDate(dateTemp, days) {
      //   var dateTemp = dateTemp.split("-");  
      //   var nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]); //转换为MM-DD-YYYY格式    
      //   var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);  
      //   var rDate = new Date(millSeconds);  
      //   var year = rDate.getFullYear();  
      //   var month = rDate.getMonth() + 1;  
      //   if (month < 10) month = "0" + month;  
      //   var date = rDate.getDate();  
      //   if (date < 10) date = "0" + date;  
      //   var time = year + "-" + month + "-" + date
      //   return time; 
      // }
      // var addTime = addDate(s2,this.icon.num);
      // console.log(addTime);
      // console.log(this.icon2)
      let newArr = []
      for(let i in this.icon2){
        let arr2 = {
          appointmentBeginTime:'',
          appointmentEndTime:'',
          appointmentNumber:''
        }
        arr2.appointmentBeginTime = this.icon2[i].appointmentBeginTime
        arr2.appointmentEndTime = this.icon2[i].appointmentEndTime
        arr2.appointmentNumber = this.icon2[i].appointmentNumber
        if(arr2.appointmentEndTime<arr2.appointmentBeginTime){
          _this.$Message.warning('结束时间不能大于开始时间')
          return false
        }
        if(arr2.appointmentBeginTime=='' || arr2.appointmentEndTime==''){
          _this.$Message.warning('时间段不能有空')
          return false
        }
        if(arr2.appointmentNumber<=0){
          _this.$Message.warning('总预约人数必须是大于0的整数')
          return false
        }
        if(arr2.appointmentNumber.length>6){
          _this.$Message.warning('总预约人数最多为5位数')
          return false
        }
        newArr.push(arr2)
      }
      console.log(newArr)
      axios.post('platform-upms/hospitalManage/addHospitalAppointmentRule',{
        // appointmentBeginTime:s2,
        // appointmentEndTime:addTime,
        appointmentDay:this.icon.num,
        hospitalAppointmentRuleDetailParams:newArr,
        name:this.icon.name,
        hospitalId:this.id
      }).then(res=>{
        this.$Message.info(res.data.data)
        this.addModel = false;
        this.getpage()
      })
    },
    confirmBtn2(){
      this.addModel = false
    },
    del(id,name){
      this.delMsg = true
      this.delMsgName = name
      this.delId = id
    },
    
    cancel(){
      this.delMsg = false
    },
    ok(){
      axios.post('platform-upms/hospitalManage/rmHospitalAppointmentRule',{
        id:this.delId
      }).then(res=>{
        this.$Message.info(res.data.data)
        this.delMsg = false
        this.getpage()
      })
    }
  }
}
</script>

<style scoped>
#appointmentChild{
  width:100%;
  height:100%;
  overflow-y: hidden;
}
#appointmentChild .header{
  display:flex;
  justify-content:space-between;
  border-bottom:1px solid #ccc;
  padding-bottom:20px;
  margin-bottom:20px;
}
#appointmentChild .header:first-child{
  font-size:14px;
  font-weight: 600;
  line-height: 35px;
}
#appointmentChild .content{
  width:98%;
  margin:auto;
  height:300px;
  overflow-y: auto;
}

/*新增编辑模态框*/
#appointmentChild .warrant{
  position:absolute;
  width:100%;
  height:100%;
  background-color:rgba(0,0,0,0.4);
  top:0;
  left:0;
  z-index:999;
}
#appointmentChild .warrantBox{
  position: absolute;
  width:620px;
  top:80px;
  left:50%;
  background-color:#fff;
  margin-left:-310px;
  border-radius:10px;
  padding-bottom:20px;
}
#appointmentChild .modelTitle{
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  background-color: #00507e;
  color: #fff;
  border-radius: 10px 10px 0 0;
  text-align: center;
}
#appointmentChild .exit{
  position: absolute;
  font-size: 20px;
  right: 20px;
  cursor: pointer;
}
#appointmentChild .content{
  padding:15px 25px;
}
#appointmentChild .content p{
  font-size:14px;
  font-weight: 600;
  line-height: 30px;
  margin-bottom:10px;
}
#appointmentChild .content .red{
  color:red;
}
#appointmentChild .redbox{
  width:20px;
  height:20px;
  border:1px solid red;
  text-align: center;
  cursor:pointer;
  margin-top: 7px;
  margin-right: 10px;
  color:red;
}
#appointmentChild .buttons{
  text-align: right;
  margin-right:40px;
}
#appointmentChild .buttons button{
  margin: 10px;
}
</style>