<template>
  <view class="order-wrap">
    <u-navbar
      title-color="#FFFFFF"
      title-size="32"
      back-icon-color="#FFFFFF"
      :background="background"
      :border-bottom="false"
      :custom-back="goBack"
      title-bold
    ></u-navbar>
    <view class="content">
      <view class="title-view">
        <view class="title-text">{{ title }}</view>
        <!-- 拒单 -->
        <view
          v-show="allowRejection"
          class="reject-button"
          @click="$u.throttle(rejectOrder, 500)"
          >拒单</view
        >
      </view>
      <!-- 订单详情 -->
      <view class="card">
        <view class="header" v-if="showTimeView">
          <view class="header-left-view">
            <u-icon
              :name="clockName"
              margin-left="10"
              custom-prefix="wxh"
              :color="countColor"
              size="40"
              :label="tipText"
              label-size="32"
              :label-color="countColor"
              :custom-style="{ 'font-weight': 'bold' }"
            />
          </view>
          <!-- 倒计时 -->
          <view class="title">
            <u-count-down
              :timestamp="timestamp"
              font-size="28"
              show-days
              separator="zh"
              separator-size="32"
              height="40"
              color="#FFFFFF"
              separator-color="#666666"
              @change="timeOutChange"
              ref="order-count-down"
              :bg-color="countColor"
            ></u-count-down>
          </view>
        </view>
        <Detail
          :order="order"
          :readMore.sync="readMore"
          :operate="isAllowDianhuaAndDaohang"
        ></Detail>
      </view>
      <!-- 从我的页面进来显示结算信息 -->
      <view v-if="isOther" class="settlement-view">
        <view class="settlement-title">结算信息</view>
        <view class="settlement-content">
          <text class="content-left">工单确认时间：</text>
          <text>{{ settlementInfo.formatTime }}</text>
        </view>
        <view
          class="settlement-content"
          v-for="(item, index) in settlementInfo.list"
          :key="index"
        >
          <text class="content-left">{{
            item.businessSettlementType + '：'
          }}</text>
          <text>{{
            (item.realSettlementAmount || item.settlementAmount) + '元'
          }}</text>
          <text v-if="item.adjustmentRemark">{{
            '-' + item.adjustmentRemark
          }}</text>
        </view>
        <view class="settlement-content">
          <text class="content-left">最终结算金额：</text>
          <text>{{ settlementInfo.amount }}元</text>
        </view>
      </view>
      <!-- 不是从我的页面，而是其他页面进来 -->
      <view v-else>
        <!-- 业务文件 -->
        <view
          class="order-file"
          v-if="showFile"
          @click="$u.throttle(handleClickFile, 500)"
        >
          <view class="order-file-left">
            <image :src="wenjianImage" class="file-image"></image>
            <text>充电桩安装业务文件</text>
          </view>
          <view class="order-file-right">
            <text>点击查看</text>
            <u-icon name="arrow-right"></u-icon>
          </view>
        </view>
        <view
          class="customer"
          v-if="order.customerServiceId"
        >
          <view class="top-item">
            <text>联系客服</text>
          </view>
          <cell :plugid='order.customerServiceId'  />
        </view>
        <!-- 带预约显示时间选择 -->
        <FeedbackContent
          ref="feed-back"
          v-show="isWaitAppointment"
          :categoryId="order.categoryId"
          type="filing"
          @change="handleChange"
          class="content-view"
        />
        <!-- 履约记录 -->
        <view class="card record-item">
          <Record :orderRecords="orderRecords"></Record>
        </view>
      </view>
    </view>
    <!-- 不是从我的页面进来才显示 -->
    <template v-if="!isOther">
      <!-- 提示窗口 -->
      <view>
        <u-toast ref="uToast" />
      </view>
      <BottomButtons
        v-if="showBottomBtn"
        :buttons="buttons"
        @submit="handleSubmit"
      ></BottomButtons>
      <!-- 拍照 -->
      <take-photo
        type="test"
        v-if="takeStatus"
        @close="closeTake"
        :upload="false"
        :num="1"
      ></take-photo>
      <!-- 添加客服 -->
      <u-popup
        border-radius="12"
        v-model="visible"
        safe-area-inset-bottom
        mode="center"
        width="690rpx"
        :mask-close-able="false"
        close-icon-color="#FFFFFF"
      >
        <view class="order-pop-view">
          <Customer type="pop" @click="handleJoin"></Customer>
        </view>
      </u-popup>
      <!-- 已申请配件列表 -->
      <!-- <ApplyList :show.sync="showApplyList" :list="partsList" @action="handleClickCell"  @operate="handleOperate" @apply="handleApply"></ApplyList> -->
    </template>
  </view>
