<template>
  <view>
    <u-navbar
      class="u-navbar"
      title="短信推送"
      placeholder
      @leftClick="leftClick"
      leftIconColor="#fff"
      bgColor="#00337A"
      :titleStyle="{ color: '#FFF', fontSize: '32rpx' }"
    />
    <view class="push-container">
      <view class="receipt-person">
        <view>收件人：</view>
        <view>
          <u--textarea v-model="phoneStr" placeholder="请输入手机号" autoHeight />
        </view>
        <view class="search-icon" @tap="onSearchPerson" />
      </view>

      <!-- 内容区域 -->
      <view class="message-content">
        <view class="btn-container">
          <view class="report-btn" @tap="getReportMessage">报告</view>
        </view>

        <view class="message-ipt">
          <u--textarea v-model="reportMessage" placeholder="请输入或点击报告填写内容" autoHeight />
        </view>
      </view>

      <view class="send-btn" @tap="onSendMessage">发送</view>
    </view>

    <!-- 人员弹框 -->
    <uni-popup ref="popupAuditing" background-color="#fff">
      <view class="auditing-content">
        <view class="auditing-title">
          <view class="title">
            <text style="margin-left: 15rpx">请选择推送人</text>
          </view>
          <view class="search">
            <view class="search-ipt">
              <uni-easyinput :clear="false" type="text" placeholder="请输入姓名关键字" v-model="searchUserName" />
            </view>
            <view class="search-btn" @tap="onSearchUserInfo">搜索</view>
          </view>
        </view>

        <view class="user-info">
          <view class="user-title">
            <view style="width: 8%"></view>
            <view style="width: 12%">姓名</view>
            <view style="width: 40%">岗位</view>
            <view style="width: 40%">电话</view>
          </view>

          <scroll-view :scroll-y="true" style="height: 33vh" @scrolltolower="onScrollTolower">
            <view class="user-content" v-for="item in auditingUserList" :key="item.id">
              <view style="width: 8%">
                <label>
                  <checkbox
                    :checked="item.isChecked"
                    color="#fff"
                    borderColor="#ccc"
                    backgroundColor="#fff"
                    activeBorderColor="#003778"
                    activeBackgroundColor="#003778"
                    style="transform: scale(0.7)"
                    @tap="onCheckBoxChange(item)"
                  />
                </label>
              </view>
              <view style="width: 12%">{{ item.name }}</view>
              <view style="width: 40%">{{ item.orgName }}</view>
              <view style="width: 40%">{{ item.phone }}</view>
            </view>
          </scroll-view>
        </view>

        <view class="user-btn">
          <view class="btn-cancel" @tap="onHandlerCancel">取消</view>
          <view class="btn-submit" @tap="onHandlerSubmit">确定</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getPushPersonListApi, getReportMessageApi } from '../../../api/workPlan/my'
