<template>
  <view class="wrap"
    v-if="!isLoading">
    <uni-forms ref="baseForm"
      :model="baseFormData">
      <template v-if="!onWorkRecord.id">
        <uni-forms-item label="范围选择"
          required>
          <uni-data-checkbox v-model="baseFormData.type"
            :localdata="typeList"
            @change="changeFn" />
        </uni-forms-item>
        <uni-forms-item label="选择店铺"
          required>
          <uni-combox :candidates="planList"
            placeholder="请选择店铺"
            v-model="plan"
            emptyTips="无匹配项，切换全国尝试"
            @input="planInput"></uni-combox>
        </uni-forms-item>
      </template>
      <template v-else>
        <uni-forms-item label="当前店铺"
          required>
          <view>{{ plan }}</view>
        </uni-forms-item>
      </template>
      <uni-forms-item label="当前位置">
        <view class="address">
          {{ address }}
          <uni-icons type="reload"
            class="u-icon"
            size="16"
            ref="myIcon"
            style="margin-left: 20px;"
            @click="refreshAdd">
            刷新
          </uni-icons>
        </view>
      </uni-forms-item>
    </uni-forms>
    <div class="button_wrap">
      <div class="line">
        <van-button class="btn_item"
          type="primary"
          @click="attendanceClickFn(1)"
          v-if="!onWorkRecord.clockInTime">上班卡</van-button>
        <view class="clock_item"
          v-else>
          <van-image width="250rpx"
            height="250rpx"
            :src="onWorkRecord.clockInPhoto"
            fit="cover"
            round />
          <view class="mark">
            <view class="mark_text">上班卡-已打</view>
            <view class="mark_time">{{ onWorkRecord.clockInTime }}</view>
          </view>
        </view>
      </div>
      <div class="line">
        <van-button class="btn_item"
          type="primary"
          v-if="onWorkRecord.clockInTime && !onWorkRecord.noonClockOutTime"
          @click="attendanceClickFn(2)">午休卡</van-button>
        <view class="clock_item"
          v-else-if="onWorkRecord.noonClockOutTime">
          <van-image width="250rpx"
            height="250rpx"
            :src="onWorkRecord.noonClockOutPhoto"
            fit="cover"
            round />
          <view class="mark">
            <view class="mark_text">午休卡-已打</view>
            <view class="mark_time">{{ onWorkRecord.noonClockOutTime }}</view>
          </view>
        </view>
        <van-button class="btn_item"
          type="primary"
          v-if="onWorkRecord.noonClockOutTime && !onWorkRecord.noonClockInTime"
          @click="attendanceClickFn(3)">午-上班卡</van-button>
        <view class="clock_item"
          v-else-if="onWorkRecord.noonClockInTime">
          <van-image width="250rpx"
            height="250rpx"
            :src="onWorkRecord.noonClockInPhoto"
            fit="cover"
            round />
          <view class="mark">
            <view class="mark_text">午休卡-已打</view>
            <view class="mark_time">{{ onWorkRecord.noonClockInTime }}</view>
          </view>
        </view>
      </div>
      <div class="line">
        <van-button class="btn_item"
          type="primary"
          v-if="onWorkRecord.clockInTime && !onWorkRecord.clockOutTime"
          @click="attendanceClickFn(4)">下班卡</van-button>
        <view class="clock_item"
          v-else-if="onWorkRecord.clockOutTime">
          <van-image width="250rpx"
            height="250rpx"
            :src="onWorkRecord.clockOutPhoto"
            fit="cover"
            round />
          <view class="mark">
            <view class="mark_text">午休卡-已打</view>
            <view class="mark_time">{{ onWorkRecord.clockOutTime }}</view>
          </view>
        </view>
      </div>
    </div>
    <uni-popup ref="popup"
      type="bottom"
      border-radius="10px 10px 0 0">底部弹出 Popup 自定义圆角</uni-popup>
  </view>
</template>

<script>

