<template>
  <view class="home">
    <view class="nav">
      <view :style="{ paddingTop }">
        <view class="title" :style="[{ height }, { lineHeight: height }]">
          <view class="back" @click="goBack()">
            <u-icon name="arrow-left" color="#ffffff" size="22"></u-icon>
          </view>
          <text>打卡</text>
        </view>
      </view>
    </view>
    <view class="main">
      <view class="main-header">
        <view class="user-info">
          <image class="user-img" src="@/static/images/user.jpg" mode="scaleToFill" />
          <view class="info flex1 flex-column flex_1">
            <u-text :lines="1" size="32rpx" :bold="true" :text="nickName"></u-text>
            <u-text :lines="1" size="24rpx" :text="postName"></u-text>
          </view>
        </view>
        <view class="more" @click="showCheckList">
          <u-icon name="order" size="60rpx"></u-icon>
          <u-text :lines="1" size="24rpx" text="打卡记录"></u-text>
        </view>
      </view>
      <view class="main-form" v-if="!showList">
        <u-form :model="form" :rules="rules" ref="form" label-width="0">
          <u-form-item prop="punchVal" borderBottom customStyle="padding:40rpx 0 30rpx" @click="showCheckType = true">
            <view class="form-label flex_l">
              <view class="label-tag"></view>
              打卡类型
            </view>
            <u-input
              :readonly="true"
              placeholder="请选择销售模式"
              v-model="form.punchVal"
              border="none"
              suffixIcon="arrow-down"
              suffixIconStyle="color:#CDCDCD"
              clearable
              customStyle="padding: 0 30rpx 0 12rpx"></u-input>
          </u-form-item>
          <u-form-item
            prop="targetName"
            borderBottom
            customStyle="padding:40rpx 0 30rpx"
            v-if="form.punchType > 10"
            @click="openSelectUser()">
            <view class="form-label flex_l">
              <view class="label-tag"></view>
              {{ selectLable(form.punchType) }}
            </view>
            <u-input
              :readonly="true"
              :placeholder="`请选择${selectLable(form.punchType)}`"
              v-model="form.targetName"
              border="none"
              suffixIcon="arrow-down"
              suffixIconStyle="color:#CDCDCD"
              clearable
              customStyle="padding: 0 30rpx 0 12rpx"></u-input>
          </u-form-item>
          <!-- 合作伙伴联系人 -->
          <u-form-item
            prop="partnerContactName"
            borderBottom
            customStyle="padding:40rpx 0 30rpx"
            v-if="form.punchType == 50 && form.targetId"
            @click="openPartnersConcat()">
            <view class="form-label flex_l">
              合作伙伴联系人
            </view>
            <u-input
              :readonly="true"
              placeholder="请选择合作伙伴联系人"
              v-model="form.partnerContactName"
              border="none"
              suffixIcon="arrow-down"
              suffixIconStyle="color:#CDCDCD"
              clearable
              customStyle="padding: 0 30rpx 0 12rpx"></u-input>
          </u-form-item>
          <!-- END -->
        </u-form>
      </view>
      <view class="main-container">
        <template v-if="!showList">
          <view class="btn" @click="checkIn">打卡</view>
          <view class="location">
            <u-text @click="getLocation" :lines="1" :block="true" align="center" size="32rpx" :text="address"></u-text>
            <u-loading-icon mode="circle" size="24rpx" :show="show"></u-loading-icon>
          </view>
        </template>
        <u-list height="calc(100vh - 410rpx)" @scrolltolower="scrolltolower" v-else>
          <u-list-item v-for="(item, index) in checkList" :key="index">
            <u-cell :title="item.punchTime" :label="item.punchLocation"></u-cell>
          </u-list-item>
        </u-list>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <!-- <uni-file-picker file-mediatype="all" v-model="imageValue" @select="select" @progress="progress" @success="success"
      @fail="fail" ref="upload" limit="1">
      <view class="upload-btn">
        <u-icon name="plus-circle-fill" color="blue" size="28"></u-icon>
      </view>
    </uni-file-picker> -->
    <!-- 打卡类型 -->
    <u-picker
      :show="showCheckType"
      :columns="[checkTypeColumns]"
      keyName="value"
      @cancel="showCheckType = false"
      @confirm="pickCheckType"></u-picker>
    <!-- 选择经销商 -->
    <select-dealer ref="dealer" :distrId="form.punchType" dist @close="closeDealer($event)"></select-dealer>
    <!-- 选择客户 -->
    <select-customer ref="cust" @close="closeCust($event)"></select-customer>
    <!-- 选择合作伙伴 -->
    <select-partners ref="partners" @close="closePartners($event)"></select-partners>
    <select-partners-concat
      ref="partnersConcat"
      :queryParams="{ partnerId: form.targetId }"
      @close="closePartnersConcat($event)"></select-partners-concat>
    <u-notify ref="uNotify"></u-notify>
  </view>
