<template>
  <view
    :class="['order-view', { simple: isSimple }]"
    @click="handleClickCell"
    :hover-class="isSimple ? 'u-hover-class' : ''"
  >
    <view v-if="!isSimple" class="order-top-view">
      <view class="left-view">
        <view :class="['tag-view', { active: active }]">
          {{ orderData.orderServiceType }}
        </view>
        <view class="store-view">{{ orderData.categoryName }}</view>
      </view>
      <view class="right-view">{{ orderData.orderBusinessTypeText }}</view>
    </view>
    <view class="content-view">
      <view
        class="info-view"
        v-for="(item, key) in infoTexts"
        :key="key"
        :style="item.style"
      >
        <view class="info-left-view">
          <view v-if="item.symbol" class="symbol-view"> </view>
          <view class="info-title">
            <text>{{ item.name + '：' }}</text>
          </view>
          <view class="info-content">
            <text @longpress="handleLongpress(key, orderData[key])">{{
              orderData[key]
            }}</text>
            <text v-if="item.content">{{
              ' / ' + orderData[item.content]
            }}</text>
          </view>
        </view>
        <view v-if="item.icon">
          <u-icon :name="item.icon"></u-icon>
        </view>
      </view>
      <view class="address-view">
        <view class="address-left-view">
          <image
            class="address-image"
            :src="dizhiImage"
            mode="widthFix"
          ></image>
          <text>{{ formatAddress || '' }}</text>
        </view>
        <view v-if="showDistance" class="address-right-view">
          {{ orderDistance }}km
        </view>
      </view>
    </view>
    <template v-if="!isSimple">
      <view class="line-view"></view>
      <view class="reason-view" v-if="showReason">
        <view class="reason-title"><text>未通过原因：</text></view>
        <view class="reason-text">
          <text
            v-for="(item, index) in orderData.partAuditResults"
            :key="index"
            >{{ item }}</text
          >
          <text v-for="(item, index) in orderData.auditResults" :key="index">{{
            item
          }}</text>
        </view>
      </view>
      <view class="bottom-view">
        <view>
          <view v-if="showCountTime" class="bottom-left-view">
            <view :class="['bottom-tag-view', { timeout: timeout }]"
              ><text>{{ tagText }}</text></view
            >
            <u-count-down
              :timestamp="timestamp"
              font-size="40"
              show-days
              separator="zh"
              :color="timeout ? '#FA5A49' : '#FF930D'"
              @change="handleChange"
              separator-color="#666666"
              ref="order-count-down"
            ></u-count-down>
          </view>
          <view v-else-if="showTime">
            <text>{{ timeTitle }}</text>
            <text>{{ timeText }}</text>
          </view>
        </view>
        <u-button
          class="right-btn"
          @click.stop="handleClick"
          :custom-style="buttonStyle"
          type="primary"
          shape="circle"
        >
          {{ orderText }}
        </u-button>
      </view>
    </template>
  </view>
</template>