import { getAttendanceDetailAPI, addAttendanceAPI, getAttendanceListAPI, getProStoreAPI, getPlanListAPI, getOnWorkCardAPI, createOnWorkPlanAPI, getOnWorkRecordAPI } from '@/api'
import { checkStartLessEndTime, parseTime, isSameDay, zeroTo24, checkTimeIsBetween } from '@/utils/common'
import { uploadFile } from '@/api/common/upload'
import QQMapWX from '../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.js'
// var QQMapWX = require('../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.js');
import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
export default {
  data() {
    return {
      isLoading: true,
      baseFormData: {
        type: 2
      },
      // 计划范围选择
      typeList: [{
        value: 0,
        text: '全国'
      }],
      // 计划完整列表
      oriPlanList: [],
      // 计划名称-列表
      planList: [],
      // 计划 id
      plan: '',
      // 促销员地址
      address: '',
      // 促销员省市区对象
      addressObj: {
        province: '',
        city: '',
        area: ''
      },
      lat: '', // 纬度
      lng: '', // 经度
      // 促销员打卡记录
      onWorkRecord: {},
    }
  },
  async created() {
    this.isLoading = true
    this.phone = storage.get(constant.loginPhone)
    await this.getAddress()
    await this.getPlanListFn()
    this.getOnWorkRecordFn()
  },
  methods: {
    // ************************ //
    // 获取计划列表
    async getPlanListFn() {
      // 根据单选框范围，决定带什么参数查询
      const res = await getPlanListAPI({
        area: this.baseFormData.type === 2 ? this.typeList[this.baseFormData.type]?.text : '',
        city: this.baseFormData.type === 1 ? this.typeList[this.baseFormData.type]?.text : '',
        storeNameLike: this.baseFormData.storeName
      })
      this.oriPlanList = res.data
      this.planList = res.data.map(item => {
        return item.storeName
      })
    },
    // 获取地理位置
    async getAddress() {
      return new Promise((resolve, reject) => {
        var _this = this;
        var qqmapsdk = new QQMapWX({
          key: config.mapKey
        });
        qqmapsdk.reverseGeocoder({
          success: function (ress) {
            console.log('地址', ress)
            const { result: { ad_info: { province, city, district, location: { lat, lng } }, formatted_addresses: { recommend } } } = ress
            _this.address = recommend;
            _this.lat = lat
            _this.lng = lng
            _this.typeList = [{
              value: 0,
              text: '全国'
            }, {
              value: 1,
              text: city
            }, {
              value: 2,
              text: district
            }]
            _this.addressObj = {
              province,
              city,
              area: district
            }
            resolve()
          },
          fail: function (error) {
            console.error(error);
          },
          complete: function (res) {
            // console.log(res);
          }
        })
      })
    },
    // 所选区域切换
    async changeFn() {
      this.baseFormData.storeName = ''
      this.plan = ''
      this.getPlanListFn()
    },
    // 计划输入切换
    async planInput(str) {
      this.baseFormData.storeName = str
      this.getPlanListFn()
    },
    // 考勤打卡（type 代表打卡类型：1 上班，2 午休下班，3 午休上班，4 下班）
    async attendanceClickFn(type) {
      // 从计划列表里，找到计划的 id
      const planObj = this.oriPlanList.find(item => {
        return item.storeName === this.plan
      })
      if (!planObj && !this.onWorkRecord.planId) {
        this.$modal.msgError('请选择计划')
        return
      }

      const photoUrl = await this.pickerPhoto(type) // 拍照

      const { id, name } = this.$store.getters.user
      // 配置考勤参数
      const attObj = {
        temporaryId: id, // 促销员 ID
        temporaryName: name, // 促销员姓名
        planId: planObj?.id || this.onWorkRecord.planId, // 促销计划 ID
        clockType: type, // 打卡类型
        id: this.onWorkRecord.id,
        clockAddress: this.address, // 打卡地址
        clockCoordinates: `${this.lng},${this.lat}`, // 打卡坐标
        clockPhoto: photoUrl, // 打卡照片地址
        clockProvince: this.addressObj.province, // 打卡省份
        clockCity: this.addressObj.city, // 城市
        clockArea: this.addressObj.area, // 区域
      }

      try {
        // 打卡
        const res = await getOnWorkCardAPI(attObj)
        if (type === 1) {
          // 创建上报记录
          await this.createOnWorkPlanFn()
        }
        this.$modal.msgSuccess('打卡成功')
        console.log('考勤打卡记录', res)
      } catch (err) {
        this.$modal.msgError(err.msg)
      }

      // 打卡记录
      this.getOnWorkRecordFn()
    },
    // 刷新当前位置
    async refreshAdd() {
      this.$modal.loading('刷新中...')
      await this.$store.dispatch('GetLocation')
      this.getAddress()
      // 弹窗提示并自动关闭
      this.$modal.closeLoading()
      this.$modal.msgSuccess('刷新成功')
    },
    // 拍摄照片
    async pickerPhoto(type) {
      return new Promise((resolve, reject) => {
        uni.chooseImage({
          count: 1, // 默认9, 设置图片的最大选择数，设置为1表示只选择一张图片
          sizeType: ['original'], // original 原图，compressed 压缩图，可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: async (res) => {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            const tempFilePaths = res.tempFilePaths;
            console.log(tempFilePaths[0]); // 输出图片路径
            const result = await uploadFile(`planAndPhoto/${this.phone}/clock/${type}.png`, tempFilePaths[0])
            resolve(result)
          }
        });
      })
    },
    // 创建活动上报记录
    async createOnWorkPlanFn() {
      const res = await createOnWorkPlanAPI({
        temporaryId: this.$store.getters.user.id, // 促销员 ID
        temporaryName: this.$store.getters.user.name, // 促销员姓名
        // "tgscPhotoUrls":[],
        // "tgscChangePhotoUrls":[],
        // "tghdPhotoUrls":[],
        // "tghdChangePhotoUrls":[],
        // "tgcjPhotoUrls":[],
        // "tgcjChangePhotoUrls":[]
      })
      console.log(res)
    },
    // 获取促销员任务列表
    async getOnWorkRecordFn() {
      const res = await getOnWorkRecordAPI(this.$store.getters.user.id)
      if (!res.data) return this.isLoading = false
      this.planList = [res.data.storeName]
      this.plan = res.data.storeName
      // 上班打卡时间格式化成时分秒
      if (res.data.clockInTime) {
        res.data.clockInTime = parseTime(res.data.clockInTime, '{h}:{m}:{s}')
      }
      if (res.data.noonClockOutTime) {
        res.data.noonClockOutTime = parseTime(res.data.noonClockOutTime, '{h}:{m}:{s}')
      }
      if (res.data.noonClockInTime) {
        res.data.noonClockInTime = parseTime(res.data.noonClockInTime, '{h}:{m}:{s}')
      }
      if (res.data.clockOutTime) {
        res.data.clockOutTime = parseTime(res.data.clockOutTime, '{h}:{m}:{s}')
      }
      this.onWorkRecord = res.data
      this.isLoading = false
    }
  }
}
</script>

<style scoped
  lang="scss">
  ::v-deep .uni-forms {
    padding: 10px;

    .uni-forms-item__label {
      padding: 0;
    }

    .uni-forms-item {
      align-items: center;
    }

    .uni-forms-item__content {
      margin-left: 20px;
    }
  }

  /********************************** */
  .wrap {
    background-color: white;
    min-height: 100vh;
    display: flex;
    flex-direction: column;

    .u-icon {
      transition: all 2s;
    }

    .button_wrap {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 50rpx;
      padding: 0 0 50rpx;
      flex: 1;

      .line {
        display: flex;
        gap: 50rpx;
      }

      .btn_item {
        ::v-deep button {
          width: 250rpx;
          height: 250rpx;
          border-radius: 50%;
        }

        ::v-deep .van-button--primary {
          background-color: #69b0fb;
          border: none;
        }
      }

      .clock_item {
        width: 250rpx;
        height: 250rpx;
        border-radius: 50%;
        position: relative;

        .mark {
          border-radius: 50%;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: 2;
          background-color: rgba(0, 0, 0, 0.5);
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;
          color: white;
          flex-direction: column;

          .mark_time {
            font-size: 24rpx;
          }
        }

      }
    }
  }
</style>