</template>

<script>
  import { mapGetters } from 'vuex'
  import to from 'await-to-js'
  import api from '@/api/system'
  import SelectDealer from 'components/SelectDealer'
  import SelectCustomer from 'components/SelectCustomer'
  import SelectPartners from 'components/SelectPartners'
  import SelectPartnersConcat from 'components/SelectPartnersConcat'
  export default {
    components: {
      SelectDealer,
      SelectCustomer,
      SelectPartners,
      SelectPartnersConcat,
    },
    data() {
      return {
        height: '',
        paddingTop: '',
        address: '获取定位',
        showCheckType: false,
        form: {
          targetId: undefined, //经销商/代理商ID
          targetName: undefined, //经销商/代理商名称
          punchType: '', //打卡类型
          punchVal: '',
          punchLat: 0,
          punchLng: 0,
          punchLocation: '',
          punchImg: '',
          partnerContactId: null,
          partnerContactName: null,
        },
        show: false,
        imageValue: [],
        showList: false,
        checkList: [],
        queryForm: {
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        checkTypeColumns: [
          {
            key: '10',
            value: '居家',
          },
          {
            key: '20',
            value: '客户',
          },
          {
            key: '30',
            value: '经销商',
          },
          { key: '40', value: '代理商' },
          { key: '50', value: '合作伙伴' },
        ],
        rules: {
          punchVal: [
            {
              required: true,
              trigger: ['blur', 'change'],
              message: '请选择打卡类型',
            },
          ],
          targetName: [
            {
              required: true,
              trigger: ['blur', 'change'],
              message: `请选择用户`,
            },
          ],
        },
      }
    },
    computed: {
      ...mapGetters(['nickName', 'postName']),
    },
    created() {
      this.getLocation()
      const navData = uni.getMenuButtonBoundingClientRect()
      this.height = navData.height + 'px'
      this.paddingTop = navData.top + 'px'
    },
    watch: {
      'form.punchType'(val) {
        this.form.targetId = undefined
        this.form.targetName = undefined
        this.form.partnerContactId = null
        this.form.partnerContactName = null
      },
      'form.targetId'(val) {
        this.form.partnerContactId = null
        this.form.partnerContactName = null
      },
    },
    methods: {
      selectLable(type) {
        if (type) {
          const findItem = this.checkTypeColumns.find((item) => item.key == type)
          return findItem.value
        }
      },
      // 选择打卡类型
      pickCheckType(e) {
        this.form.punchType = e.value[0].key
        this.form.punchVal = e.value[0].value
        this.showCheckType = false
      },
      // 经销商
      closeDealer(dealer) {
        if (dealer) {
          this.form.targetId = dealer.id
          this.form.targetName = dealer.name
        }
      },
      // 关闭选择客户
      closeCust(user) {
        if (user) {
          this.form.targetId = user.id
          this.form.targetName = user.name
        }
      },
      closePartners(partners) {
        if (partners) {
          this.form.targetId = partners.id
          this.form.targetName = partners.name
        }
      },
      closePartnersConcat(concat) {
        if (concat) {
          this.form.partnerContactId = concat.id
          this.form.partnerContactName = concat.name
        }
      },
      openSelectUser() {
        if (this.form.punchType == '20') {
          this.$refs.cust.open()
        } else if (this.form.punchType == '30' || this.form.punchType == '40') {
          this.$refs.dealer.open()
        } else if (this.form.punchType == '50') {
          this.$refs.partners.open()
        }
      },
      openPartnersConcat() {
        this.$refs.partnersConcat.open(this.form.partnerContactId)
      },
      getLocation() {
        this.show = true
        const _this = this
        uni.getLocation({
          type: 'wgs84',
          success: function (res) {
            const latitude = res.latitude.toString()
            const longitude = res.longitude.toString()
            uni.request({
              header: {
                'Content-Type': 'application/text',
              },
              url:
                process.uniEnv.VUE_APP_PROTOCOL +
                'apis.map.qq.com/ws/geocoder/v1/?location=' +
                latitude +
                ',' +
                longitude +
                '&key=6REBZ-BRN6J-BMAFY-FIRI3-SMK43-G3FXU',
              success(re) {
                if (re.statusCode === 200) {
                  _this.address = re.data.result.address
                  _this.form.punchLat = latitude
                  _this.form.punchLng = longitude
                  _this.form.punchLocation = re.data.result.address
                  _this.show = false
                } else {
                  _this.address = '点击重试'
                  this.$refs.uToast.show({
                    type: 'error',
                    message: '定位失败，请重试',
                  })
                }
              },
              fail: (err) => (_this.show = false),
            })
          },
          fail: (err) => (_this.show = false),
        })
      },
      async checkIn() {
        const [fail, resp] = await to(this.$refs.form.validate())
        if (fail && fail.length > 0) {
          this.$refs.uNotify.show({
            top: this.height + this.paddingTop + 10,
            type: 'warning',
            message: fail[0].message,
            duration: 1000 * 3,
          })
          return
        }
        if (!this.form.punchLat || !this.form.punchLng) {
          this.address = '点击重试'
          return this.$refs.uToast.show({
            type: 'error',
            message: '定位失败，请重试',
          })
        }
        const [err, res] = await uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['camera'],
        })
        if (err) return
        this.select(res)
        res.tempFiles[0].name = new Date().getTime() + ''
        res.tempFiles[0].type = ''
      },
      // // 选择上传触发函数
      select(e) {
        let url = process.uniEnv.VUE_APP_UPLOAD_WEED
        uni.request({
          url, //仅为示例，并非真实接口地址。
          success: (res) => {
            this.uploadFiles(e, res.data)
          },
        })
      },
      // 上传函数
      async uploadFiles(e, res) {
        let action = process.uniEnv.VUE_APP_PROTOCOL + res.publicUrl + '/' + res.fid
        uni.uploadFile({
          url: action,
          filePath: e.tempFilePaths[0],
          name: 'file',
          formData: {
            file: e.tempFiles[0],
          },
          success: (res) => {
            this.form.punchImg = action
            api.checkIn(this.form).then((res) => {
              this.$refs.uToast.show({
                type: 'success',
                message: '打卡成功',
              })
            })
          },
          fail: () => {
            console.log('err')
          },
        })
      },
      showCheckList() {
        if (!this.showList) {
          this.queryForm.pageNum = 1
          this.checkList = []
          this.loadCheckList()
        }
        this.showList = !this.showList
      },
      async loadCheckList() {
        this.loadStatus = 'loading'
        const [err, res] = await to(api.getCheckList(this.queryForm))
        if (err) {
          this.loadStatus = 'nomore'
          return
        }
        if (res && res.code == 200) {
          this.checkList = [...this.checkList, ...(res.data.list || [])]
          // this.checkList = res.data.list
          this.total = res.data.total
          this.loadStatus = this.checkList.length == this.total ? 'nomore' : 'loadmore'
        } else {
          this.loadStatus = 'nomore'
        }
      },
      scrolltolower() {
        if (this.checkList.length < this.total && this.loadStatus != 'loading') {
          this.queryForm.pageNum++
          this.$u.throttle(this.loadCheckList(), 2000, false)
        }
      },
      goBack() {
        uni.navigateBack({
          //关闭当前页面，返回上一页面或多级页面。
          delta: 1,
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  /deep/ .uni-file-picker {
    display: none;
  }

  .home {
    padding-top: 188rpx;
    height: 100%;

    .nav {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 284rpx;
      background: #3e7ef8;

      .title {
        position: relative;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
        color: #ffffff;

        .back {
          position: absolute;
          top: 0;
          bottom: 0;
          margin: auto;
          left: 70rpx;
          display: flex;
        }
      }
    }

    .main {
      display: flex;
      flex-direction: column;
      position: absolute;
      width: 100%;
      height: calc(100vh - 188rpx);
      background: #ffffff;
      box-shadow: 0 6rpx 19rpx 2rpx rgba(0, 45, 132, 0.15);
      border-radius: 31rpx 31rpx 0 0;
      padding: 0 32rpx;
      overflow: hidden;
      padding-bottom: 64rpx;

      .main-header {
        padding: 20rpx 40rpx;
        display: flex;
        justify-content: space-between;

        .user-info {
          display: flex;

          .user-img {
            width: 116rpx;
            height: 116rpx;
            border-radius: 50%;
            margin-right: 32rpx;
          }

          .info {
            height: 116rpx;
            margin-right: 32rpx;
          }
        }

        .more {
          display: flex;
          flex-direction: column;
          align-items: center;
        }
      }

      .main-container {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;

        .btn {
          width: 300rpx;
          height: 300rpx;
          border-radius: 50%;
          background: linear-gradient(70deg, #3e7ef8, #1d66dc);
          display: flex;
          justify-content: center;
          align-items: center;
          color: #fff;
          font-size: 48rpx;
          font-weight: bold;
          box-shadow: 0 6rpx 19rpx 2rpx rgba(29, 102, 220, 0.2);
          margin-bottom: 40rpx;
        }

        .location {
          display: flex;
          height: 32rpx;
          line-height: 32rpx;
        }
      }
    }
  }
</style>
