<template>
  <view class="patientBuild">
    <view class="qco_msg" v-html="patientMsg"></view>
    <view class="select_block_wrap">
      <view class="uni-list">
        <checkbox-group @change="checkboxChange">
          <label class="select_block" v-for="good in goods" :key="good.value">
            <checkbox color="#09BB07" :value="good.value" :checked="good.checked" />
            <view>{{good.name}}</view>
          </label>
        </checkbox-group>
      </view>
    </view>
    <!-- 加急 -->
    <view class="remarks" v-if="patientTaskType.allowUrgent == 1">
      <view class="remarks_nav">
        是否加急
      </view>
      <view class="remarks_btn">
        <text class="remarks_btn_name">加急</text>
        <switch class="remarks_btn_value" color="#09BB07" :checked="isUrgent" @change="switchChange" />
      </view>
      <textarea v-if="isUrgent" class="remarks_textarea" auto-height :maxlength="100" placeholder-style="color:#999;"
        placeholder="请填写加急原因" v-model.trim="urgentRemark" />
      <view class="remarks_tips" v-if="isYYBuild">
        <view class="tips">系统支持提前预约送检服务，您是否需要！</view>
        <view class="tips">我不需要预约，希望送检人员立即上门，点击立即建单；</view>
        <view class="tips">我需要提前预约送检服务，点击预约建单；</view>
      </view>
    </view>
    <!-- 底部 -->
    <seiminFooterBtn :btns="btns"></seiminFooterBtn>
    <seiminModel ref="seiminModel" :otherData="{timestamp,date,time}"></seiminModel>
  </view>
</template>

<script>
  import cloneDeep from 'lodash/cloneDeep';
  import {
    mapState,
    mapMutations,
  } from "vuex";
  import {
    ASSOCIATION_TYPES
  } from "../../utils/enum.association_types.js";
  export default {
    data() {
      return {
        ASSOCIATION_TYPES,
        // 时间戳
        timestamp: new Date().getTime(),
        // 预约日期
        date: false,
        // 预约时间
        time: false,
        // 预约建单按钮是否显示
        isYYBuild: false,
        // 有预约时间并且是选中的
        hasYYtimeChecks: [],
        // 是否加急
        isUrgent: false,
        // 设备
        goods: [],
        //患者建单信息展示
        patientMsg: '',
        // 传递过来的参数
        queryParams: {},
        // 加急原因
        urgentRemark: "",
        //底部按钮
        btns: [],
      };
    },
    computed: {
      ...mapState('other', [
        'patientBuildTrip',
        'patientTaskType',
        'selectedPatient',
        'patientBuildData',
      ]),
    },
    methods: {
      ...mapMutations('other', ['changePatientBuildData']),
      // 切换是否加急
      switchChange(e) {
        this.isUrgent = e.detail.value;
        this.urgentRemark = '';
        this.showBtns(!this.isUrgent);
      },
      // 选择设备
      checkboxChange: function(e) {
        console.log(e, this.goods);
        var goods = this.goods,
          values = e.detail.value;
        for (var i = 0, lenI = goods.length; i < lenI; ++i) {
          const item = goods[i]
          if (values.includes(item.value)) {
            this.$set(item, 'checked', true)
          } else {
            this.$set(item, 'checked', false)
          }
        }
      },
      // 立即建单,isYY 是否预约建单
      buildOrder(isYY = false) {
        console.log(this.urgentRemark)
        console.log(this.isUrgent)
        console.log(this.goods)
        // 加急原因非空
        if (this.isUrgent && !this.urgentRemark) {
          this.$refs.seiminModel.show({
            skin: 'toast',
            icon: 'warn',
            content: '请填写加急原因',
          })
          return;
        }
        // 存储建单数据
        // 设备
        this.changePatientBuildData({
          key: 'goods',
          value: this.goods.filter(v => v.checked)
        })
        // 加急
        this.changePatientBuildData({
          key: 'urgent',
          value: {
            isUrgent: this.isUrgent,
            urgentRemark: this.urgentRemark,
          }
        })
        // 预约时间
        this.changePatientBuildData({
          key: 'yyTime',
          value: isYY ? `${this.$refs.seiminModel.dateVal} ${this.$refs.seiminModel.timeVal}:00` : ''
        })
        // 是否预约建单
        this.changePatientBuildData({
          key: 'isYY',
          value: isYY
        })
        // 跳转
        uni.navigateTo({
          url: '/pages/patientBuildConfirm/patientBuildConfirm'
        })
      },
      // 需要预约建单-事件
      yyInspectChange() {
        if (this.patientTaskType.associationType.value === this.ASSOCIATION_TYPES['患者陪检业务']) {
          //陪检
          let obj = this.hasYYtimeChecks.find((item) => {
            return (
              new Date(item.yyTime).getTime() - new Date().getTime() >
              this.patientTaskType.appointmentTime * 60 * 1000
            );
          });
          if (obj) {
            this.showDateTime();
          } else {
            this.date = true;
            this.time = false;
            this.timestamp = new Date().getTime();
          }
        } else {
          //转运
          this.date = true;
          this.time = false;
          this.timestamp = new Date().getTime();
        }
      },
      // 是否加急
      allowUrgentChange(isUrgent) {
        if (this.isYYBuild) {
          this.isYYBuild = !isUrgent;
          if (!this.isYYBuild) {
            this.date = false;
            this.time = false;
            this.timestamp = new Date().getTime();
          }
        } else {
          this.date = false;
          this.time = false;
          this.timestamp = new Date().getTime();
        }
      },
      //回显时间日期
      showDateTime() {
        //当前时间要大于生效时间
        let isYYBuild = this.hasYYtimeChecks.every((item) => {
          return (
            new Date(item.yyTime).getTime() - new Date().getTime() >
            this.patientTaskType.appointmentTime * 60 * 1000
          );
        });
        //如果勾选需要预约检查
        if (isYYBuild) {
          //筛选离当前时间最近的
          let timeList = this.hasYYtimeChecks
            .map((item) => new Date(item.yyTime).getTime())
            .sort();
          this.date = true;
          this.time = true;
          this.timestamp = new Date(timeList[0] - this.patientTaskType.appointmentTime * 60 * 1000);
        } else {
          this.date = false;
          this.time = false;
          this.timestamp = new Date().getTime();
        }
      },
      // 初始化
      init() {
        // 提示文字
        this.patientMsg = `患者<b class="green">${this.selectedPatient.patientName}</b>即将出科，请您选择送检人员需携带哪些设备！`;
        let goods = this.patientBuildTrip.goods ? cloneDeep(this.patientBuildTrip.goods) : []; // 设备
        let checks = this.patientBuildTrip.checks ? cloneDeep(this.patientBuildTrip.checks) : []; // 检查
        this.goods = goods;
        // 患者陪检业务和患者其他服务业务相关处理
        this.hasYYtimeChecks = checks.filter((v) => Boolean(v.yyTime));
        let isPriority = checks.some(v => v.priority == 1);
        // 检查有紧急度,则加急
        if (isPriority) {
          this.isUrgent = true;
          this.urgentRemark = '系统根据检查信息，自动进行加急';
        } else {
          this.isUrgent = false;
          this.urgentRemark = '';
        }
        //判断预约建单按钮
        if (this.hasYYtimeChecks.length && this.patientTaskType.appointmentSwitch == 1) {
          //选中的检查数组都有预约时间并且允许预约建单
          this.isYYBuild = true;
          this.allowUrgentChange(this.isUrgent);
          if (!this.isUrgent) {
            //不加急状态下，回显时间
            this.showDateTime();
          }
          this.yyInspectChange();
        } else {
          //不允许预约建单
          this.isYYBuild = true;
          this.date = false;
          this.time = false;
          this.timestamp = new Date().getTime();
          this.yyInspectChange();
        }

        // 底部按钮展示
        this.showBtns(this.isYYBuild);
      },
      // 底部按钮展示
      showBtns(flag) {
        if (flag) {
          //患者陪检业务或患者其他服务业务，并且预约建单开关打开的情况下
          this.btns = [{
            name: "上一步",
            type: "primary",
            click: () => {
              uni.navigateBack();
            },
          }, {
            name: "预约建单",
            type: "primary",
            click: () => {
              this.$refs.seiminModel.show({
                skin: 'yyDate',
                title: '',
                content: '请您选择希望陪检人员上门的时间',
                btns: [{
                    name: '取消'
                  },
                  {
                    name: '预约建单',
                    click: () => {
                      if (this.$refs.seiminModel.dateVal && this.$refs.seiminModel.timeVal) {
                        this.buildOrder(true);
                      }
                    }
                  }
                ]
              })
            },
          }, {
            name: "立即建单",
            type: "primary",
            click: () => {
              this.buildOrder();
            },
          }, ];
        } else {
          this.btns = [{
            name: "上一步",
            type: "primary",
            click: () => {
              uni.navigateBack();
            },
          }, {
            name: "立即建单",
            type: "primary",
            click: () => {
              this.buildOrder();
            },
          }, ];
        }
      },
    },
    onLoad(queryParams) {
      this.queryParams = queryParams;
      this.init();
    },
  };
