<!--我的考勤-详情-->
<template>
  <view class="main_box">
    <fui-segmented-control
        :values="optionTable"
        :current="(Number(currentIndex))"
        type="text"
        activeColor="#29d3b4"
        color="#fff"
        @click="segmented">
    </fui-segmented-control>

    <view class="main_section">
      <view>
        <!--全部-->
        <scroll-view
            class="section_1"
            v-if="currentIndex == '0'"
            scroll-y="true"
            :lower-threshold="lowerThreshold"
            @scrolltolower="loadMoreData"
            style="height: 80vh;"
        >
          <view class="ul">
            <view class="li"
                  v-for="(v,k) in tableList"
                  :key="k"
                  @click="openInfo(v)"
            >
              <view class="left">
<!--                <image src="http://www.firstui.cn:4000/vipdoc/img/img_logo.png" model="aspectFill"></image>-->
              </view>
              <view class="right">
                <view class="content">普通考勤</view>
                <view class="content">
                  {{v.status_name}}
                </view>
                <view class="content">
                  校区：{{v.campus_id_name}}
                </view>
                <view class="content">
                  备注：{{v.remarks || ''}}
                </view>
                <view class="content">
                  <text>{{v.attendance_date}} {{v.check_in_time}}</text>
                  <text v-if="v.check_out_time" style="padding: 0 20rpx">-</text>
                  <text v-if="v.check_out_time">{{v.attendance_date}} {{v.check_out_time}}</text>
                </view>
              </view>
            </view>
          </view>

        </scroll-view>

        <!--考勤-->
        <scroll-view
            class="section_1"
            v-if="currentIndex == '1'"
            scroll-y="true"
            :lower-threshold="lowerThreshold"
            @scrolltolower="loadMoreData"
            style="height: 80vh;"
        >
          <view class="ul">
            <view class="li"
                  v-for="(v,k) in tableList"
                  :key="k"
            >
              <view class="left">
                <!--                <image src="http://www.firstui.cn:4000/vipdoc/img/img_logo.png" model="aspectFill"></image>-->
              </view>
              <view class="right">
                <view class="content">普通考勤</view>
                <view class="content">
                  {{v.status_name}}
                </view>
                <view class="content">
                  校区：{{v.campus_id_name}}
                </view>
                <view class="content">
                  备注：{{v.remarks || ''}}
                </view>
                <view class="content">
                  <text>{{v.attendance_date}} {{v.check_in_time}}</text>
                  <text v-if="v.check_out_time" style="padding: 0 20rpx">-</text>
                  <text v-if="v.check_out_time">{{v.attendance_date}} {{v.check_out_time}}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <!--请假-->
        <scroll-view
            class="section_1"
            v-if="currentIndex == '2'"
            scroll-y="true"
            :lower-threshold="lowerThreshold"
            @scrolltolower="loadMoreData"
            style="height: 80vh;"
        >
          <view class="ul">
            <view class="li"
                  v-for="(v,k) in tableList"
                  :key="k"
            >
              <view class="left">
                <!--                <image src="http://www.firstui.cn:4000/vipdoc/img/img_logo.png" model="aspectFill"></image>-->
              </view>
              <view class="right">
                <view class="content">普通考勤</view>
                <view class="content">
                  {{v.status_name}}
                </view>
                <view class="content">
                  校区：{{v.campus_id_name}}
                </view>
                <view class="content">
                  备注：{{v.remarks || ''}}
                </view>
                <view class="content">
                  <text>{{v.attendance_date}} {{v.check_in_time}}</text>
                  <text v-if="v.check_out_time" style="padding: 0 20rpx">-</text>
                  <text v-if="v.check_out_time">{{v.attendance_date}} {{v.check_out_time}}</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

      </view>


      <view class="section_btn">
        <!--打卡按钮-->
        <view class="btn" style="background-color: #20CAAFFF;" @click="openSignInShow('present')">打卡</view>

        <!--请假按钮-->
        <view class="btn" style="background-color: #ffb703;" @click="openSignInShow('leave')">请假</view>

        <!--签退按钮-->
        <view class="btn" style="background-color: #465cff;" @click="openSignInShow('sign_out')">签退</view>
      </view>

    </view>

    <!--打卡提示框-->
    <fui-modal :buttons="[]" width="600" :show="signIn_show">
      <text class="fui-title">{{signIn_title}}</text>
      <text class="fui-descr">{{signIn_content}}</text>
      <fui-form class="form-section" ref="form" top="0" :model="formData" :show="false">
        <view class="input-style">
          <!--校区选择-->
          <fui-form-item
              label="选择校区"
              asterisk
              asteriskPosition="right"
              labelSize='26'
              prop=""
              background='#fff'
              labelColor='#000'
              :bottomBorder='true'
          >
            <view class="input-title" style="margin-right:14rpx;">
              <view
                  class="input-title"
                  style="margin-right:14rpx;"
                  @click="openCicker()">
                {{ (formData.campus_id) ? formData.campus_id_name : '点击选择' }}
              </view>
            </view>
          </fui-form-item>
          <!--备注-->
          <fui-form-item
              v-if="formData.status == 'leave'"
              label="备注"
              labelSize='26'
              prop=""
              background='#fff'
              labelColor='#000'
              :bottomBorder='true'
          >
            <view class="input-title" style="margin-right:14rpx;">
              <fui-input
                  :borderBottom="false"
                  :padding="[0]"
                  placeholder="请输入备注"
                  v-model="formData.remarks"
                  backgroundColor="#fff"
                  size="26"
                  color="#000"
              ></fui-input>
            </view>
          </fui-form-item>
        </view>
        <view class="button_box">
          <fui-button background="#fff" color="#414141" borderColor="#465CFF" btnSize="small" @click="closeSignInShow">取消</fui-button>
          <fui-button background="#fff" color="#465CFF" borderColor="#465CFF" btnSize="small" @click="clickSignIn({index:1})">确定</fui-button>

        </view>
      </fui-form>
      <view class="fui-icon__close" @tap="closeSignInShow">
        <fui-icon name="close" color="#B2B2B2" :size="48"></fui-icon>
      </view>
    </fui-modal>


    <!--详情提示框-->
    <fui-modal :buttons="[]" width="600" :show="info_show">
      <text class="fui-title">详情</text>
      <view class="info_ul">
        <view class="li">
          <view class="title">考勤状态：</view>
          <view class="content">{{info_data.status_name}}</view>
        </view>
        <view class="li">
          <view class="title">考勤日期：</view>
          <view class="content">
            <text style="padding: 0;">{{info_data.attendance_date}}</text>
            <text v-if="info_data.status == 'present'">{{info_data.check_in_time}}</text>
            <text v-if="info_data.status == 'present' && (info_data.check_out_time || '')">-</text>
            <text v-if="info_data.status == 'present' && (info_data.check_out_time || '')">{{info_data.check_out_time || ''}}</text>

            <text v-if="info_data.status == 'present' && !(info_data.check_out_time || '')">(未签退)</text>
          </view>
        </view>
        <view class="li">
          <view class="title">校区名称：</view>
          <view class="content">{{info_data.campus_id_name || ''}}</view>
        </view>
        <view class="li">
          <view class="title">备注：</view>
          <view class="content">{{info_data.remarks || ''}}</view>
        </view>
        <view class="map_section" v-if="info_data.id && info_data.latitude">
          <view class="title">地图：</view>
          <view class="map">
            <map
                v-if="info_data.latitude"
                :id="`shopMap_${info_data.id}`"
                :longitude="info_data.longitude"
                :latitude="info_data.latitude"
                :markers="getMarkers(info_data.id,info_data)"
                :scale="16"
                :show-location="false"
                style="width: 100%; height: 400rpx;"
            ></map>
          </view>
        </view>
      </view>
      <view class="fui-icon__close" @tap="closeInfoShow">
        <fui-icon name="close" color="#B2B2B2" :size="48"></fui-icon>
      </view>
    </fui-modal>




    <!-- 选择器 -->
    <fui-picker
        :linkage='picker_linkage'
        :options="picker_options"
        :layer="1"
        :show="picker_show"
        @change="changeCicker"
        @cancel="cancelCicker">
    </fui-picker>

  </view>
