import request from '@/helpers/request'
import { Divider, Cell, CellGroup, Button, Toast } from 'vant'
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import ShopItem from '../components/shop-item'
import styles from './index.module.less'
import { orderState } from '@/views/shop-mall/shop-mall'
import { moneyFormat } from '@/helpers/utils'

export default defineComponent({
  name: 'shop-order-detail',
  setup() {
    const route = useRoute()
    let items = ref([])
    let order = ref({}) as any
    const getOrderInfo = async () => {
      const id = route.query.id
      if (!id) return
      try {
        let { code, data } = await request.get(
          `/api-mall-portal/order/detail/${id}`
        )
        if (code === 200) {
          items.value = data.orderItemList
          delete data.orderItemList
          order.value = data
          order.value.address_data = [
            data.receiverProvince,
            data.receiverCity,
            data.receiverRegion,
            data.receiverDetailAddress
          ].join('')
        }
      } catch (error) {}
    }
    onMounted(() => {
      getOrderInfo()
    })

    const copyText = text => {
      // 数字没有 .length 不能执行selectText 需要转化成字符串
      const textString = text.toString()
      let input = document.querySelector('#copy-input') as HTMLInputElement
      if (!input) {
        input = document.createElement('input')
        input.id = 'copy-input'
        input.readOnly = true // 防止ios聚焦触发键盘事件
        input.style.position = 'absolute'
        input.style.left = '-1000px'
        input.style.zIndex = '-1000'
        document.body.appendChild(input)
      }

      input.value = textString
      // ios必须先选中文字且不支持 input.select();
      selectText(input, 0, textString.length)
      console.log(document.execCommand('copy'), 'execCommand')
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        Toast('复制成功')
      }
      input.blur()

      // input自带的select()方法在苹果端无法进行选择，所以需要自己去写一个类似的方法
      // 选择文本。createTextRange(setSelectionRange)是input方法
      function selectText(textbox, startIndex, stopIndex) {
        if (textbox.createTextRange) {
          //ie
          const range = textbox.createTextRange()
          range.collapse(true)
          range.moveStart('character', startIndex) //起始光标
          range.moveEnd('character', stopIndex - startIndex) //结束光标
          range.select() //不兼容苹果
        } else {
          //firefox/chrome
          textbox.setSelectionRange(startIndex, stopIndex)
          textbox.focus()
        }
      }
    }

    return () => (
      <>
        {items.value.length ? (
          <div class={styles.shopOrderDetail}>
            <div class={styles.box}>
              {items.value.map((item: any, index: number) => (
                <div>
                  <ShopItem item={item}></ShopItem>
                  {index === items.value.length - 1 ? null : (
                    <Divider></Divider>
                  )}
                </div>
              ))}
            </div>

            <div class={styles.box} style={{ padding: 0 }}>
              <Cell
                border={false}
                title="商品价格："
                value={'¥ ' + moneyFormat(order.value?.totalAmount)}
              ></Cell>
              <Cell
                border={false}
                title="订单金额："
                value={
                  '¥ ' +
                  moneyFormat(
                    order.value?.payAmount + order.value?.integrationAmount
                  )
                }
              ></Cell>
              <Cell
                border={false}
                title="优惠价格："
                value={'-¥ ' + moneyFormat(order.value?.couponAmount)}
              ></Cell>

              <Cell
                border={false}
                title="余额支付："
                value={moneyFormat(order.value?.integrationAmount)}
              ></Cell>
              <Cell
                border={false}
                title="现金支付："
                value={moneyFormat(order.value?.payAmount)}
              ></Cell>

              <Cell
                border={false}
                title="订单状态："
                value={orderState[order.value?.status]}
              ></Cell>
              <Cell
                border={false}
                title="收货状态："
                value={order.value?.confirmStatus ? '已确认收货' : '未确认收货'}
              ></Cell>
              <Divider style={{ margin: 0 }}></Divider>
              <Cell
                border={false}
                title="订单号："
                value={order.value?.orderSn}
              ></Cell>

              <Cell
                border={false}
                title="创建时间："
                value={order.value?.createTime}
              ></Cell>
              <Cell
                border={false}
                title="付款时间："
                value={order.value?.paymentTime}
              ></Cell>
            </div>

            <div class={styles.box} style={{ padding: 0 }}>
              <CellGroup title="收货信息" border={false}>
                <Cell
                  border={false}
                  title="姓名："
                  value={order.value?.receiverName}
                ></Cell>
                <Cell
                  border={false}
                  title="手机号："
                  value={order.value?.receiverPhone}
                ></Cell>
                <Cell
                  class={styles.addressDetail}
                  border={false}
                  title="地址："
                  value={order.value?.address_data}
                ></Cell>
                <Cell
                  class={styles.addressDetail}
                  border={false}
                  title="物流公司(配送方式):"
                  value={order.value?.deliveryCompany}
                ></Cell>
                <Cell
                  class={styles.addressDetail}
                  border={false}
                  title="运单编号："
                  v-slots={{
                    value: () => (
                      <div class={styles.copyWrap}>
                        <span style={{ marginRight: '8px' }}>
                          {order.value?.deliverySn}
                        </span>
                        {order.value?.deliverySn && (
                          <Button
                            size="mini"
                            onClick={evt => {
                              copyText(order.value?.deliverySn)
                            }}
                          >
                            点击复制
                          </Button>
                        )}
                      </div>
                    )
                  }}
                ></Cell>
              </CellGroup>
            </div>
          </div>
        ) : null}
      </>
    )
  }
})