export default {
  data() {
    return {
      pageNo: 0, // 当前页数
      phoneStr: '',
      reportMessage: '',
      searchUserName: '',
      mobilePhoneNumber: '',
      phoneList: [],
      auditingUserList: [],
      pushPersonListAll: []
    }
  },
  methods: {
    leftClick() {
      uni.navigateBack()
    },
    onSearchPerson() {
      // console.log('查找收件人')
      this.searchUserName = ''
      this.$refs.popupAuditing.open('center')
      this.getPushPersonListData()
    },

    async getPushPersonListData() {
      this.pageNo = 0
      uni.showLoading({ title: '正在查询，请勿重复点击', mask: true })
      const res = await getPushPersonListApi({ name: this.searchUserName })
      uni.hideLoading()
      // console.log(res, '人员信息')
      // 1. 先存储所有数据
      this.pushPersonListAll = res
      this.pushPersonListAll.forEach(e => {
        this.$set(e, 'isChecked', false)
      })

      // 2. 展示 10 条数据
      this.auditingUserList = this.pushPersonListAll.slice(this.pageNo, 10)
      this.pageNo++
    },
    // 搜索人员
    onSearchUserInfo() {
      this.getPushPersonListData()
    },
    // 取消
    onHandlerCancel() {
      this.$refs.popupAuditing.close()
    },
    // 确定
    onHandlerSubmit() {
      const selectPersonList = this.auditingUserList.filter(e => e.isChecked === true)

      // console.log('selectPersonList', selectPersonList)

      let phoneList = []
      if (selectPersonList.length > 0) {
        selectPersonList.forEach(e => {
          phoneList.push(e.phone)
        })
      }

      this.phoneList = phoneList // 选中的人员号码
      this.phoneStr = phoneList.join(',') // 回显号码
      this.$refs.popupAuditing.close()
    },
    // 复选框单击事件
    onCheckBoxChange(item) {
      // console.log(item, '*****')
      item.isChecked = !item.isChecked
    },
    // 滚动触底
    onScrollTolower() {
      // console.log('滚动触底---')
      this.auditingUserList = [
        ...this.auditingUserList,
        ...this.pushPersonListAll.splice(this.pageNo * 10, (this.pageNo + 1) * 10)
      ]
      this.pageNo++
    },
    // 报告按钮
    async getReportMessage() {
      const res = await getReportMessageApi()
      this.reportMessage = res
      // console.log('报告内容', res)
    },
    // 发送按钮
    onSendMessage() {
      if (!this.phoneStr) {
        uni.showToast({ title: '请选择收件人或填写收件人号码', icon: 'none' })
        return
      }
      if (!this.reportMessage) {
        uni.showToast({ title: '请填写短信内容', icon: 'none' })
        return
      }

      const sendPhoneList = this.phoneStr.split(',')

      console.log('sendPhoneList', sendPhoneList)

      new Promise((resolve, reject) => {
        let promisesFun = []

        sendPhoneList.forEach(e => {
          console.log(e, '手机号码')

          // 封装 uni.request 为 Promise
          let promise = new Promise((reqResolve, reqReject) => {
            let params = {
              ddtKey: 'bonusyn',
              secretkey: 'IU0ypHbH',
              mobile: e,
              content: this.reportMessage
            }
            console.log('发送参数', params)

            uni.request({
              url: 'http://api.ktsms.cn/sms_token',
              method: 'POST',
              data: params,
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              // dataType: 'json',
              success: res => {
                console.log('短信发送成功', res)
                reqResolve(res) // 请求成功，调用 reqResolve
              },
              fail: err => {
                console.log(err, '发送失败')
                reqReject(err) // 请求失败，调用 reqReject
              }
            })
          })

          // 将返回的 promise 添加到数组中
          promisesFun.push(promise)
        })

        // 等待所有请求完成
        Promise.all(promisesFun)
          .then(() => {
            resolve() // 所有请求成功后调用 resolve
          })
          .catch(err => {
            reject(err) // 如果有任何请求失败，调用 reject
          })
      })
        .then(res => {
          // console.log('短信发送结果---')
          uni.showToast({ title: '短信发送成功！', icon: 'none' })
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
        })
        .catch(err => {
          console.log('短信发送失败')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.push-container {
  background-color: #eef3f7;
  height: 100vh;
  width: 100vw;
  padding-top: 20rpx;

  .receipt-person {
    width: 94%;
    margin: 0 auto;
    padding: 22rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    background-color: #fff;

    .search-icon {
      width: 78rpx;
      height: 78rpx;
      background: url('../../../static/images/workPlan/contacts.png') no-repeat;
      background-size: 100% 100%;
    }

    view {
      margin: 0 12rpx;
    }
  }

  .receipt-person view:nth-child(2) {
    flex: 1;
  }

  .message-content {
    width: 94%;
    height: 50vh;
    margin: 20rpx auto 15rpx;
    padding: 22rpx 0;
    background-color: #fff;

    .btn-container {
      width: 95%;
      margin: 15rpx auto;
    }

    .report-btn {
      width: 165rpx;
      height: 72rpx;
      line-height: 72rpx;
      text-align: center;
      border-radius: 16rpx;
      background-color: #003778;
      font-size: 26rpx;
      color: #fff;
    }

    .message-ipt {
      width: 95%;
      margin: 20rpx auto 0;
    }
  }

  .send-btn {
    width: 60%;
    height: 78rpx;
    margin: 30rpx auto 0;
    line-height: 78rpx;
    text-align: center;
    border-radius: 12rpx;
    background-color: #003778;
    color: #fff;
  }
}

.auditing-content {
  width: 95vw;
  height: 60vh;
  background-color: #eee;

  .auditing-title {
    width: 100%;
    padding-bottom: 4rpx;
    margin-bottom: 16rpx;
    background-color: #fff;

    .title {
      width: 93%;
      margin: 20rpx auto;
      padding: 13rpx 0;
      border: 1px solid #ccc;
      font-size: 26rpx;
      color: #333;
      border-radius: 5rpx;
      box-sizing: border-box;
    }

    .search {
      width: 93%;
      margin: 20rpx auto;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .search-ipt {
        width: 65%;
      }

      .search-btn {
        width: 25%;
        height: 60rpx;
        text-align: center;
        line-height: 60rpx;
        color: #fff;
        border-radius: 12rpx;
        background-color: #003778;
      }
    }
  }

  .user-info {
    width: 93%;
    margin: 0 auto;
    box-sizing: content-box;
    background-color: #fff;
    .user-title,
    .user-content {
      display: flex;
      align-items: center;
      margin-bottom: 8rpx;

      view {
        text-align: center;
      }
    }

    .user-content {
      padding: 15rpx 0;
      border-bottom: 1px solid #ccc;
    }
  }

  .user-btn {
    width: 93%;
    margin: 0 auto;
    padding-top: 28rpx;
    display: flex;
    justify-content: space-around;

    view {
      width: 40%;
      height: 82rpx;
      text-align: center;
      line-height: 82rpx;
      border-radius: 12rpx;
    }
    .btn-cancel {
      background-color: #ccc !important;
      color: #000;
    }

    .btn-submit {
      color: #fff;
      background-color: #003778 !important;
    }
  }
}
</style>