</template>

<script>
import apiRoute from '@/api/apiRoute.js';
import commonApi from '@/api/common.js';
import marketApi from '@/api/market.js';
import AQTabber from "@/components/AQ/AQTabber.vue"


export default {
  components: {
    AQTabber,
  },
  data() {
    return {
      userType: '', //用户类型|1=教练,2=销售
      //tab切换
      optionTable: [
        {
          id: 0,
          name: '全部',
          value:[]
        },
        {
          id: 1,
          name: '考勤',
          value:['present']
        },
        {
          id: 2,
          name: '请假',
          value:['leave']
        }
      ],
      currentIndex:0,

      userInfo:{},//用户信息


      loading:false,//加载状态
      lowerThreshold: 100,//距离底部多远触发
      isReachedBottom: false,//防止重复加载|true=不可加载|false=可加载

      //筛选条件
      filteredData:{
        page:1,//当前页码
        limit:10,//每页返回数据条数
        total:10,//数据总条数
        status_arr:[]//考勤状态: present-出勤, absent-缺勤, late-迟到, leave_early-早退,leave-请假
      },
      tableList:[],//表格数据

      //请假-打卡-签退表单
      formData:{
        campus_id:'',//校区ID
        campus_id_name:'',//校区ID
        status:'',//考勤状态: present-出勤, absent-缺勤, late-迟到, leave_early-早退,leave-请假,sign_out-签退
        remarks:'',//备注
        attendance_date:'',//请假/打卡日期
        longitude:'',//经度
        latitude:'',//纬度
      },

      //请假提示框相关
      show:false,//是否展示
      content:'',//请假提示语

      //打开签到相关
      signIn_show:false,
      signIn_title:'',//打卡签到标题
      signIn_content:'',//打卡签到提示语


      //下拉选择器相关
      picker_input_name:'',//下拉组件的input_name
      picker_show:false,//下拉组件是否展示
      picker_linkage:true,//选择器是否为联动选择
      picker_options:[
        // {
        //   text:'张三',
        //   value:'1'
        // },
      ],//选择器可选值列表

      //详情模态窗
      info_show:false,//是否展示|true=是,false=否
      info_data:{},//详情数据
    }
  },
  onLoad(options) {},
  onShow(){
    this.init()//初始化
  },
  methods: {
    //初始化
    async init(){
      // 条件编译-小程序
      //  #ifdef MP-WEIXIN
      uni.authorize({
        scope: 'scope.userLocation',
        success() {
          // 用户已授权

        },
        fail() {
          uni.showToast({
            title: '请开启定位权限',
            icon: 'none'
          });
          return
        }
      });
      // #endif
      this.userType = uni.getStorageSync('userType')
      this.getCurrentDate()//获取并格式化当前日期
      await this.getUserInfo()//获取用户信息
      // await this.getList();
      this.getList();
    },

    //获取用户信息
    async getUserInfo(){
      let res = await apiRoute.getPersonnelInfo({})
      if (res.code != 1) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }

      this.userInfo = res.data
      this.picker_options = []
      res.data.cameus_dept_arr.forEach((v,k)=>{
        this.picker_options.push({
          text: v.campus_id_name,
          value: v.campus_id
        })
      })
      console.log(123123,this.picker_options)
    },

    // 获取并格式化当前日期
    getCurrentDate() {
      let now = new Date();
      let year = now.getFullYear();
      let month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
      let day = String(now.getDate()).padStart(2, '0');


      let res = `${year}-${month}-${day}`



      this.formData.attendance_date = res
    },

    //切换tag列表
    async segmented(e) {
      console.log(e)
      this.currentIndex = e.id
      //重置为第一页
      await this.resetFilteredData()


      //e.id|0全部 1考勤 2请假
      let status = e.id
      let status_arr = []
      switch (status) {
        case 1:
          status_arr = ['present']
          break;
        case 2:
          status_arr = ['leave']
          break;
      }

      this.filteredData.status_arr = status_arr
      await this.getList()
    },

    //加载更多(下一页)
    loadMoreData() {
      //判断是否加载
      if (!this.isReachedBottom) {
        this.isReachedBottom = true;//设置为不可请求状态
        this.getList();
      }
    },
    //重置为第一页
    async resetFilteredData() {
      this.isReachedBottom = false; // 重置状态，以便下次触发加载更多

      this.filteredData.page = 1//当前页码
      this.filteredData.limit = 10//每页返回数据条数
      this.filteredData.total = 10//数据总条数
    },
    //获取列表
    async getList(){
      this.loading = true

      let data = {...this.filteredData}

      //判断是否还有数据
      if(this.filteredData.page * this.filteredData.limit > this.filteredData.total){
        this.loading = false
        uni.showToast({
          title: '暂无更多',
          icon: 'none'
        })
        return
      }

      if(data.page == 1){
        this.tableList = []
      }

      let res = await apiRoute.common_attendanceIndex(data)
      this.loading = false
      this.isReachedBottom = false;
      if (res.code != 1){
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }

      this.tableList = this.tableList.concat(res.data.data); // 使用 concat 方法 将新数据追加到数组中

      console.log('列表',res.data.data)
      this.filteredData.total = res.data.total
      this.filteredData.page++
    },

    //打开请假提示框
    openShow(){
      this.show = true
    },
    //关闭请假提示框
    closeShow(){
      this.show = false
    },
    //点击确认请假按钮
    async onClick(e){
      console.log('xxx',e)
      if(e.index == 0){
        //取消按钮
        this.closeShow()
      }else{
        if(!this.formData.campus_id){
          uni.showToast({
            title: '请选择校区',
            icon: 'none'
          })
          return
        }
        //确认按钮
        this.formData.status='absent'//考勤类型|present-出勤, absent-缺勤
        await this.submitFormData()
      }
    },


    //打卡签到相关
    //显示打卡弹窗
    openSignInShow(status){

      this.formData.status = status

      switch (status){
        case 'present':
          this.signIn_title = `是否确认打卡?`
          this.signIn_content = `${this.formData.attendance_date} 是否确认打卡?`
          break;
        case 'leave':
          this.signIn_title = `是否确认请假?`
          this.signIn_content = `${this.formData.attendance_date} 是否确认请假?`
          break;
        case 'sign_out':
          this.signIn_title = `是否确认签退?`
          this.signIn_content = `${this.formData.attendance_date} 是否确认签退?`
          break;
      }

      //重置的数据
      this.formData.campus_id = ''
      this.formData.campus_id_name = ''
      this.formData.remarks = ''
      this.formData.longitude = ''
      this.formData.latitude = ''

      this.getlocation()//获取经纬度

    },
    //关闭打卡弹窗
    closeSignInShow(){
      this.signIn_show = false
    },
    //监听-打卡签到回调
    async clickSignIn(e){
      console.log('xxx',e)
      if(e.index == 0){
        //取消按钮
        this.closeSignInShow()
      }else{
        if(!this.formData.campus_id){
          uni.showToast({
            title: '请选择校区',
            icon: 'none'
          })
          return
        }
        await this.submitFormData()
      }
    },

    //下拉选择器-校区选择器
    openCicker(e){
      // 使用 nextTick 确保数据更新后再打开 picker
      this.$nextTick(() => {
        this.picker_show = true
      })
    },
    //监听-下拉选择器
    changeCicker(e) {
      console.log('监听-下拉选择器', e)
      this.formData.campus_id = e.value
      this.formData.campus_id_name = e.text
      this.cancelCicker()
    },
    //关闭下拉选择器
    cancelCicker() {
      this.picker_show = false
    },


    //获取用户经纬度
    async getLocation_COPY() {
      try {
        const location = await new Promise((resolve, reject) => {
          uni.getLocation({
            type: 'wgs84', // 坐标类型，wgs84 返回 gps 坐标，gcj02 返回国测局坐标
            success: (res) => {
              console.log('当前位置的经度：' + res.longitude);
              console.log('当前位置的纬度：' + res.latitude);
              this.longitude = res.longitude
              this.latitude = res.latitude
              resolve(res);
            },
            fail: (err) => {
              reject(err);
            }
          });
        });

        console.log('纬度:', location.latitude); // 纬度
        console.log('经度:', location.longitude); // 经度

        // 在这里可以对获取到的经纬度进行操作，比如保存到 data 中
        this.formData.latitude = location.latitude;
        this.formData.longitude = location.longitude;

        uni.showToast({
          title: `定位-${this.formData.latitude}`,
          icon: 'none'
        });

        // uni.showToast({
        //   title: '位置获取成功',
        //   icon: 'success'
        // });
      } catch (error) {
        uni.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
        console.error('获取位置失败:', error);
      }
    },

    getlocation() {
      uni.getLocation({
        type: 'gcj02',//腾讯坐标系
        isHighAccuracy: true,//开启高精度定位
        success: (res) => {
          console.log('当前位置的经度：' + res.longitude);
          console.log('当前位置的纬度：' + res.latitude);
          this.formData.longitude = res.longitude
          this.formData.latitude = res.latitude
          // 调用后端接口根据得到的经纬度获取地址
          console.log(res, "根据经纬度获取地址");
          this.signIn_show = true//展示弹层
        },
        // 若用户点击拒绝获取位置则弹出提示
        fail: (err) => {
          uni.showModal({
            content: '检测到您没打开获取位置功能权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                uni.openSetting({
                  success: (res) => {
                    uni.showToast({
                      title: '授权后请重新打开此页面',
                      icon: 'none'
                    })
                  },
                  fail: (err) => {
                    console.log(err)
                  }
                })
              } else {
                uni.showToast({
                  title: '获取地理位置授权失败',
                  icon: 'none',
                  success: () => {
                    // 返回上一页
                    setTimeout(() => {
                      uni.showToast({
                        title: "请开启手机定位后再试",
                        icon: 'none'
                      })
                      // uni.navigateBack({
                      //   delta: 1
                      // })
                    }, 500)
                  }
                })
              }
            }
          })
        },
      })
    },

    //发起请假/打卡请求
    async submitFormData() {
      this.closeSignInShow()

      let param = {...this.formData}
      let res = await apiRoute.common_attendanceEdit(param)
      if (res.code != 1) {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
        return
      }

      uni.showToast({
        title: '操作成功',
        icon: 'success'
      })

      //延迟1s执行
      setTimeout(() => {
        this.segmented({id:0})//初始化
      }, 1500)
    },

    //打开详情
    openInfo(item){


      let coordinate_arr= []
      if (item.coordinate){
        coordinate_arr = item.coordinate.split(',')
      }
      item.longitude = Number(coordinate_arr[0] || 0)//经度
       item.latitude = Number(coordinate_arr[1] || 0)//纬度


      // item.latitude = 18.252865
      // item.longitude = 109.511709

      this.info_data = {...item};
      console.log('详情',this.info_data)
      // 设置 info_data 并打开弹窗
      this.info_show = true


    },
    //关闭详情
    closeInfoShow(){
        this.info_show = false
    },

    // 获取标记点
    getMarkers(id,item) {
      console.log('获取标记点',item)
      let data = {
        id: Number(id),
        // 设置标记点的纬度坐标
        latitude: Number(item.latitude),
        // 设置标记点的经度坐标
        longitude: Number(item.longitude),

        // name: item.campus_address,
        iconPath: '/static/icon-img/ding_wei.png',
        width: 30,
        height: 30
      }
      console.log(88888,data)
      return [data];
    },

  }
}
</script>

