<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="新建外勤拜访">
        <!-- #ifndef MP-WEIXIN -->
        <button
          class="button white-btn"
          @click="handleSave">
          保存
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <view class="container">
        <scroll-view :scroll-y="true" class="scroll-content">
          <map
            id="legworkMap"
            :style="{
              width: mapStyle.width
            }"
            :markers="markers"
            :longitude="centerPoint.longitude"
            :latitude="centerPoint.latitude"
            enable-scroll />
          <!-- show-location -->
          <!-- :markers="markers" -->
          <!-- #ifdef APP-PLUS | MP-WEIXIN -->
          <cover-view :class="{show: showCoverView}" class="cover-mask" />
          <!-- #endif -->

          <view class="address-box">
            <text class="wk wk-position icon" />
            <text class="address">
              {{ centerPoint.addr || '定位失败，请检查您的系统设置项' }}
            </text>
            <text class="re-location" @click="reLocation">
              重新定位
            </text>
          </view>

          <!-- <view class="customer">
						<wk-field-revelance
							v-model="selectedCustomer"
							:config="customerConfig"
							:field="customerField" />
					</view> -->

          <!-- <textarea
						ref="core"
						v-model="formContent"
						:maxlength="500"
						placeholder="请输入外勤详细内容"
						placeholder-class="wk-placeholder placeholder"
						class="input-core" /> -->

          <view class="content">
            <wk-form
              ref="form"
              :fields="fieldArr" />

            <view class="image-cell">
              <view class="cell-title" @click.stop="handleSheet">
                <image :src="$static('images/icon/image.png')" class="pic" />
                <text class="text">
                  图片
                </text>
                <view class="add-icon">
                  <text class="wk wk-plus" />
                </view>
              </view>

              <wk-image-content
                v-if="imgList.length > 0"
                :list="imgList"
                show-delete
                @delete="handleDeleteFile" />
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->
    </view>

    <uni-popup
      ref="popup"
      type="actionsheet"
      radius="10rpx 10rpx 0 0"
      @change="handlePopupChange">
      <wk-action-sheet
        :list="popList"
        @select="handlePopSelect" />
    </uni-popup>
  </view>
</template>