</script>

<style lang="scss" scoped>
  .patientBuild {
    margin-bottom: 100rpx;

    ::v-deep .uni-checkbox-input {
      border-radius: 50%;
    }

    ::v-deep .uni-checkbox-input-checked {
      background-color: #09BB07;

      &:before {
        color: #fff;
      }
    }

    ::v-deep uni-checkbox:not([disabled]) .uni-checkbox-input:hover {
      border-color: #09BB07;
    }

    .qco_msg {
      min-height: 144rpx;
      padding: 32rpx;
      color: #999;
      line-height: 40rpx;
      font-size: 28rpx;
      text-align: center;
    }

    .select_block_wrap {
      @include border(top);

      // 设备
      .select_block {
        padding: 0 30rpx;
        height: 88rpx;
        font-size: 34rpx;
        background-color: #fff;
        position: relative;
        @include flex(flex-start, center);

        &:last-of-type {
          &::after {
            opacity: 0;
          }
        }

        &::after {
          content: '';
          height: 1px;
          width: calc(100vw - 30rpx);
          background-color: #E5E5E5;
          position: absolute;
          right: 0;
          bottom: 0;
        }

        .select_label {
          color: #000;
        }
      }
    }

    // 备注
    .remarks {
      min-height: 150rpx;
      background-color: #f9fafb;
      @include border(top);

      .remarks_nav {
        padding: 0 25rpx;
        height: 66rpx;
        font-size: 28rpx;
        color: #666;
        @include flex(flex-start, center);
        @include border(bottom);
      }

      .remarks_btn {
        padding: 0 25rpx;
        font-size: 34rpx;
        height: 88rpx;
        background-color: #fff;
        @include border(bottom);
        @include flex(space-between, center);
      }

      .remarks_textarea {
        padding: 22rpx 25rpx;
        width: 100%;
        min-height: 150rpx;
        background-color: #fff;
        @include border(bottom);
      }

      .remarks_tips {
        padding: 32rpx 25rpx;
        color: #999;
        font-size: 28rpx;
        line-height: 40rpx;
      }
    }
  }
</style>