<style lang="less" scoped>

.main_box{
  background: #292929 ;
}

//自定义导航栏
.navbar_section{
  display: flex;
  justify-content: center;
  align-items: center;
  background: #29d3b4;
  .title{
    padding: 40rpx 0rpx;

    /* 小程序端样式 */
    // #ifdef MP-WEIXIN
    padding: 80rpx 0rpx;
    // #endif

    font-size: 30rpx;
    color: #315d55;
  }
}

.main_section{
  min-height: 100vh;
  background: #292929 100%;
  padding: 0 24rpx;
  padding-top: 32rpx;
  padding-bottom: 150rpx;
  font-size: 28rpx;
  .section_1{
    color: #fff;
    font-size: 28rpx;
    .ul{
      margin-top: 23rpx;
      display: flex;
      flex-direction: column;
      gap: 24rpx;
      .li{
        border: 1px solid #5f5f5f;
        border-radius: 15rpx;
        padding: 20rpx 0;
        display: flex;
        align-items: center;
        gap: 43rpx;
        .left{
          image{
            width: 174rpx;
            height: 174rpx;
            border-radius: 24rpx;
            background-color: #333333;
          }
        }
        .right{
          display: flex;
          flex-direction: column;
          gap: 18rpx;
          .content{
            font-size: 24rpx;
          }
          .content:nth-child(1){
            font-size: 28rpx;
          }
        }
      }
    }
    .title_box{
      margin-top: 46rpx;
      font-size: 28rpx;
    }
    .subhead_box{
      margin-top: 22rpx;
      font-size: 24rpx;
    }
  }

  .section_btn{
    display: flex;
    justify-content: center;
    display: flex;
    justify-content: space-between;
    .btn{
      width: 30%;
      height: 64rpx;
      line-height: 64rpx;
      border-radius: 8rpx;
      color: rgba(255,255,255,1);
      font-size: 28rpx;
      text-align: center;
    }
  }

}




//请假模态框
.fui-title {
  font-size: 32rpx;
  padding-top: 24rpx;
}

.fui-descr {
  font-size: 24rpx;
  color: #B2B2B2;
  padding-top: 12rpx;
  padding-bottom: 48rpx;
}

.fui-icon__close {
  position: absolute;
  right: 24rpx;
  top: 20rpx;
}



.form-section{

  .input-style {
    text-align: right !important;
  }
  .button_box{
    margin-top: 30rpx;
    padding: 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
  }
}

//详情
.info_ul{
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  width: 100%;
  .li{
    display: flex;
    .title{
      min-width: 140rpx;
    }
    .content{
      word-break: break-all;
      text{
        padding:0 10rpx;
      }
    }
  }
  .map_section{
    display: flex;
    flex-direction: column;
    .title{
      width: 130rpx;
    }
    .map{
      border: 1px solid #8b8b8b;
      margin-top: 10rpx;
      width: 100%;
    }
  }
}

</style>