import {
  Button,
  Cell,
  CellGroup,
  Field,
  Popup,
  Radio,
  RadioGroup,
  showToast
} from 'vant';
import { defineComponent, reactive } from 'vue';
import styles from './item.module.less';
import icon_order from '../image/icon_order.svg';
import {
  api_userPaymentOrderCancelPayment,
  api_userPaymentOrderDetail,
  api_userPaymentOrderRefundPayment,
  api_userPaymentOrderUnpaid,
  type_OrderTypes
} from '../api';
import { postMessage } from '@/helpers/native-message';
import { state } from '@/state';

export default defineComponent({
  name: 'collection-record-item',
  props: {
    item: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['refund', 'close'],
  setup(props, { emit }) {
    const data = reactive({
      open: false,
      order: {} as any,
      confirmLoading: false,
      cancelOrderLoading: false
    });
    const forms = reactive({
      refundReason: '',
      refundReasonDes: ''
    });

    const handleOpenDetail = () => {
      if (props.item?.orderNo) {
        const url = `${location.origin}${
          location.pathname
        }#/collection-record-detail?orderNo=${props.item?.orderNo}${
          props.item.isRefund
            ? '&userRefundOrderId=' + props.item.userRefundOrderId
            : ''
        }`;
        console.log('🚀 ~ url:', url);
        postMessage({
          api: 'openWebView',
          content: {
            url,
            orientation: 1,
            isHideTitle: false
          }
        });
      }
    };

    const getDetails = async (item: any) => {
      if (!item.orderNo) return;
      const res = await api_userPaymentOrderDetail(item.orderNo);
      if (res?.code === 200) {
        data.order = res.data;
      }
    };
    /** 申请退款 */
    const handleCancel = async () => {
      await api_userPaymentOrderRefundPayment({
        merOrderNo: data.order.orderNo,
        serviceCharge: true,
        paymentClient: 'STUDENT',
        userId: state.user?.data?.id,
        refundReason:
          forms.refundReason === '其他原因'
            ? forms.refundReasonDes
            : forms.refundReason,
        userPaymentOrderId: data.order.id,
        userRefundOrderDetails: data.order.goodsInfos
          ? data.order.goodsInfos
              .filter((n: any) => n.goodsType !== 'VIP')
              .map((goods: any) => ({
                userPaymentOrderDetailId: goods.id,
                num: goods.goodsNum
              }))
          : []
      });
      showToast('申请退回成功');
      data.open = false;
      emit('close');
      emit('refund');
    };

    /** 继续支付 */
    const onConfirmOrder = async () => {
      console.log(props.item);
      data.confirmLoading = true;
      const res = await api_userPaymentOrderUnpaid({
        orderNo: props.item.orderNo,
        paymentType: props.item.orderType
      });
      data.confirmLoading = false;
      if (res?.code === 200) {
        const paymentConfig = res.data.paymentConfig;
        const url =
          location.origin +
          location.pathname +
          '#/order-detail?orderNo=' +
          paymentConfig.orderNo +
          '&config=' +
          JSON.stringify(paymentConfig.paymentConfig);
        console.log('🚀 ~ url:', url);
        postMessage({
          api: 'openWebView',
          content: {
            url,
            orientation: 1,
            isHideTitle: false
          }
        });
      }
    };

    /** 取消订单 */
    const handleCancelOrder = async () => {
      data.cancelOrderLoading = true;
      try {
        await api_userPaymentOrderCancelPayment(props.item.orderNo);
        setTimeout(() => {
          showToast('取消成功');
          emit('close');
        }, 100);
      } catch {
        //
      }
      data.cancelOrderLoading = false;
    };
    return () => (
      <div class={styles.item}>
        <CellGroup inset>
          <Cell center>
            {{
              title: () => (
                <div class={styles.time}>{props.item.createTime}</div>
              ),
              value: () => (
                <div
                  class={[styles.state]}
                  style={{ color: props.item.statusColor }}>
                  {props.item.statusName}
                </div>
              )
            }}
          </Cell>
          <Cell center isLink onClick={() => handleOpenDetail()}>
            {{
              icon: () => <img class={styles.icon} src={icon_order} />,
              title: () => (
                <div class={styles.name}>
                  {type_OrderTypes[props.item.orderType]}
                </div>
              ),
              value: () => (
                <div class={styles.price}>
                  ¥
                  <span style={{ fontSize: '0.42667rem' }}>
                    {props.item.paymentCashAmount}
                  </span>
                </div>
              )
            }}
          </Cell>
          {['WAIT_PAY', 'PAYING'].includes(props.item.status) &&
            props.item.orderType !== 'SCHOOL_REGISTER' && (
              <div class={styles.btns}>
                <Button
                  style={{ margin: '0 11px 0 auto' }}
                  round
                  size="small"
                  loading={data.cancelOrderLoading}
                  onClick={() => handleCancelOrder()}>
                  取消领取
                </Button>
                <Button
                  round
                  size="small"
                  loading={data.confirmLoading}
                  onClick={() => onConfirmOrder()}>
                  继续领取
                </Button>
              </div>
            )}
          {props.item.refundable && (
            <div
              class={[styles.btns, styles.cancelBtn]}
              onClick={() => {
                data.open = true;
                getDetails(props.item);
              }}>
              申请退回
            </div>
          )}
        </CellGroup>

        <Popup
          teleport="body"
          v-model:show={data.open}
          class={['popup-custom', 'van-scale']}
          transition="van-scale">
          <div class={styles.cancelBox}>
            <div class={styles.boxContent}>
              <div class={styles.title}>
                <div class={styles.titleTag}></div> 申请退回
              </div>
              <div class={styles.des}>
                您将要发起退回，退回需承担千分之六的手续费，确认退回后款项将原路返还到您的付款账户中。
              </div>
              <div class={styles.radioTitle}>
                <span style={{ color: 'rgba(244, 69, 65, 1)' }}>*</span>
                请选择您的退回原因
              </div>
              <RadioGroup v-model={forms.refundReason}>
                <Cell>
                  {{
                    title: () => (
                      <div>
                        <Radio name="价格太贵了">价格太贵了</Radio>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div>
                        <Radio name="不喜欢/不想要">不喜欢/不想要</Radio>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div>
                        <Radio name="七天无理由退货">七天无理由退货</Radio>
                      </div>
                    )
                  }}
                </Cell>
                <Cell>
                  {{
                    title: () => (
                      <div>
                        <Radio name="其他原因">其他原因</Radio>
                      </div>
                    )
                  }}
                </Cell>
              </RadioGroup>
              <div
                class={styles.radioDes}
                style={{
                  display: forms.refundReason === '其他原因' ? '' : 'none'
                }}>
                <Field
                  v-model={forms.refundReasonDes}
                  rows="2"
                  autosize
                  label=""
                  type="textarea"
                  maxlength="50"
                  placeholder="在这里填写退回原因"
                />
              </div>
            </div>
            <div class={styles.radioBtns}>
              <Button
                block
                onClick={() => {
                  if (!forms.refundReason) {
                    showToast('请选择退回原因');
                    return;
                  }
                  if (
                    forms.refundReason === '其他原因' &&
                    !forms.refundReasonDes
                  ) {
                    showToast('请输入退回原因');
                    return;
                  }
                  handleCancel();
                }}>
                确认退回
              </Button>
              <Button
                block
                type="primary"
                plain
                onClick={() => (data.open = false)}>
                取消
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
