<template>
  <div class="resident-list">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond">
    </bread-crumb>
    <div class="resident-content f-main-content screenSet">
      <p class="page-title">预约管理</p>
      <div class="search-div">
        <div class="search-input">
          <el-form :model="searchData" ref="searchData" :inline="true" :label-width="labelWidth">
            <el-form-item label="随访计划名称：" prop="planName">
              <el-input v-model="searchData.planName" size="small" placeholder="请输入随访计划名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="姓名：" prop="nickname">
              <el-input v-model="searchData.nickname" size="small" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号：" prop="mobilePhone">
              <el-input v-model="searchData.mobilePhone" size="small" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
            <el-form-item label="随访时间范围：" prop="planTimes" clearable>
              <el-date-picker
                v-model="searchData.planTimes"
                type="daterange"
                size="small"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 380px;">
              </el-date-picker>
            </el-form-item>
            <!--<el-form-item label="居民预约状态：" prop="timeStatus">
              <el-select v-model="searchData.timeStatus">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>-->
          </el-form>
        </div>
        <div class="search-btn">
          <el-button class="button-green" type="primary" size="small" @click="searchReservationList">查询</el-button>
          <el-button class="button-white" plain size="small" @click="resetSearchData('searchData')">重置</el-button>
        </div>
      </div>
      <div class="reservation-table table-content">
        <el-radio-group v-model="status" size="small">
          <el-radio-button label="">全部({{reservationList.count}})</el-radio-button>
          <el-radio-button label="1">未发送({{reservationList.unSendCount}})</el-radio-button>
          <el-radio-button label="2">待确认({{reservationList.waitAcceptCount}})</el-radio-button>
          <el-radio-button label="4">已拒绝({{reservationList.refusedCount }})</el-radio-button>
          <el-radio-button label="3">已接受({{reservationList.acceptedCount}})</el-radio-button>

        </el-radio-group>
        <el-button class="button-green" type="primary" size="small" @click="sendReservation">发送预约</el-button>
        <el-table
          :data="reservationList.enteringDtos"
          center
          style="width: 100%;margin-top: 20px;"
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
          ref="multipleReservation">
          <el-table-column
            type="selection"
            align="center"
            :reserve-selection="true">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="姓名"
            align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="goPatientDetail(scope.row)" >{{scope.row.nickname}}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="mobilePhone"
            label="手机"
            align="center">
          </el-table-column>
          <el-table-column
            prop="name"
            label="随访计划名称"
            align="center">
          </el-table-column>
          <el-table-column
            width="160"
            prop="fuPlanTime"
            label="随访计划时间"
            align="center">
          </el-table-column>
          <el-table-column
            width="160"
            label="随访预约时间"
            align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status==1" style="color: #49C688;">未发送</span>
              <span v-else-if="scope.row.status==2">待确认</span>
              <span v-else-if="scope.row.status==4"  style="color: #D5172E;">已拒绝</span>
              <span v-else>{{scope.row.appointmentTime}}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="180"
            fixed="right"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button class="btn-right-class" type="text" @click="sendReservationRow(scope.row)">发送预约</el-button>|
              <el-button class="btn-right-class" type="text" @click="changeReserveClick(scope.row)">变更预约</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            v-if="reservationList.enteringDtos"
            @size-change="handleSizeChangePre"
            @current-change="handleCurrentChangePre"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="reservationList.pageNo"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="reservationList.pageSize"
            :total="statusTotal">
          </el-pagination>
        </div>
      </div>
    </div>
    <send-reservation :isDialogShow="isDialogShow" :checkData="checkRevervationData" :selectList="selectList" @closeSendReserve="closeSendReserve" :validContents="validContents"></send-reservation>
    <no-enough :isNoEnoughShow="isNoEnoughShow" @closeTipsDialog="closeTipsDialog"></no-enough>
    <change-reservation :isChangeReservation="isChangeReservation" @closeChangeReserve="closeChangeReserve" :reservationForm="needPara"></change-reservation>
    <followup-detail :dialogFormVisible="dialogDetailShow" @closeDetail="closeDetail" :enteringInfo="enteringInfo"></followup-detail>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';

  //面包屑
  import BreadCrumb from '@/components/breadcrumb';

  import SendReservation from './dialog/send-reservation';
  import NoEnough from './dialog/no-enough';
  import ChangeReservation from "./dialog/change-reservation";
  import followupDetail from "@/views/followup/record-manage/dialog/followupDetail";
  export default {
    name: "reservation-list",
    components: {
      ChangeReservation,
      BreadCrumb,
      SendReservation,
      NoEnough,
      followupDetail
    },
    data() {
      return {
        /*面包屑配置*/
        curmbFirst: '随访管理',
        curmbSecond: '预约管理',
        /*面包屑配置*/
        labelWidth: '125px',  //标题长度
        searchData: {
          planName: '',
          planTimes: ''
        }, //查询数据
        status: '', //列表筛选条件
        statusOptions: [
          {
            value: 1,
            label: '未完成'
          },
          {
            value: 2,
            label: '已完成'
          },
          {
            value: 3,
            label: '已过期'
          }
        ],  //居民预约状态\
        // hasSmsBalance: true, //短信余额是否充足
        isDialogShow: false, //发送预约dialog展示
        // checkData: {},
        isNoEnoughShow: false, //余额不足dialog展示
        isChangeReservation: false, //变更预约状态dialog展示
        selectionData: [],
        selectList: [],
        ids: [],
        needPara: {},
        dialogDetailShow: false,
        validContents: [],
        getRowKeys(row) {
          return row.fuPlanPatientTimesId;
        },
        statusTotal: null, //每种状态的总数
      }
    },
    created() {

    },
    mounted() {
      if(this.$route.query.planName && this.$route.query.appointTime && this.$route.query.status) {
        this.searchData.planName = this.$route.query.planName;
        this.searchData.planTimes = [this.$route.query.appointTime,this.$route.query.appointTime];
        this.status = this.$route.query.status
        this.getReservationList({
          planName: this.$route.query.planName,
          beginTime: this.$route.query.appointTime,
          endTime: this.$route.query.appointTime,
          status: this.status
        })
      } else {
        this.getReservationList({
          status: this.status
        });
      }

    },
    computed: {
      ...mapState('reservationManage',{
        reservationList: state => state.reservationList,
        checkRevervationData: state => state.checkRevervationData,
      }),
      ...mapState('recordManage',{
        enteringInfo: state => state.enteringInfo,
      })
    },
    methods: {
      ...mapActions('reservationManage', ['getReservationList','getCheckReservation']),
      ...mapActions('recordManage', [ 'getEnteringInfo']),
      handleSizeChangePre(pageSize) {
        this.getReservationList({
          pageSize,
          status: this.status,
          ...this.setSearchData()
        })
      },
      handleCurrentChangePre(pageNo) {
        this.getReservationList({
          pageNo,
          status: this.status,
          ...this.setSearchData()
        })
      },
      searchReservationList() { //查询预约列表
        this.getReservationList({
          ...this.setSearchData(),
          status: this.status,
          pageNo: 1
        })
      },
      resetSearchData(formName) {
        this.$refs[formName].resetFields();
        this.getReservationList({
          status: this.status
        });
      },
      async goPatientDetail(row) { //预约详情页
        await this.getEnteringInfo({patientId: row.patientId,fuPlanPatientTimesId: row.fuPlanPatientTimesId});
        this.dialogDetailShow = true;
      },
      setSearchData() {
        const { planName, mobilePhone, timeStatus, nickname } = this.searchData;
        let para = {}
        if(this.searchData.planTimes) {
          para = {
            planName,
            mobilePhone,
            timeStatus,
            nickname,
            beginTime: this.searchData.planTimes[0],
            endTime: this.searchData.planTimes[1],
            status: this.status
          }
        } else {
          para = {
            planName,
            mobilePhone,
            timeStatus,
            nickname,
            status: this.status
          }
        }
        return para;
      },
      async initCheck() {
        await this.getCheckReservation({
          // patientIds: this.ids
          content: '',
          validContents:this.validContents
        })
        const { sendFlag, inServiceTimeFlag } = this.checkRevervationData
        //判断短信余额是否不足
        if(sendFlag){
          this.isDialogShow = true;
        }else {
          if(!inServiceTimeFlag) {
            this.$message.warning('已超过发送时间范围!');
            return;
          }else {
            this.isNoEnoughShow = true;
          }
        }
      },
       sendReservation() {
        // console.log('选择人员长度',this.selectionData.length)
         if(this.selectionData.length > 100) {
           this.$message.warning('每次最多选择100条单条随访进行预约!');
           return;
         }else if(this.selectionData.length <= 0){
           this.$message.warning('请选择要发送预约的居民!');
           return;
         }else{
           this.selectList = this.selectionData;
           // 发送预约校验
           this.initCheck();
         }
      },
      sendReservationRow(row){
        let newList = [];
        newList.push({
          planId: row.fuPlanId,
          patientId: row.patientId,
          planName: row.name,
          patientsTimesId: row.fuPlanPatientTimesId,
          type: row.fuPlanType,
        });
        this.selectList = newList;
        this.validContents = [{
          patientId: row.patientId,
          size: 1,
        }];
        // 发送预约校验
        this.initCheck();
      },
      changeReserveClick(row){
        this.needPara = {
          nickname: row.nickname,
          appointmentDate: '',
          appointmentRange: '',
          planId: row.fuPlanId,
          patientId: row.patientId,
          planName: row.name,
          patientsTimesId: row.fuPlanPatientTimesId,
          type: row.fuPlanType,
          changeReason: '',
          appointStatus: null
        };
        this.isChangeReservation = true;
      },
      closeSendReserve(val){
        this.isDialogShow = val;
        this.getReservationList({
          ...this.setSearchData(),
          status: this.status,
        })
        this.$refs.multipleReservation.clearSelection();
      },
      closeTipsDialog(val){
        this.isNoEnoughShow = val;
      },
      closeChangeReserve(val){
        this.isChangeReservation = val;
        this.getReservationList({
          ...this.setSearchData(),
          status: this.status,
        })
      },
      handleSelectionChange(val){
        for(let i in val){
          for(let j in val[i]) {
            if(j == 'fuPlanId') {
              val[i]['planId'] = val[i][j];
              // delete val[i]['fuPlanId'];
            }
            if(j == 'name') {
              val[i]['planName'] = val[i][j];
            }
            if(j == 'fuPlanPatientTimesId') {
              val[i]['patientsTimesId'] = val[i][j];
            }
            if(j == 'fuPlanType') {
              val[i]['type'] = val[i][j];
            }
          }
        }
        this.selectionData = val;
        //统计选择的居民的patientId
        let idsArray = [];
        if (val.length > 0) {
          for(let i=0; i<val.length; i++){
            idsArray.push(val[i].patientId)
          }
          // this.ids = idsArray.join(",")
          this.ids = idsArray;
        }
        let dedupeArr = Array.from(new Set(this.ids))
        let count = 0;
        let obj = {};//最终返回的数据
        dedupeArr.forEach(i => {
          count = 0;
          this.ids.forEach(j => {
            if(i === j){
              count++;
            }
          })
          obj[i] = count;
        })
        let i=0;
        let aaa = [];
        for(i in obj ){
          aaa.push({patientId: i,size: obj[i]});
        }
        this.validContents = aaa;

      },
      closeDetail(val){
        this.dialogDetailShow = val;
      },
    },
    watch: {
      status(val) {
        this.getReservationList({
          status: val,
          pageNo: 1,
          pageSize: 10,
          ...this.setSearchData()
        })
      },
      reservationList(val) {
        if(this.status == 1) {
          this.statusTotal = val.unSendCount
        } else if (this.status == 2) {
          this.statusTotal = val.waitAcceptCount
        } else if (this.status == 3) {
          this.statusTotal = val.acceptedCount
        } else if(this.status == 4) {
          this.statusTotal = val.refusedCount
        } else {
          this.statusTotal = val.count
        }

      },
    }
  }
</script>
<style lang="scss" scoped>

  @import '../../../style/followup/followup-common';
  @import '../../../style/followup/element-reset.css';

  .reservation-table {
    .button-green {
      float: right;
    }
  }
</style>