</template>

<script>
// import appointTime from '@/components/appoint/appoint-time.vue'
import takePhoto from '@/components/take/index.vue'
// import PopView from "@/components/popView/index.vue"
import baseFile from '@/components/upload/index'
import Customer from '@/components/mine/customer.vue'
import Record from '@/components/order/performanceRecord.vue'
import Detail from '@/components/order/detail.vue'
import BottomButtons from '@/components/order/bottomButtons.vue'
import FeedbackContent from '@/components/order/feedback.vue'
import upload from '@/components/upload/task.js'

// import ApplyList from "@/components/parts/applyList.vue"
let now = new Date(new Date().toLocaleDateString()).getTime()
export default {
  components: {
    // appointTime,
    'take-photo': takePhoto,
    // PopView,
    Customer,
    Record,
    Detail,
    BottomButtons,
    FeedbackContent,
    // ApplyList
  },
  mixins: [baseFile],
  data() {
    return {
      type: '',
      readMore: true, // 是：显示的是'查看更多'按钮；否：显示的是'点击收起'按钮
      background: {
        backgroundColor: 'none',
        // 导航栏背景图
        // background: 'url(https://cdn.uviewui.com/uview/swiper/1.jpg) no-repeat',
        // 还可以设置背景图size属性
        // backgroundSize: 'cover',
        // 渐变色
      },
      visible: false,
      // orderId: null,
      orderId: 11881507, // 测试数据
      order: {},
      needPhotograph: true, // 需要现场拍摄
      orderRecords: [],
      method: null,
      submitType: '',
      nextUrl: '',
      takeStatus: false,
      isErrorSign: false,
      errorSignUrl: '',
      signDistance: 3000,
      contactAddressLongitud: 0,
      contactAddressLatitud: 0,
      num: 0,
      clicking: false,
      dateItem: null,
      centerBtnDisabled: false,
      settlementInfo: { formatTime: '-', list: [], amount: '' },
      unloaded: false,
      timeout: false,
      timestamp: 0,
      showCountTime: false, // 从上个页面传入是否显示倒计时
      // showApplyList: false, // 显示已申请配件列表
      partsList: [], // 已申请的配件列表
      partsCount: 0,
    }
  },
  computed: {
    customStyle() {
      return {
        height: '48rpx',
        width: '100rpx',
        color: '#FFFFFF',
        'border-color': 'transparent',
        'background-color': 'transparent',
      }
    },
    buttons() {
      //id: 0 主流程； 1 过程反馈；2 异常签到； 3 现场拍照； 4 备件申请
      // label: 按钮文字,
      // type: 'image' 上图片下文字；'text' 纯文字,
      // image: 图片名,
      // show: 是否显示,
      // disabled: 是 禁用；否 正常,
      // id: 区分各个按钮
      return [
        {
          label: '异常签到',
          type: 'image',
          image: 'yichangqiandao.png',
          show: this.isWaitCheckIn, // 待签到显示
          disabled: false,
          id: 2,
        },
        {
          label: '现场拍照',
          type: 'image',
          image: 'xiancahngpaizhao.png',
          show: this.isWaitFinish,
          disabled: false,
          id: 3,
        },
        {
          label: '物料申请',
          type: 'image',
          image: 'peijian.png',
          show: this.showPartsButton,
          disabled: false,
          count: this.partsCount,
          id: 4,
        },
        {
          label: '改约',
          type: 'image',
          image: 'guochengfankui.png',
          show: this.allowFeedback,
          disabled: false,
          id: 1,
        },
        {
          label: this.bottomButtonText,
          type: 'text',
          image: '',
          show: true,
          disabled: this.centerBtnDisabled,
          id: 0,
          customStyle: {
            'background-color': this.isCompetitionAndWaitAccept
              ? '#FF930D'
              : this.centerBtnDisabled
              ? '#D1D4D4'
              : '#2272FF',
          },
        },
      ]
    },
    clockName() {
      return this.timeout ? 'timeout' : 'clock'
    },
    countColor() {
      return this.timeout ? '#FA5A49' : '#2272FF'
    },
    wenjianImage() {
      return process.uniEnv.qn_base_url + 'wenjian.png'
    },
    types() {
      return {
        waitAccept: 0, // 待接单、待抢单
        waitAppointment: 1, // 待预约、
        waitCheckIn: 2, // 待签到、
        waitFinish: 3, // 待完工、
        audit: 4, // 审核中、
        exception: 5, // 异常单、
        finish: 6, // 已完工
        snapped: 8, // 已被抢
        other: 9, // 工单结算信息
      }
    },
    titles() {
      return [
        '待' + this.type0Text,
        '待预约',
        '待签到',
        '待完工',
        '审核中',
        '异常单',
        '已完工',
        '',
        '',
        '订单信息',
      ]
    },
    bottomButtonText() {
      // 底部主流程按钮文字
      return this.buttonTexts[this.types[this.type]]
    },
    buttonTexts() {
      return [
        this.type0Text,
        '预约',
        '签到',
        '去完工',
        '',
        '',
        '',
        '',
        '已被抢',
        '',
      ]
    },
    tipText() {
      // 时间紧迫提示文字
      return this.timeout ? '订单超时' : '剩余时间'
    },
    title() {
      // 标题
      return this.titles[this.types[this.type]]
    },
    type0Text() {
      return this.isCompetition ? '抢单' : '接单'
    },
    isCompetition() {
      // 是：订单池，抢单； 否：指派单，接单
      return this.order.orderBusinessType == 'R'
    },
    isOther() {
      // 工单结算信息
      return this.type == 'other'
    },
    allowRejection() {
      // 允许拒单
      // 待接单 && 业务类型非抢单
      return this.type == 'waitAccept' && !this.isCompetition
    },
    isCompetitionAndWaitAccept() {
      // 抢单页面
      // 待接单 && 业务类型抢单
      return this.type == 'waitAccept' && this.isCompetition
    },
    showBottomBtn() {
      // 显示底部button
      // 0 待接单、待抢单, 1 待预约, 2 待签到, 3 待完工, 8 已被抢
      return [0, 1, 2, 3, 8].indexOf(this.types[this.type]) != -1
    },
    showFile() {
      // 显示查看业务文件
      // 1 待预约, 2 待签到, 3 待完工, 4 审核中, 5 异常单, 6 已完工, 8 已被抢
      return this.types[this.type] > 0
    },
    isAllowDianhuaAndDaohang() {
      // 可以点击电话和定位按钮
      return this.type != 'waitAccept'
    },
    showTimeView() {
      // 是否显示倒计时窗口
      // 上个页面传入 || 订单信息有超过时间点 && ((待预约、 待签到、 待完工) || (待接单 && 业务类型非抢单))
      return (
        this.showCountTime ||
        (this.order.currentOverTime &&
          ([1, 2, 3].indexOf(this.types[this.type]) != -1 ||
            (this.type == 'waitAccept' && !this.isCompetition)))
      )
    },
    showPartsButton() {
      // 显示配件申请按钮
      // 1 待预约, 2 待签到, 3 待完工
      return [1, 2, 3].indexOf(this.types[this.type]) != -1
    },
    allowFeedback() {
      // 允许改约
      // 2 待签到, 3 待完工
      return [2, 3].indexOf(this.types[this.type]) != -1
      // return [1, 2, 3].indexOf(this.types[this.type]) != -1
    },
    isWaitCheckIn() {
      // 待签到
      return this.type == 'waitCheckIn'
    },
    isWaitAppointment() {
      // 待预约
      return this.type == 'waitAppointment'
    },
    isWaitFinish() {
      return this.type == 'waitFinish'
    },
  },
  onLoad(option) {
    getApp().trackPage('订单详情页')
    // 生命周期函数--监听页面加载
    if (option && option.id) {
      this.orderId = option.id
    }
    if (option && option.showCountTime) {
      // 是否显示倒计时，上个页面传入，可以快速显示避免页面跳动太大；之后还需要从后台获取信息，再根据其他条件判断一次
      this.showCountTime = option.showCountTime
    }
    if (option && option.type) {
      // 类型,从上个页面传进来可以快速构建页面；之后还需要从后台获取信息，更新状态
      // 'waitAccept': 待接单、待抢单;'waitAppointment': 待预约;'waitCheckIn': 待签到;'waitFinish': 待完工;'audit': 审核中;'exception': 异常单;'finish': 已完工;'other': 工单结算信息
      this.type = option.type
    }

    // this.loadOrderDetail() // onShow里面刷新
    this.getLocation()
    if (this.isOther) {
      // 获取结算信息
      this.loadSettlement()
    } else {
      this.loadOrderRecord() // 履约记录
      this.getSignDistance() // 定位
      // this.getOrderPartsSum() // 备件单数量
    }
  },
  onShow(option) {
    if (option && option.id) {
      this.orderId = option.id
    }
    if(!this.vuex_token) {
      this.$refs.uToast.show({
        title: '登录过期，请先登录',
        type: 'warning',
      })
      setTimeout(() => {
        this.$u.route({url: 'pages/login/index'})
      }, 1500)
    }

    if (this.uploadTask.length > 0) {
      upload.uploadImageTask(this)
    }
    this.loadOrderDetail()

    // 从过程反馈回来，需要刷新数据
    let pages = getCurrentPages()
    let page = pages[pages.length - 1]
    if (page.needFresh) {
      page.needFresh = null
      this.loadOrderRecord()
    }
    if (page.needRefresh) {
      page.needRefresh = null
      this.getApplyList()
    }
  },
  onUnload() {
    this.unloaded = true
    this.closeLocationChange()
  },
  methods: {
    goBack() {
      let pages = getCurrentPages()
      if (pages.length === 1) {
        uni.switchTab({
          url:'pages/index/order'
        })
      } else {
        uni.navigateBack({
          delta: 1
        })
      }
    },
    updateLocation() {
      let self = this
      wx.startLocationUpdate({
        success: function() {
          self.openLocationChange()
        },
      })
    },
    _locationChangeFn(res) {
      let self = this
      console.log('location change', res)
      const dataValue = this.dataValue || []
      dataValue.push(res.longitude)
      dataValue.push(res.latitude)
      self.dataValue = dataValue

      if (this.getDistance(res.latitude, res.longitude) > this.signDistance) {
        // 计算签到距离
        this.centerBtnDisabled = true
      } else {
        this.centerBtnDisabled = false
      }
    },
    openLocationChange() {
      console.log('openLocationChange')
      wx.onLocationChange(this._locationChangeFn)
    },
    closeLocationChange() {
      console.log('closeLocationChange')
      wx.offLocationChange(this._locationChangeFn)
    },
    handleClickRight(active) {
      this.isWaitFinish ? this.scenePhotoClick() : this.take()
    },
    scenePhotoClick() {
      // 跳转拍照小程序
      uni.navigateTo({
        url:
          'pages/photo/list?orderId=' +
          this.order.orderId +
          '&brandId=' +
          this.order.lianbaoBrandId +
          '&brand=' +
          this.order.brandName +
          '&systemId=' +
          this.order.partnerCompanyId +
          '&classifyId=' +
          this.order.categoryId +
          '&orderNumber=' +
          this.order.orderNumber,
      })
    },
    take() {
      uni.hideTabBar()
      this.takeStatus = true
    },
    async closeTake(img) {
      this.takeStatus = false
      // 获取返回的图片 ,如果返回的图片存在则直接异常签约，成功后跳转到去完工页面，
      if (img) {
        // 拍照完成
        const value = await this.saveToTask(img)
        this.isErrorSign = true
        this.errorSignUrl = value[0].key
        this.handleBtn()
      } else {
        this.$refs.uToast.show({
          title: '异常签到失败，请先按要求拍照',
          type: 'warning',
        })
      }
    },
    loadOrderDetail() {
      // 获取工单详情
      let self = this
      self.$u.api.orderDetail({}, self.orderId).then((res) => {
        if (res.code == 200) {
          self.order = res.data
          this.setOrderType()
          var nowTime = new Date().getTime()
          this.timeout =
            this.order.currentOverTime && nowTime > this.order.currentOverTime
          this.timestamp = Math.round(
            Math.abs(this.order.currentOverTime - nowTime) / 1000
          )
          // 格式化时间
          this.settlementInfo.formatTime = this.order.settleCenterSyncDatetime
            ? this.$u.timeFormat(
                this.order.settleCenterSyncDatetime,
                'yyyy.mm.dd hh:MM:ss'
              )
            : '-'
        } else {
          console.log(res.message, '获取订单详情失败！')
        }
      })
    },
    loadSettlement() {
      // 获取工单详情
      let self = this
      var data = {
        orderId: self.orderId,
      }
      self.$u.api.querySettleByOrder(data, self.orderId).then((res) => {
        if (res.code == 200) {
          var amount = 0
          for (var item of res.data) {
            amount += item.realSettlementAmount || item.settlementAmount
          }
          this.settlementInfo.amount = amount
          this.settlementInfo.list = res.data
        } else {
          console.log(res.message, '获取订单详情失败！')
        }
      })
    },
    // getOrderPartsSum() { // 获取订单配件数量
    // 	this.$u.api.getOrderPartsSum(this.orderId).then((res) => {
    // 		if (res.code == 200) {
    // 			if (res.data) {
    // 				this.partsCount = res.data.totalPartCount
    // 			}
    // 		} else {
    // 			console.log(res.message)
    // 		}
    // 	});
    // },
    getSignDistance() {
      let self = this
      var data = {}
      self.$u.api.getSignDistance(data).then((res) => {
        if (res.code == 200) {
          self.signDistance = res.data
        }
      })
    },
    loadOrderRecord() {
      let self = this
      var param = {
        orderId: self.orderId,
      }
      self.$u.api.listOrderRecord(param).then((res) => {
        if (res.code == 200) {
          res.data.forEach((item) => {
            item.isTrace = false
            item.traceTime = null
            item.traceLabel = item.operationType
            if (
              item.operationType === '报备' ||
              item.operationType === '改约'
            ) {
              item.isTrace = true
              item.traceLabel =
                item.operationType === '报备' ? '下次联系时间' : '改约时间'
              item.operationTypeText = item.operationType
              item.traceTime = item.orderRecordRemark
              let arr = item.orderRecordRemark.split(',')
              if (arr && arr.length > 1) {
                let remark = arr[1].substring(
                  arr[1].indexOf('：') + 1,
                  arr[1].length
                )
                item.traceTime = remark
                item.operationTypeText = arr[0]
              }
            } else if (item.operationType === '预约') {
              let remark = item.orderRecordRemark.substring(
                item.orderRecordRemark.lastIndexOf(',') + 1
              )
              item.traceTime = remark
              item.operationTypeText = `上门 ${remark}`
            } else {
              item.operationTypeText = item.operationType
            }
          })
          self.orderRecords = res.data
        } else {
          console.log(res.message, '获取订单详情失败！')
        }
      })
    },

    handleChange(val) {
      console.log('-----handleChange-------', val)
    },
    addressToCoordinate() {
      let self = this
      self.$u.api.addressToCoordinate(self.orderId).then((res) => {
        if (res.code == 200) {
          self.contactAddressLongitud = res.data.lng
          self.contactAddressLatitud = res.data.lat
        } else {
          console.log(res.message)
        }
      })
    },
    setOrderType() {
      // 确定工单类型
      var orderStatus = this.order.orderStatus
      if (orderStatus < 31) {
        // 接单
        this.type = 'waitAccept'
        this.submitType = this.isCompetition ? 'orderGan' : 'orderAccept'
      } else if (orderStatus === 31 && !this.order.appointmentDatetime) {
        // 预约
        this.type = 'waitAppointment'
        this.submitType = 'workerAppointment'
        // this.loadCalendar()
      } else if (orderStatus === 31 && this.order.appointmentDatetime) {
        // 签到
        this.type = 'waitCheckIn'
        this.submitType = 'maintainWorkerCheckin'
        this.updateLocation()
      } else if (orderStatus > 31 && orderStatus < 80) {
        // 完工
        this.type = 'waitFinish'
        this.submitType = 'toFilish'
      } else if (orderStatus == 85 || orderStatus == 87 || orderStatus == 88) {
        // 审核中
        this.type = 'audit'
      } else if (orderStatus == 86) {
        // 异常单
        this.type = 'exception'
      } else if ([80, 81, 89, 110].indexOf(orderStatus) != -1) {
        // 已完工
        this.type = 'finish'
      }
      this.readMore = this.type != 'waitAccept'
    },
    handleClickSure() {
      if (
        (this.submitType == 'orderAccept' || this.submitType == 'orderGan') &&
        process.uniEnv.node_env == 'prod'
      ) {
        this.$u.api.checkAddCustomer().then((res) => {
          if (res.code == 200) {
            if (res.data === true) {
              this.handleBtn()
            } else {
              this.visible = true
            }
          } else {
          }
        })
      } else {
        this.handleBtn()
      }
    },
    handleSubmit(id) {
      // 0 主流程； 1 过程反馈；2 异常签到； 3 现场拍照
      switch (id) {
        case 0:
          this.handleClickSure()
          break
        case 1:
          this.clickFeedback()
          break
        case 2:
          getApp().track('order_errorSign', { orderId: this.orderId })
          this.take()
          break
        case 3:
          getApp().track('order_scenePhotoClick', { orderId: this.orderId })
          this.scenePhotoClick()
          break
        case 4:
          this.handleApplyParts()
          break
      }
    },

    handleApplyParts() {
      // 点击了配件申请按钮
      // if (this.buttons[3].count > 0) { // 已经有配件,弹出配件列表
      // 	this.showApplyList = true
      // 	this.getApplyList()
      // } else { // 没有配件,跳到配件申请
      this.toApplyParts()
      // }
    },
    async getApplyList() {
      let res = await this.$u.api.applyList({
        pageSize: 1000,
        pageNumber: 1,
        // 'status': null,  // -不传值  全部   待签收 15  待发货 10  待审核 1 已取消 -1  已驳回 -2 已签收 20
        workOrderId: this.order.orderId,
      })
      if (res && res.code == 200) {
        this.partsList = res.data || []
      }
    },
    handleBtn() {
      if (!this.submitType) {
        return
      }
      var data = {}
      // 不同请求类型传递不同数据
      if (this.submitType === 'orderAccept') {
        // 接单
        data.orderId = this.order.orderId
      } else if (this.submitType === 'orderGan') {
        // 抢单
        data.orderId = this.order.orderId
        data.channel = 4
      } else if (this.submitType === 'workerAppointment') {
        data = this.$refs['feed-back'].submitData
        if (!data.remark) {
          this.commonToast('请补充详细说明', 'waring')
          return
        }

        if (!data.appointmentDatetime) {
          this.commonToast('请选择预约日期', 'waring')
          return
        }
        if (!data.appointmentDatetimeRange) {
          this.commonToast('请选择预约时间段', 'waring')
          return
        }
      } else if (this.submitType === 'maintainWorkerCheckin') {
        // 签到
        // 检查见到距离是否符合
        if (!this.isErrorSign) {
          if (this.centerBtnDisabled) {
            return
          } else {
            this.closeLocationChange()
          }
          if (this.getDistance() > this.signDistance) {
            this.commonToast('签到失败，请点击异常签到处理或联系客服', 'error')
            return
          }
        }
        data.channel = 4
        data.exception = this.isErrorSign
        data.coordinate = this.dataValue
          ? this.dataValue[0] + ',' + this.dataValue[1]
          : ''
        data.url = this.errorSignUrl ? this.errorSignUrl : ''
        data.version = 2
      } else if (this.submitType === 'toFilish') {
        // 去完工
        if (this.order.categoryName != '充电桩') {
          uni.showModal({
            title: '提示',
            content: '非充电桩订单，请在扳手APP进行完工',
            showCancel: false,
            confirmText: '好的',
          })
        } else {
          this.filish()
        }
        return
      }
      if (this.clicking) {
        return
      }
      this.clicking = true
      this.$u.api[this.submitType](data, this.order.orderId).then((res) => {
        let self = this

        if (res.code === 200) {
          this.trackOrder()
          this.$refs.uToast.show({
            title: this.bottomButtonText + '操作成功',
            type: 'success',
            duration: 1000,
            callback: function() {
              if (self.unloaded === false) {
                // 如果用户一秒钟之内没有后退退出该页面才跳转
                self.clicking = false
                uni.redirectTo({
                  url: 'pages/order/detail?id=' + self.order.orderId,
                })
              }
            },
          })
        } else {
          let self = this
          this.$refs.uToast.show({
            title:
              res.data.message !== undefined ? res.data.message : res.message,
            // 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
            type: 'warning',
            callback: function() {
              self.clicking = false
              res.data.message === '抱歉，手快的师傅已经抢到此单！'
                ? self.isGan()
                : ''
            },
          })
        }
      })
    },
    // 去业务材料页面
    handleClickFile() {
      getApp().track('order_click_view_files', {
        brandId: this.order.lianbaoBrandId,
        partnerCompanyId: this.order.partnerCompanyId,
      })
      this.$u.route({
        url:
          'pages/order/document' +
          '?partnerCompanyId=' +
          this.order.partnerCompanyId +
          '&brandId=' +
          this.order.lianbaoBrandId,
      })
    },
    trackOrder() {
      // 接单成功事件，签到成功事件
      if (
        this.submitType == 'orderAccept' ||
        this.submitType == 'maintainWorkerCheckin'
      ) {
        getApp().track(this.submitType, {
          orderId: this.order.orderId,
        })
      }
    },
    commonToast(message, type, url, params) {
      // 统一得toast
      this.$refs.uToast.show({
        title: message,
        type: type,
        url: url,
        params: params,
      })
    },
    isGan() {
      this.type = 'snapped'
      this.submitType = ''
      this.centerBtnDisabled = true
    },
    clickFeedback() {
      getApp().track('order_clickFeedback', {
        orderId: this.order.orderId,
        categoryId: this.order.categoryId,
      })
      // 过程反馈
      uni.navigateTo({
        url:
          'pages/order/feedback?orderId=' +
          this.order.orderId +
          '&categoryId=' +
          this.order.categoryId +
          '&showGY=' +
          (this.bottomButtonText != '预约' ? '1' : '0'),
      })
    },
    filish() {
      // 去完工

      uni.navigateTo({
        url:
          'pages/order/complete?orderId=' +
          this.order.orderId +
          '&categoryId=' +
          this.order.categoryId +
          '&orderServiceType=' +
          this.order.orderServiceType +
          '&inGuaranteePeriod=' +
          this.order.inGuaranteePeriod +
          '&partnerCompanyId=' +
          this.order.partnerCompanyId +
          '&partnerCompanyName=' +
          this.order.partnerCompanyName +
          '&maintainStep=' +
          this.order.maintainStep +
          '&orderStatus=' +
          this.order.orderStatus +
          '&brandId=' +
          this.order.lianbaoBrandId +
          '&orderNumber=' +
          this.order.orderNumber,
      })
    },
    rejectOrder() {
      // 拒单
      // 检查是否可以拒单
      var data = {}
      this.$u.api.checkRejectable(data).then((res) => {
        if (res.code === 200) {
          if (res.data && res.data.rejectable) {
            this.$u.route({
              type: 'redirect',
              url: 'pages/order/refuse',
              params: {
                orderId: this.order.orderId,
                count: res.data.remainderTimes,
              },
            })
          } else {
            this.commonToast('本月无拒单机会，请联系客服', 'warning')
          }
        }
      })
    },
    /**
     * 获取当前位置的经纬度
     */
    getLocation() {
      let self = this
      const dataValue = this.dataValue || []
      uni.getLocation({
        type: 'gcj02',
        success: function(res) {
          dataValue.push(res.longitude)
          dataValue.push(res.latitude)
          self.dataValue = dataValue
        },
        complete: function(res) {
          if (res.errMsg.indexOf('auth') != -1) {
            uni.showModal({
              title: '提示',
              content: '获取权限失败，请到设置页面开启权限',
              confirmText: '好的',
              success(res) {
                if (res.confirm) {
                  uni.openSetting({
                    success(res) {
                      console.log(res.authSetting)
                    },
                  })
                }
              },
            })
          }
        },
      })
    },
    getDistance(Latitud, Longitud) {
      return this.distance(
        this.order.contactAddressLatitud,
        this.order.contactAddressLongitud,
        this.dataValue[1],
        this.dataValue[0]
      )
    },
    /**
     * echo distance(116.3896,39.91917,116.3940,39.91726);
     * 计算两点之间直线距离
     * @param float $lon1    纬度
     * @param float $lat1    经度
     * @param float $lon2    纬度
     * @param float $lat2    经度
     * @return float         浮点数
     */
    distance(lat1, lng1, lat2, lng2) {
      var radLat1 = this.Rad(lat1)
      var radLat2 = this.Rad(lat2)
      var a = radLat1 - radLat2
      var b = this.Rad(lng1) - this.Rad(lng2)
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) *
                Math.cos(radLat2) *
                Math.pow(Math.sin(b / 2), 2)
          )
        )
      s = s * 6378.137 // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10 //输出为米
      console.log('计算结果', s, 'M')
      return Number(s ? s.toFixed(2) : 0)
    },
    Rad(d) {
      return (d * Math.PI) / 180.0 //经纬度转换成三角函数中度分表形式。
    },
    timeOutChange(timestamp) {
      if (this.timeout) this.$refs['order-count-down'].seconds += 2
      if (timestamp == 0 && !this.timeout) {
        // 超时之后倒计时变为正计时
        setTimeout(() => {
          this.timestamp = 1
          this.timeout = true
        }, 1000)
      }
    },
    // handleClick(){
    // this.visible = false
    // // 交互规范
    // uni.switchTab({
    // 	url: 'pages/index/learn'
    // })
    // },
    handleJoin() {
      this.visible = false
      // 添加客服
    },
    handleOperate() {
      // 点了弹窗里的配件操作
      this.$u.api[operateType](partsId).then((res) => {
        var type = 'error'
        var message = res.message
        if (res.code === 200) {
          type = 'success'
          for (var item of this.partsList) {
            if (item.id == partsId) {
              item.status = willStatus
              break
            }
          }
        } else {
          console.log(res.message)
        }
        this.$refs.uToast.show({
          title: message,
          type: type,
          duration: 1500,
          callback: function() {},
        })
      })
    },
    handleClickCell(info) {
      this.setPageInfo(info)
      uni.navigateTo({
        url: 'pages/mine/warehouse/partsDetail',
      })
    },
    handleClickExpress(info) {
      this.setPageInfo(info)
      uni.navigateTo({
        url: 'pages/mine/warehouse/express',
      })
    },
    setPageInfo(info) {
      var pages = getCurrentPages()
      if (pages.length >= 1) {
        var page = pages[pages.length - 1]
        page.info = info
      }
    },
    handleApply() {
      // 点了弹窗的申请配件
      this.toApplyParts()
    },
    toApplyParts() {
      uni.navigateTo({
        url: 'pages/parts/application?orderId=' + this.order.orderId,
      })
    },
  },
}
</script>
<style lang="scss">
.order-wrap {
  .u-countdown-colon {
    margin-left: 6rpx;
    margin-right: 6rpx;
  }
  .u-mode-center-box {
    background-color: transparent !important;
    padding-top: 40rpx;
  }
}
</style>

