import request from '@/helpers/request'
import {
  Divider,
  Cell,
  CellGroup,
  Button,
  Toast,
  Steps,
  Step,
  Dialog
} 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 { dateFormat, moneyFormat } from '@/helpers/utils'
import ColSticky from '@/components/col-sticky'
import ColHeader from '@/components/col-header'

export default defineComponent({
  name: 'shop-order-detail',
  setup() {
    const route = useRoute()
    const items = ref([])
    const order = ref({}) as any
    const deliveryList = ref([])
    const getOrderInfo = async () => {
      const id = route.query.id
      if (!id) return
      try {
        const { 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('')

          // 判断是否有订单号
          if (data.deliverySn) {
            await getCourier(data.deliverySn)
          }
        }
      } 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)
        document.querySelector('#input-copy-container')?.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()
        }
      }
    }

    // 获取物流信息
    const getCourier = async (deliverySn: string) => {
      try {
        const { data } = await request.get(
          '/api-mall-portal/order/selectCourier',
          {
            params: {
              deliverySn
            }
          }
        )
        const logistics = data.logistics ? JSON.parse(data.logistics) : []
        console.log(logistics)
        deliveryList.value = logistics
      } catch {
        //
      }
    }

    // 确认收货
    const onConfirmReceipt = async (item: any) => {
      const dialog = await Dialog.confirm({
        title: '提示',
        message: '确认收货?',
        confirmButtonText: '收货',
        confirmButtonColor: 'var(--van-primary)'
      })
      if (dialog === 'confirm') {
        const res = await request.post(
          '/api-mall-portal/order/confirmReceiveOrder',
          { params: { orderId: item.id } }
        )
        if (res.code === 200) {
          getOrderInfo()
        }
      }
    }

    return () => (
      <>
        <ColHeader />
        {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?.couponAmount)}
                ></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 id="input-copy-container"></div>
              </div>

              {/* 判断是否有物流单号 */}
              {deliveryList.value.length > 0 && (
                <div class={styles.box} style={{ padding: 0 }}>
                  <CellGroup title="物流信息" border={false}>
                    <Steps
                      direction="vertical"
                      active={0}
                      activeColor={'var(--van-primary)'}
                    >
                      {deliveryList.value.map((item: any) => (
                        <Step>
                          <h3 class={styles.logisticsTitle}>{item.context}</h3>
                          <p class={styles.logisticsTime}>
                            {dateFormat(item.time, 'YYYY-MM-DD HH:mm')}
                          </p>
                        </Step>
                      ))}
                    </Steps>
                  </CellGroup>
                </div>
              )}
            </div>
            {order.value.status === 2 && (
              <ColSticky position="bottom" background="white">
                <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
                  <Button
                    block
                    round
                    type="primary"
                    onClick={() => {
                      onConfirmReceipt(order.value)
                    }}
                  >
                    确认收货
                  </Button>
                </div>
              </ColSticky>
            )}
          </>
        ) : null}
      </>
    )
  }
})