<script>
  import { QueryById } from 'API/crm/customer'
  import { LegworkClock } from 'API/oa/legwork'
  import { FileDeleteById } from 'API/file'

  import Fields from '@/utils/fields.js'
  import {
    qqMapTransBMap,
    getLocation
  } from '@/utils/map.js'
  import WkFile from '@/utils/file.js'
  import { guid } from '@/utils/lib.js'

  export default {
    name: 'LegworkAdd',
    data() {
      return {
        fieldArr: [
          new Fields({
            name: '拜访客户',
            fieldName: 'activityTypeId',
            formType: 'customer',
            isNull: 1
          }),
          new Fields({
            name: '外勤详细内容',
            fieldName: 'content',
            formType: 'textarea',
            isNull: 1
          })
        ],
        customerConfig: {
          otherParams: {type: 2}
        },
        mapStyle: {
          width: 0
        },
        markers: [],

        centerPoint: {},
        selectedCustomer: [],
        imgList: [],
        batchId: guid(),
        formContent: '',

        showCoverView: false,
        popList: [
          '拍照',
          '从相册中选择'
        ],
        loading: false
      }
    },
    onLoad(options) {
      const id = options.customerId || null
      if (id) {
        this.getCustomerDetail(id)
      }
    },
    mounted() {
      this.mapStyle = {
        width: uni.upx2px(750) + 'px'
      }
      // #ifdef MP-WEIXIN
      this.getUserLocationAuth()
      // #endif
      // #ifndef MP-WEIXIN
      this.getLocation()
      // #endif

      this.$nextTick(function() {
        this.$refs.form.setConfig('activityTypeId', {
          optionsConfig: { showCreate: true }
        })
      })
    },
    methods: {
      getUserLocationAuth() {
        const that = this
        uni.getSetting({
          success: (data) => {
            console.log('setting: ', data)
            const flag = data.authSetting['scope.userLocation']
            if (!flag) {
              uni.authorize({
                scope: 'scope.userLocation',
                success: () => {
                  that.getLocation()
                },
                fail: () => {
                  that.$toast('定位失败')
                }
              })
            } else {
              that.getLocation()
            }
          },
          fail: () => {
            that.$toast('定位失败')
          }
        })
      },

      /**
       * 获取客户详情
       */
      getCustomerDetail(id) {
        QueryById({
          customerId: id
        }).then(res => {
          this.$nextTick(() => {
            this.$refs.form.setFormVal('activityTypeId', [res])
          })
        }).catch(() => {})
      },

      getLocation() {
        console.log('开始定位')
        getLocation().then(data => {
          this.centerPoint = data
          this.markers = [{
          ...data,
          width: 30,
          height: 30,
          iconPath: this.$static('images/map/location.png')
          }]
          console.log('定位：', this.centerPoint)
        }).catch(() => {
          // this.$toast(JSON.stringify(err))
          this.$toast('定位失败')
        })
      },

      reLocation() {
        uni.$once('choose-address', this.chooseAddress)
        this.$Router.navigateTo({
          url: '/pages_common/map/chooseAddress'
        })
      },

      chooseAddress(data) {
        this.centerPoint = {
        ...data,
        addr: data.address
        }
        this.markers = [{
        ...data,
        width: 30,
        height: 30,
        iconPath: this.$static('images/map/location.png')
        }]
      },

      handlePopupChange() {
        this.showCoverView = !this.showCoverView
      },

      handleDeleteFile(index) {
        let fileId = this.imgList[index].fileId || null
        this.imgList.splice(index, 1)
        FileDeleteById({
          id: fileId
        }).then().catch()
      },

      handleSheet() {
        // this.$refs.popup.open()
        const params = {type: 'img'}
        if (this.batchId) {
          params.batchId = this.batchId
        }
        const fileUpload = new WkFile(params)
        fileUpload.choose().then(data => {
          console.log('upload res: ', data)
          this.imgList = this.imgList.concat(data)
        })
      },

      handlePopSelect(index) {
      // this.$refs.popup.close()
      // const pop = this.popList[index]
      // if (pop === '拍照') {
      // } else {
      // }
      },

      handleSave() {
        if (this.loading) return
        this.loading = true
        this.$refs.form.getForm().then(form => {
          form = form.entity
          const p = this.centerPoint
          const point = qqMapTransBMap(p.longitude, p.latitude)
          form = {
          ...form,
          lng: point.longitude,
          lat: point.latitude,
          address: p.addr || p.address || '',
          activityType: 2
          }
          if (!form.lng || !form.lat) {
            this.$toast('定位失败！')
            this.loading = false
            return
          }
          // form.img = this.imgList
          if (this.imgList.length > 0) {
            form.batchId = this.imgList[0].batchId
          }
          console.log('save: ', form)

          LegworkClock(form).then(res => {
            this.loading = false
            this.$toast('签到成功')
            this.$refreshAndToPrev(this)
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          this.loading = false
        })
      },
    }
  }
</script>

<style scoped lang="scss">

.main-container {
  .container {
    position: relative;
    flex: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    // padding-bottom: 150rpx;

    .scroll-content {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }

    #legworkMap {
      width: 750rpx;
      height: 380rpx;
    }

    .cover-mask {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1024;
      width: 750rpx;
      height: 0;
      background-color: rgba(0,0,0,.4);
      &.show {
        height: 380rpx;
      }
    }

    .address-box {
      width: 100%;
      font-size: 28rpx;
      background-color: white;
      padding: 24rpx 20rpx;
      @include left;
      .icon {
        font-size: 36rpx;
        font-weight: 500;
        line-height: normal;
        color: #1C6CFF;
        margin-right: 15rpx;
      }
      .address {
        flex: 1;
        color: #999;
        margin-right: 15rpx;
        @include ellipsis;
      }
      .re-location {
        font-size: 24rpx;
        color: $theme-color;
        text-align: center;
        margin-right: 10rpx;
      }
    }

    .content {
      flex: 1;
      width: 100%;
      background-color: white;
      margin-top: 20rpx;
      padding: 20rpx 0;

      .image-cell {
        padding: 0 32rpx;
        .cell-title {
          padding: 15rpx 0;
          @include left;
          .pic {
            width: 36rpx;
            height: 36rpx;
            margin-right: 15rpx;
          }
          .text {
            flex: 1;
          }
          .add-icon {
            width: 38rpx;
            height: 38rpx;
            background-color: #E1E1E1;
            border-radius: 50%;
            @include center;
            .wk {
              font-size: $wk-font-mini;
              line-height: normal;
              color: white;
            }
          }
        }

      }
    }
  }

  .save-btn {
    position: fixed;
    left: 3%;
    bottom: 24rpx;
    width: 94%;
    height: 100rpx;
    font-size: 36rpx;
    text-align: center;
    line-height: 100rpx;
    color: white;
    border-radius: 10rpx;
    background-color: $theme-color;
  }
}
</style>