<style lang="scss" scoped>
.order-wrap {
  width: 750rpx;
  height: 100vh;
  overflow: auto;
  background-color: #f4f5f7;
  background-image: linear-gradient(to top, #f4f5f7 0%, #2272ff 50%);
  background-size: 750rpx 600rpx;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .content {
    height: 100%;
    border-radius: 12rpx;
    overflow: auto;
    margin: 0rpx 30rpx 30rpx 30rpx;
    .title-view {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      margin-bottom: 20rpx;
      .title-text {
        font-weight: bold;
        font-size: 48rpx;
        color: #ffffff;
      }

      .reject-button {
        width: 106rpx;
        height: 52rpx;
        font-size: 26rpx;
        line-height: 52rpx;
        color: #dedede;
        text-align: right;
        margin-right: 4rpx;
      }
    }
    .card {
      background-color: #ffffff;
      margin-bottom: 20rpx;
      padding: 30rpx 30rpx 0 30rpx;
      border-radius: 6px;

      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2rpx solid #f4f5f7;
        padding-bottom: 26rpx;
        margin-bottom: 30rpx;
        .header-left-view {
          display: flex;
          align-items: center;
        }
      }
    }

    .record-item {
      margin-bottom: 0rpx;
    }

    .appoint-item {
      padding: 0;
    }
  }
}

.settlement-view {
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  .settlement-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 30rpx;
  }
  .settlement-content {
    font-size: 26rpx;
    color: #333333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: flex-start;
    .content-left {
      flex-shrink: 0;
    }
  }
}
.customer {
  width: 100%;
  margin: 20rpx 0;
  border-radius: 12rpx;
  background-color: #ffffff;
  padding: 24rpx 30rpx;
  .top-item {
    font-size: 32rpx;
    color: #333333;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
}
.order-file {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 0;
  border-radius: 12rpx;
  background-color: #ffffff;
  padding: 24rpx 30rpx;
  .order-file-left {
    color: #333333;
    font-size: 26rpx;
    display: flex;
    align-items: center;
    .file-image {
      width: 52rpx;
      height: 52rpx;
      flex-shrink: 0;
      margin-right: 16rpx;
    }
  }
  .order-file-right {
    color: #2272ff;
    font-size: 26rpx;
  }
}
</style>