<script>
export default {
  props: {
    orderData: {
      type: Object,
      default() {
        return {
          orderServiceType: '安装', // 服务类型：安装、维修
          categoryName: '充电桩', // 品类：充电桩
          orderBusinessTypeText: '分配单', // 业务类型：分配单、订单池
          orderNumber: 'OR2021041809827', // 工单编号
          contactName: '郭小清', // 客户信息
          contactPhone: '13631612077', // 联系方式
          contactAddress: '湾街道荔枝花园D座125号', // 详细地址
          contactAddressLatitud: '116.3896', // 联系人地址经度
          contactAddressLongitud: '39.91917', // 联系人地址纬度
          orderStatus: 0, // 工单状态
          appointmentDatetime: '', // 预约时间
          currentWillOverTime: 10000, // 剩余时间
          currentOverTime: new Date().getTime() + 10000, // 超过时间点
          auditDatetime: '2021.04.19  12:45:09', // 审核时间
          orderFinishDatetime: '2021.04.19  16:24:48', // 提交时间
          auditResults: {}, // 审核结果
          orderBusinessType: 'R', // 业务类型 R 为抢单
          orderId: '0', // 订单id
          partnerSerialNumber: '', // 上游单号
          customerAddress: '', // 上游地址
        }
      },
    },
    /* 订单类型
			 waitAccept:待接单、
			 waitAppointment:待预约、
			 waitCheckIn:待签到、
			 waitFinish:待完工、
			 audit: 审核中、
			 exception：异常单、
			 finish：已完工
			 */
    type: String,
    location: {
      // 当前坐标
      type: Array,
      default() {
        return [116.3896, 39.91917] // 纬度,经度
      },
    },
    // simple: 只显示订单号、联系人/电话、地址，点击cell相当于点击订单列表的按钮; normal: 显示全部信息
    model: {
      type: String,
      default: 'normal',
    },
  },
  data() {
    return {
      timeout: false,
      timestamp: 0,
    }
  },
  computed: {
    formatAddress() {
      let order = this.orderData
      let address = order.customerAddress || ''
      if (address === '') {
        address = order.contactProvinceText || ''
        address += order.contactCityText || ''
        address += order.contactCommunityText || ''
        address += order.contactStreetText || ''
        address += order.contactAddress || ''
      }
      return address
    },
    orderText() {
      // 按钮文字
      return this.typeTexts[this.orderType]
    },
    isSimple() {
      return this.model == 'simple'
    },
    buttonStyle() {
      // 按钮样式
      /** orderType
			0 待接单、
			1 待预约、
			2 待签到、
			3 待完工、
			4 审核中、
			5 异常单、
			6 已完工
			*/
      switch (this.orderType) {
        case 0:
          if (!this.isCompetition) {
            return this.buttonStyles[0]
          } else {
            return this.buttonStyles[1]
          }
        case 1:
        case 2:
        case 3:
        case 5:
        case 4:
        case 6:
          return this.buttonStyles[0]
      }
    },
    showCountTime() {
      // ((待预约、 待签到、 待完工) || (待接单 && 业务类型非抢单)) && 有超过时间点
      return (
        ([1, 2, 3].indexOf(this.orderType) != -1 ||
          (this.orderType == 0 && !this.isCompetition)) &&
        this.orderData.currentOverTime
      )
    },
    showTime() {
      return [4, 5, 6].indexOf(this.orderType) != -1
    },
    infoTexts() {
      return this.isSimple
        ? {
            partnerSerialNumber: {
              symbol: true,
              name: '订单编号',
              style: 'font-weight: 450;font-size: 28rpx',
              icon: 'arrow-right',
            },
            contactName: { name: '客户信息', content: 'contactPhone' },
          }
        : {
            partnerSerialNumber: { name: '订单编号' },
            partnerCompanyName: { name: '合作厂商' },
            contactName: { name: '客户信息', content: 'contactPhone' },
          }
    },
    typeTexts() {
      return [
        this.type0Text,
        '去预约',
        '去签到',
        '去完工',
        '去查看',
        '去处理',
        '去查看',
      ]
    },
    isCompetition() {
      // 是：订单池，抢单； 否：指派单，接单
      return this.orderData.orderBusinessType == 'R'
    },
    type0Text() {
      return !this.isCompetition ? '接单' : '抢单'
    },
    buttonStyles() {
      return [
        {
          'background-color': '#2272FF',
          color: '#FFFFFF',
          'font-size': '32rpx',
          height: '80rpx',
          width: '200rpx',
        },
        {
          'background-color': '#FF930D',
          color: '#FFFFFF',
          'font-size': '32rpx',
          height: '80rpx',
          width: '200rpx',
        },
        // {
        //   'background-color': 'transparent',
        //   color: '#2272FF',
        //   'font-size': '32rpx',
        //   height: '32rpx',
        //   width: '100rpx',
        // },
      ]
    },
    // buttonTextType() {
    // 	return this.orderType == 4 || this.orderType == 6
    // },
    dizhiImage() {
      return process.uniEnv.qn_base_url + 'shouye-dizhi.png'
    },
    active() {
      return this.orderData.orderServiceType == '安装'
    },
    tagText() {
      return this.timeout ? '超' : '剩'
    },
    timeText() {
      let time =
        this.orderType == 4
          ? this.orderData.orderFinishDatetime
          : this.orderData.auditDatetime
      return time ? this.$u.timeFormat(time, 'yyyy.mm.dd hh:MM:ss') : ''
    },
    timeTitle() {
      return this.orderType == 4 ? '提交时间：' : '审核时间：'
    },
    showReason() {
      return this.orderType == 5
    },
    showDistance() {
      return (
        !this.isSimple &&
        this.orderType == 0 &&
        this.location.length >= 2 &&
        (this.orderData.contactAddressLatitud ||
          this.orderData.contactAddressLongitud)
      )
    },
    isWaitFinish() {
      return this.orderType == 3
    },
    isException() {
      return this.orderType == 5
    },
    types() {
      return {
        waitAccept: 0, // 待接单、
        waitAppointment: 1, // 待预约、
        waitCheckIn: 2, // 待签到、
        waitFinish: 3, // 待完工、
        audit: 4, // 审核中、
        exception: 5, // 异常单、
        finish: 6, //已完工
      }
    },
    typeList() {
      return [
        'waitAccept', // 待接单、
        'waitAppointment', // 待预约、
        'waitCheckIn', // 待签到、
        'waitFinish', // 待完工、
        'audit', // 审核中、
        'exception', // 异常单、
        'finish', //已完工
      ]
    },
    realType() {
      if (this.type && this.typeList.indexOf(this.type) != -1) {
        return this.type
      } else {
        return this.typeList[this.orderType]
      }
    },
    auditResults() {
      let partAuditResults = Object.keys(this.orderData.partAuditResults || {}).length > 0
        ? ['orderSpareParts']
        : []
      let auditResults = this.orderData.auditResults
        ? Object.keys(this.orderData.auditResults)
        : []
      return auditResults.concat(partAuditResults)
    },

    orderDistance() {
      return this.distance(
        this.orderData.contactAddressLatitud,
        this.orderData.contactAddressLongitud,
        this.location[0],
        this.location[1]
      )
    },
    /** orderType
			0 待接单、
			1 待预约、
			2 待签到、
			3 待完工、
			4 审核中、
			5 异常单、
			6 已完工
			*/
    orderType() {
      /*
				orderStatus:
					待接单	orderStatus<31																	                        工单状态小于31
					待预约	orderStatus == 31  and appointmentDatetime == null								      工单状态等于30并且预约时间为空
					待签到	orderStatus == 31  and appointmentDatetime is not null						    	工单状态等于30并且预约时间不为空
					待完工	orderStatus >31 and orderStatus < 80										               	工单状态大于31 小于80
					审核中	orderStatus ==83 or  orderStatus == 87	 or  orderStatus == 88					工单状态 等于83 或者 等于85 或者 等于87 或者 等于88
					异常		orderStatus ==86															                        	工单状态 等于86
					已完工	orderStatus in(80,81,89,110)													                  工单状态 等于80 or 81 or 89 or 110
				*/
      if (this.type && this.typeList.indexOf(this.type) != -1) {
        return this.types[this.type]
      } else {
        // 没传或传错type
        if (this.orderData.orderStatus < 31) {
          return 0
        } else if (this.orderData.orderStatus == 31) {
          if (this.orderData.appointmentDatetime) {
            return 2
          } else {
            return 1
          }
        } else if (
          this.orderData.orderStatus > 31 &&
          this.orderData.orderStatus < 80
        ) {
          return 3
        } else if (
          this.orderData.orderStatus == 83 ||
          this.orderData.orderStatus == 85 ||
          this.orderData.orderStatus == 87 ||
          this.orderData.orderStatus == 88
        ) {
          return 4
        } else if (this.orderData.orderStatus == 86) {
          return 5
        } else if (
          [80, 81, 89, 110].indexOf(this.orderData.orderStatus) != -1
        ) {
          return 6
        } else {
          return 0
        }
      }
    },
  },
  created() {
    this.updateTime()
  },
  watch: {
    'orderData.currentCellTime'(val) {
      // 从后台重新获取数据之后，时间重新计算
      this.updateTime()
    },
  },
  methods: {
    handleExceptions() {
      if (this.isException) {
        getApp().track('order_handleExceptions', {})
      }
    },
    // title:标题，showCountTime：是否显示倒计时。详情页面情况太多，提前传值可以避免页面晃动
    handleClick() {
      var func = 'click'
      this.handleExceptions()
      // 不是待完工、审核中、异常单、已完工点按钮算点cell
      if ([3, 4, 5, 6].indexOf(this.orderType) != -1) {
        func = 'action'
      }
      this.orderData.auditResults = this.auditResults
      this.$emit(
        func,
        this.orderData,
        this.realType,
        this.showCountTime ? 'show' : '',
      )
      this.otherAction()
    },
    handleClickCell() {
      if (this.isSimple) {
        this.handleClick()
        return
      }
      var func = 'click'
      this.handleExceptions()
      if (this.isException) {
        // 异常单点cell算点按钮
        func = 'action'
      }
      this.orderData.auditResults = this.auditResults
      this.$emit(
        func,
        this.orderData,
        this.realType,
        this.showCountTime ? 'show' : '',
      )
      this.otherAction()
    },
    // 如果是异常单告诉后台
    // 更新最近5条查看记录
    otherAction() {
      this.exceptionRecord()
      this.storeOparation()
    },
    exceptionRecord() {
      // 如果是异常单告诉后台
      if (this.realType == 'exception') {
        this.$u.api.workerDealWithError(this.orderData.orderId).then(() => {})
      }
    },
    storeOparation() {
      // 更新最近5条查看记录
      if (!this.isSimple) {
        var array = (this.vuex_last_five_orders || []).filter((id) => {
          // 如果记录中有该工单，删除
          return id != this.orderData.orderId
        })

        array.unshift(this.orderData.orderId)
        this.$u.vuex('vuex_last_five_orders', array.slice(0, 5))
      }
    },
    handleChange(timestamp) {
      if (this.timeout) this.$refs['order-count-down'].seconds += 2
      if (timestamp == 0 && !this.timeout) {
        // 超时之后倒计时变为正计时
        setTimeout(() => {
          this.timestamp = 1
          this.timeout = true
        }, 1000)
      }
    },
    // formatAddress(order) {
    //   let address = ''
    //   if (order) {
    //     address = order.contactProvinceText || ''
    //     address += order.contactCityText || ''
    //     address += order.contactCommunityText || ''
    //     address += order.contactStreetText || ''
    //     address += order.contactAddress || ''
    //   }
    //   return address
    // },
    /**
     * 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) / 10000 //输出为米
      return Number(s ? s.toFixed(2) : 0)
    },
    Rad(d) {
      return (d * Math.PI) / 180.0 //经纬度转换成三角函数中度分表形式。
    },
    updateTime() {
      var time = new Date().getTime()
      this.timeout = this.orderData.currentOverTime < time
      this.timestamp = Math.round(
        Math.abs(this.orderData.currentOverTime - time) / 1000
      )
    },
    handleLongpress(key, text) {
      // 长按复制单号
      if (key == 'partnerSerialNumber') {
        uni.setClipboardData({
          data: text,
          success: function() {
            console.log('success')
          },
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.order-view {
  // width: 100%;
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  .hover-class {
    background-color: #dddddd;
  }
  &.simple {
    margin: 20rpx 30rpx;
    padding-top: 12rpx;
    box-shadow: 0 0 16rpx rgba(51, 51, 51, 0.1);
  }
  .order-top-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .left-view {
      display: flex;
      align-items: center;

      .tag-view {
        text-align: center;
        width: 84rpx;
        height: 40rpx;
        color: #ffffff;
        border-radius: 8rpx;
        background-image: linear-gradient(to right, #ff930d, #ffc174);
        font-size: 22rpx;
        line-height: 42rpx;
        &.active {
          background-image: linear-gradient(to right, #2272ff, #47abff);
        }
      }

      .store-view {
        color: #333333;
        font-size: 36rpx;
        font-weight: bold;
        margin-left: 20rpx;
      }
    }

    .right-view {
      text-align: center;
      width: 100rpx;
      height: 40rpx;
      background-color: #f4f5f7;
      border-radius: 20rpx;
      color: #333333;
      font-size: 22rpx;
      line-height: 40rpx;
    }
  }

  .content-view {
    .info-view {
      text-align: left;
      color: #333333;
      font-size: 26rpx;
      margin-top: 18rpx;
      margin-bottom: 18rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .info-left-view {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .symbol-view {
          background-color: #2272ff;
          width: 6rpx;
          height: 28rpx;
          border-radius: 6rpx;
          margin-right: 10rpx;
        }
        .info-title {
          flex-shrink: 0;
          align-items: center;
        }
        .info-content {
          word-break: break-all;
        }
      }
    }

    .address-view {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      color: #333333;
      font-size: 24rpx;
      margin-top: 20rpx;

      .address-left-view {
        display: flex;
        align-items: center;
        align-items: flex-start;
        text-align: left;

        .address-image {
          width: 26rpx;
          height: 28rpx;
          margin-right: 8rpx;
          flex-shrink: 0;
          margin-top: 4rpx;
        }
      }

      .address-right-view {
        margin-left: 30rpx;
      }
    }
  }

  .line-view {
    background-color: #f4f5f7;
    height: 2rpx;
    width: 100%;
    margin-top: 30rpx;
  }

  .reason-view {
    text-align: left;
    margin-top: 30rpx;
    font-size: 26rpx;
    color: #fa5a49;
    display: flex;
    align-items: flex-start;
    display: flex;
    .reason-title {
      flex-shrink: 0;
      color: #666666;
    }
    .reason-text {
      display: flex;
      flex-direction: column;
    }
  }

  .bottom-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 30rpx;

    .bottom-left-view {
      display: flex;
      align-items: center;

      .bottom-tag-view {
        width: 52rpx;
        height: 52rpx;
        border-radius: 26rpx;
        color: #ffffff;
        font-size: 26rpx;
        background-color: #ff930d;
        margin-right: 16rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        &.timeout {
          background-color: #fa5a49;
        }
      }
    }
  }
}
</style>
