<!--
 * @Author: 廖明明
 * @Date: 2022-04-01 17:11:19
 * @LastEditors: 廖明明
 * @LastEditTime: 2022-04-21 13:16:48
 * @Description: 自定义弹窗组件
-->
<template>
  <view class="seiminModel seiminModel_mask" v-if="opts.isVisible">
    <view class="seiminModel_container animate__animated animate__fadeIn animate__faster">
      <!-- 标题 -->
      <view class="seiminModel_header" :class="{noTitle:!opts.title}">
        <text>{{ opts.title }}</text>
        <text class="seiminModel_countDown" v-if="
            (nurseDeptSwitchTip < 0 || (nurseDeptSwitchTip > 0 && closeTime > 0))&&isCheckDept
          ">
          <text v-if="nurseDeptSwitchTip < 0">关闭</text>倒计时<text>{{ closeTime }}s</text>
        </text>
      </view>
      <!-- 动态二维码 -->
      <view class="seiminModel_content qrcode" v-if="opts.skin === 'qrcode'">
        <image class="w100 qrcode_img" :src="nurseCodeImg" mode="widthFix"></image>
        <view class="qrcode_operate">
          <view class="refreshQRCode" @click="showNurseCode"> 刷新 </view>
          <view>{{ refreshQRCodeTime }}s</view>
        </view>
      </view>
      <!-- 加急 -->
      <view class="seiminModel_content urgent" v-else-if="opts.skin === 'urgent'">
        <view class="urgent_txt" v-html="opts.content"></view>
        <textarea :focus="true" class="urgent_textarea" auto-height :maxlength="100"
          :placeholder-style="placeholderStyle" placeholder="请填写加急原因" v-model="urgentTextArea" />
      </view>
      <!-- 评价 -->
      <view class="seiminModel_content evaluate" v-else-if="opts.skin === 'evaluate'">
        <view class="evaluate_txt" v-html="opts.content"></view>
        <view class="evaluate_list">
          <view class="evaluate_item">
            <text class="evaluate_label">星级：</text>
            <view class="evaluate_icons">
              <text class="pda" :class="star" v-for="(star,i) in stars" :key="i" @click="clickStar(i)"></text>
            </view>
          </view>
          <view class="evaluate_item">
            <text class="evaluate_label">评级：</text>
            <textarea :focus="true" class="evaluate_textarea" auto-height :maxlength="100"
              :placeholder-style="placeholderStyle" placeholder="请输入..." v-model="evaluateTextArea" />
          </view>
        </view>
      </view>
      <!-- 预约时间 -->
      <view class="seiminModel_content yyDate" v-else-if="opts.skin === 'yyDate'">
        <view class="yyDate_txt" v-html="opts.content"></view>
        <view class="yyDate_date_time">
          <picker mode="multiSelector" @click.native="clickDate" @columnchange="columnchangeDate($event)"
            @change="changeDate($event)" :value="dateIndex" :range="dateOptions">
            <view class="yyDate_date"><text>{{dateVal}}</text><text class="pda pda-icon"></text></view>
          </picker>
          <picker mode="multiSelector" @click.native="clickTime" @columnchange="columnchangeTime($event)"
            @change="changeTime($event)" :value="timeIndex" :range="timeOptions">
            <view class="yyDate_time"><text>{{timeVal}}</text><text class="pda pda-shouye8"></text></view>
          </picker>
        </view>
        <view class="yyDate_tips red" v-if="!dateVal">
          请选择日期
        </view>
        <view class="yyDate_tips red" v-else-if="!timeVal">
          请选择时间
        </view>
        <view class="yyDate_nextDay" @click="nextDay" v-if="dateVal">
          下一日
        </view>
      </view>
      <!-- 修改密码 -->
      <view class="seiminModel_content changePwd" v-else-if="opts.skin === 'changePwd'">
        <view class="changePwd_item">
          <view class="title">原始密码</view>
          <uni-easyinput type="password" focus v-model="pwdOld" placeholder="请输入原始密码"></uni-easyinput>
        </view>
        <view class="changePwd_item">
          <view class="title">新密码</view>
          <uni-easyinput type="password" v-model="newPwd" placeholder="请输入新密码"></uni-easyinput>
        </view>
        <view class="changePwd_item">
          <view class="title">确认新密码</view>
          <uni-easyinput type="password" v-model="newPwd2" placeholder="请输入新密码"></uni-easyinput>
        </view>
      </view>
      <!-- 正常弹窗 -->
      <view class="seiminModel_content" v-else>
        <!-- 图标 -->
        <view class="seiminModel_status">
          <text class="pda pda-shibai red" v-if="opts.icon === 'error'"></text>
          <text class="pda pda-wenhao yellow" v-if="opts.icon === 'warn'"></text>
          <text class="pda pda-duigou green" v-if="opts.icon === 'success'"></text>
        </view>
        <!-- 内容 -->
        <view class="seiminModel_txt" v-html="opts.content"></view>
      </view>
      <!-- 底部 -->
      <view class="seiminModel_footer" v-if="
          nurseDeptSwitchTip <= 0 || (nurseDeptSwitchTip > 0 && closeTime === 0)
        ">
        <view class="seiminModel_footer__btn" v-for="(btn, i) in opts.btns" :style="{
            flex: btn.flex,
            color: btn.textColor,
          }" @click="btn.click($event)" :key="i">{{ btn.name }}</view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    mapState
  } from "vuex";
  import {
    reqDeptCodes
  } from "../../request/api.js";
  import {
    generateArray
  } from '../../utils/index.js';
  import {
    format,
    endOfMonth,
    addDays,
  } from 'date-fns';
  export default {
    name: "seiminModel",
    props: {
      // 其他数据
      otherData: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        isCheckDept: false, //是否是切换科室
        dateOptions: [
          [],
          [],
          []
        ],
        dateIndex: [0, 0, 0],
        dateVal: '',
        timeOptions: [
          [],
          []
        ],
        timeIndex: [0, 0],
        timeVal: '',
        // 配置项
        opts: {},
        // 动态二维码定时器
        timer: null,
        // 动态二维码qrcode
        nurseCodeImg: "",
        // 动态二维码刷新间隔时长
        refreshQRCodeTime: 30,
        // 护士科室切换提示自动关闭设置(时长，单位秒)
        closeTime: 0,
        // 护士科室切换提示自动关闭设置(定时器，单位秒)
        timerCloseTime: null,
        // 加急原因
        urgentTextArea: '',
        // 加急原因的placeholder样式
        placeholderStyle: 'color:#999;padding:18rpx;',
        // 星级
        stars: [],
        // 评价内容
        evaluateTextArea: '',
        // 原始密码
        pwdOld: '',
        // 新密码
        newPwd: '',
        // 确认新密码
        newPwd2: '',
      };
    },
    onUnload() {
      if (this.timerCloseTime) {
        clearInterval(this.timerCloseTime);
        this.timerCloseTime = null;
      }
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    computed: {
      ...mapState('other', ["nurseDeptSwitchTip"]),
      ...mapState("login", ["loginInfo"]),
    },
    methods: {
      // 下一日
      nextDay() {
        let arr = this.dateVal.split('-');
        let d_year = Number(arr[0]);
        let d_month = Number(arr[1]) - 1;
        let d_day = Number(arr[2]);
        let date = addDays(new Date(d_year, d_month, d_day, 0, 0, 0), 1);
        let year = format(date, 'yyyy');
        let month = format(date, 'MM');
        let day = format(date, 'dd');
        let year_i = this.dateOptions[0].findIndex(v => v === year);
        let month_i = this.dateOptions[1].findIndex(v => v === month);
        let day_i = this.dateOptions[2].findIndex(v => v === day);
        console.log(year_i, month_i, day_i, this.dateOptions, year, month, day)
        this.dateIndex = [year_i, month_i, day_i];
        this.dateVal = format(date, 'yyyy-MM-dd');

      },
      // 点击日期
      clickDate() {
        if (!this.dateVal) {
          this.dateIndex = [0, 0, 0];
        }
      },
      // 点击时间
      clickTime() {
        console.log(this.timeVal)
        if (!this.timeVal) {
          this.timeIndex = [0, 0];
        }
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth();
        let day = now.getDate();
        let hour = now.getHours();
        let minute = now.getMinutes();
        let second = now.getSeconds();
        if (this.dateVal) {
          let arr = this.dateVal.split('-');
          let d_year = Number(arr[0]);
          let d_month = Number(arr[1]) - 1;
          let d_day = Number(arr[2]);
          let c_d_day = Number(format(endOfMonth(new Date(d_year, d_month, d_day, 0, 0, 0)), 'dd'));
          if (year != d_year || month != d_month || day != d_day) {
            this.timeOptions = [generateArray(0, 23), ['00', '30']];
          }
          if (this.timeVal) {
            let arr = this.timeVal.split(':');
            let i1 = this.timeOptions[0].findIndex(v => v === arr[0]);
            console.log(i1)
            let i2 = this.timeOptions[1].length > 1 ? 30 : 0;
            if (i1) {
              this.timeOptions[1] = ['00', '30'];
            }
            this.timeIndex = [i1, i2];
          }
        }
      },
      // 滚动日期picker
      columnchangeDate(e) {
        console.log(e.detail);
        console.log(this.dateOptions, this.dateIndex);
        const {
          column, //列数
          value, //索引
        } = e.detail;
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth();
        let day = now.getDate();
        let hour = now.getHours();
        let minute = now.getMinutes();
        let second = now.getSeconds();
        let c_day = Number(format(endOfMonth(new Date(year, month, day, 0, 0, 0)), 'dd'));
        if (column === 0) {
          // 年
          if (year != this.dateOptions[column][value]) {
            this.dateOptions[1] = generateArray(1, 12);
            this.dateOptions[2] = generateArray(1, c_day);
          } else {
            this.dateOptions[1] = generateArray(month + 1, 12);
            this.dateOptions[2] = generateArray(day, c_day);
          }
          this.dateIndex = [value, 0, 0];
        }
        if (column === 1) {
          // 月
          if ((month + 1) != this.dateOptions[column][value]) {
            this.dateOptions[2] = generateArray(1, c_day);
          } else {
            this.dateOptions[2] = generateArray(day, c_day);
          }
          this.dateIndex = [this.dateIndex[0], value, 0];
        }
      },
      // 滚动时间picker
      columnchangeTime(e) {
        console.log(e.detail);
        console.log(this.timeOptions);
        const {
          column, //列数
          value, //索引
        } = e.detail;
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth();
        let day = now.getDate();
        let hour = now.getHours();
        let minute = now.getMinutes();
        let second = now.getSeconds();
        if (column === 0) {
          // 月份
          if (hour != this.timeOptions[column][value]) {
            this.timeOptions[1] = ['00', '30'];
          }
        }
      },
      // 修改日期
      changeDate(e) {
        console.log(e.target.value);
        this.dateIndex = e.target.value;
        this.timeVal = '';
        this.dateVal =
          `${this.dateOptions[0][this.dateIndex[0]]}-${this.dateOptions[1][this.dateIndex[1]]}-${this.dateOptions[2][this.dateIndex[2]]}`;
      },
      // 修改时间
      changeTime(e) {
        console.log(e.target.value);
        this.timeIndex = e.target.value;
        this.timeVal = `${this.timeOptions[0][this.timeIndex[0]]}:${this.timeOptions[1][this.timeIndex[1]]}`;
      },
      // 日期时间的可选范围
      dateTimeScope() {
        let now = new Date();
        let year = Number(format(now, 'yyyy'));
        let month = Number(format(now, 'MM'));
        let day = Number(format(now, 'dd'));
        let hour = Number(format(now, 'HH'));
        let minute = Number(format(now, 'mm'));
        let c_day = Number(format(endOfMonth(now), 'dd'));
        console.log(year, month, day, hour, minute);
        // 判断分钟
        if (minute >= 0 && minute < 30) {
          this.timeOptions = [generateArray(hour, 23), ['30']];
          this.dateOptions = [
            generateArray(year, year + 1),
            generateArray(month, 12),
            generateArray(day, c_day)
          ];
        } else {
          // 跨分钟
          this.timeOptions = [generateArray(hour == 23 ? 0 : hour + 1, 23), ['00', '30']];
          // 跨小时
          if (hour == 23) {
            // 跨日
            if (day == c_day) {
              // 跨月
              if (month == 12) {
                // 跨月
                this.dateOptions = [
                  generateArray(year + 1, year + 1),
                  generateArray(0, 12),
                  generateArray(0, c_day)
                ]
              } else {
                this.dateOptions = [
                  generateArray(year, year + 1),
                  generateArray(month + 1, 12),
                  generateArray(0, c_day)
                ]
              }
            } else {
              this.dateOptions = [
                generateArray(year, year + 1),
                generateArray(month, 12),
                generateArray(day + 1, c_day)
              ]
            }
          } else {
            this.dateOptions = [
              generateArray(year, year + 1),
              generateArray(month, 12),
              generateArray(day, c_day)
            ];
          }
        }
      },
      // 显示弹窗
      show(args = {}) {
        // 默认配置项
        let defaultOptions = {
          skin: "default", //弹窗风格(default|toast|qrcode|)
          isVisible: false, //是否显示弹窗
          title: "提示", //标题
          icon: "success", //图标(success|error|warn|)
          content: "", //内容
          btns: [{
              name: "取消",
              textColor: "#666",
              flex: 1,
              click: this.close,
            },
            {
              name: "确认",
              textColor: "#49B856",
              flex: 1,
              click: this.close,
            },
          ], //弹窗按钮
        };
        // 根据弹窗风格修改默认配置项
        switch (args.skin) {
          case "toast":
            defaultOptions.btns = [{
              name: "知道了",
              textColor: "#49b856",
              flex: 1,
              click: this.close,
            }, ];
            break;
        }
        // 按钮合并参数
        if (Array.isArray(args.btns)) {
          let btns = [];
          args.btns.forEach((v, i) => {
            btns.push(Object.assign({}, defaultOptions.btns[i], v));
          });
          args.btns = btns;
        }
        // 合并配置
        this.opts = Object.assign({}, defaultOptions, args, {
          isVisible: true,
        });
        if (this.opts.skin === "qrcode") {
          // 如果是动态二维码,则需要发起请求
          this.showNurseCode();
        } else if (this.opts.skin === 'evaluate') {
          // 如果是评价弹窗，则默认选中五个笑脸
          this.stars = ['pda-haoping', 'pda-haoping', 'pda-haoping', 'pda-haoping', 'pda-haoping'];
        } else if (this.opts.skin === 'yyDate') {
          console.log(this.otherData);
          // 回显
          if (this.otherData.date) {
            //回显日期
            this.dateVal = format(this.otherData.timestamp, 'yyyy-MM-dd');
          }
          if (this.otherData.time) {
            //回显日期
            this.timeVal = format(this.otherData.timestamp, 'HH:mm');
          }
          // 日期时间的可选范围
          this.dateTimeScope();
        } else if (this.opts.skin === 'changePwd') {
          // 如果是修改密码,则清空数据
          this.pwdOld = '';
          this.newPwd = '';
          this.newPwd2 = '';
        }
      },
      // 关闭弹窗
      close() {
        this.opts.isVisible = false;
        if (this.opts.skin === "qrcode") {
          clearInterval(this.timer);
          this.timer = null;
        }
      },
      // 科室动态二维码方法
      showNurseCode() {
        let deptId = this.loginInfo.user && this.loginInfo.user.dept.id;
        reqDeptCodes([deptId]).then((res) => {
          if (res.status == 200) {
            res["data"] = res["data"] || [];
            res["data"][0] = res["data"][0] || {};
            this.nurseCodeImg = res["data"][0].base64 || "";
            this.refreshQRCodeTime = res["data"][0].refreshQRCodeTime || 30;
            clearInterval(this.timer);
            this.timer = setInterval(() => {
              this.refreshQRCodeTime = Math.max(--this.refreshQRCodeTime, 0);
              if (this.refreshQRCodeTime === 0) {
                clearInterval(this.timer);
                this.showNurseCode();
              }
            }, 1000);
          } else {
            clearInterval(this.timer);
            uni.showToast({
              icon: "none",
              title: "获取数据失败",
            });
          }
        });
      },
      // 切换科室弹窗
      showChangeDept(options = {}) {
        this.isCheckDept = true;
        this.show(options);
        // (1)	当用户设置为正数时，用户必须查看此窗体指定秒数。
        // (2)	当用户设置为负数时，用户可点击知道了也可倒计时自动关闭。
        // (3)	如果用户填写0则为无自动关闭和强制查看时间。
        if (this.nurseDeptSwitchTip === 0) {
          return;
        }
        this.closeTime = Math.abs(this.nurseDeptSwitchTip);
        clearInterval(this.timerCloseTime);
        this.timerCloseTime = setInterval(() => {
          this.closeTime = Math.max(--this.closeTime, 0);
          if (this.closeTime === 0) {
            if (this.nurseDeptSwitchTip < 0) {
              this.close();
            }
            clearInterval(this.timerCloseTime);
          }
        }, 1000);
      },
      // 选择星级
      clickStar(index) {
        for (let i = 0; i < this.stars.length; i++) {
          this.$set(this.stars, i, i > index ? 'pda-haoping1' : 'pda-haoping');
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  .seiminModel {
    font-size: 36rpx;
    color: #000;
    line-height: 50rpx;
    text-align: center;

    &.seiminModel_mask {
      background-color: rgba(0, 0, 0, 0.5);
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      z-index: 999;
      @include flex(center, center);

      .seiminModel_container {
        width: 560rpx;
        border-radius: 8rpx;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        align-content: center;

        .seiminModel_status {
          margin-bottom: 35rpx;

          .pda {
            font-size: 138rpx;
          }
        }

        .seiminModel_header {
          height: 100rpx;
          position: relative;
          @include flex(center, center);

          &.noTitle {
            height: 40rpx;
          }

          .seiminModel_countDown {
            position: absolute;
            right: 26rpx;
            font-size: 28rpx;
            color: $defaultColor;
          }
        }

        .seiminModel_content {
          flex: 1;
          background-color: #f9fafb;
          margin: 0 36rpx 25rpx;
          color: #333;
          padding: 76rpx 24rpx;
          @include border;
          @include numbersAndLettersNoWrap;

          // 动态二维码
          &.qrcode {
            padding: 24rpx;
            font-size: 32rpx;
            color: #999;

            .qrcode_img {
              height: 464rpx;
            }

            .qrcode_operate {
              @include flex(space-between, center);

              .refreshQRCode {
                color: $defaultColor;
              }
            }
          }

          // 加急
          &.urgent {
            padding: 0;

            .urgent_txt {
              font-size: 28rpx;
              color: #666;
              line-height: 40rpx;
              padding: 24rpx;
              @include border(bottom);
            }

            .urgent_textarea {
              width: 440rpx;
              margin: 24rpx;
              min-height: 212rpx;
              background: #FFFFFF;
              border-radius: 2rpx;
              text-align: left;
              @include border;

              ::v-deep .uni-textarea-textarea {
                padding: 18rpx;
              }
            }
          }

          // 评价
          &.evaluate {
            padding: 0;

            .evaluate_txt {
              font-size: 28rpx;
              color: #666;
              line-height: 40rpx;
              padding: 24rpx 0;
              @include border(bottom);
            }

            .evaluate_list {
              padding: 20rpx 34rpx;

              .evaluate_item {
                font-size: 34rpx;
                color: #666;
                margin-top: 10rpx;
                @include flex;

                .evaluate_label {}

                .evaluate_icons {
                  flex: 1;
                  @include flex;

                  .pda {
                    font-size: 40rpx;
                    margin-right: 10rpx;

                    &.pda-haoping {
                      color: $defaultColor;
                    }
                  }
                }

                .evaluate_textarea {
                  flex: 1;
                  min-height: 212rpx;
                  background: #FFFFFF;
                  border-radius: 2rpx;
                  text-align: left;
                  @include border;

                  ::v-deep .uni-textarea-textarea {
                    padding: 18rpx;
                  }
                }
              }
            }
          }

          // 预约时间
          &.yyDate {
            padding: 56rpx 0 82rpx;

            .yyDate_txt {
              font-size: 28rpx;
              color: #666;
              padding-bottom: 20rpx;
              @include border(bottom);
            }

            .yyDate_date_time {
              font-size: 32rpx;
              color: #333;
              @include flex;

              .pda {
                font-size: 44rpx;
              }

              .yyDate_date {
                width: 260rpx;
                height: 66rpx;
                margin: 0 14rpx;
                padding: 0 8rpx;
                background-color: #fff;
                @include border(all, #8E9D9E);
                @include flex(space-between, center);
              }

              .yyDate_time {
                width: 164rpx;
                height: 66rpx;
                margin: 0 14rpx;
                padding: 0 8rpx;
                background-color: #fff;
                @include border(all, #8E9D9E);
                @include flex(space-between, center);
              }
            }

            .yyDate_nextDay {
              margin-top: 42rpx;
              color: $defaultColor;
              text-align: left;
              padding: 0 14rpx;
              text-decoration: underline;
            }

            .yyDate_tips {
              padding: 8rpx;
              font-size: 28rpx;
              text-align: left;
            }
          }

          // 修改密码
          &.changePwd {
            .changePwd_item {
              text-align: left;
              margin-bottom: 24rpx;

              .title {
                font-size: 34rpx;
                color: #666;
                height: 60rpx;
              }

              .uni-easyinput {
                color: #999;
                background-color: #fff;

                .uni-easyinput__placeholder-class {
                  font-size: 28rpx !important;
                  margin-top: 10rpx;
                }
              }
            }
          }
        }

        .seiminModel_footer {
          height: 100rpx;
          color: #666;
          @include border(top);
          @include flex(center, center);

          .seiminModel_footer__btn {
            height: 100%;
            position: relative;
            @include flex(center, center);

            &::after {
              content: "";
              height: 86rpx;
              position: absolute;
              width: 1px;
              bottom: 0;
              right: 0;
              background-color: #dde1e5;
            }
          }
        }
      }
    }
  }
</style>
