import { TimeController } from "@/controllers/TimeController";
import { initPayment } from "@/modules/payment";
import { css } from "@linaria/core";
import { useAuth } from "@queenjs-modules/auth";
import { InputNumber } from "ant-design-vue";
import { queenApi } from "queenjs";
import Modal from "queenjs/adapter/vue/components/modal";
import { defineComponent, reactive } from "vue";
import PayQrcode from "./PayQrcode";
import { IconScan, IconTransfer } from "@/assets/icons";

export default defineComponent({
  setup() {
    const auth = useAuth();
    const payment = initPayment({
      config: { project: "queenshow" },
    });
    const { store, https, actions } = payment;

    const payVersions = [
      {
        label: "个人",
        children: [
          "queenshow_person_year",
          "queenshow_person_month",
          // "queenshow_point_test",
        ],
      },
      {
        label: "团队",
        children: [
          "queenshow_team_15month",
          "queenshow_team_year",
          "queenshow_team_month",
        ],
      },
    ];

    const payWays = [
      {
        label: "快捷支付",
        icon: IconScan,
      },
      {
        label: "对公转账",
        icon: IconTransfer,
      },
    ];

    const payMethods: Record<string, { label: string; icon: string }> = {
      wechatPay: {
        label: "微信支付",
        icon: require("@/assets/imgs/icon-wx.png"),
      },
      aliPay: {
        label: "支付宝支付",
        icon: require("@/assets/imgs/icon-zfb.png"),
      },
    };

    const payPointsInfo: Record<
      string,
      {
        name: string;
        desc: string;
        default: { quantity: number; number: number };
        quantityProps?: any;
        numberProps?: any;
        quantityUnit?: string;
        priceTip?: string;
      }
    > = {
      // queenshow_point_test: {
      //   name: "测试",
      //   desc: "xxxx",
      //   default: {
      //     quantity: 1,
      //     number: 1,
      //   },
      // },
      queenshow_person_year: {
        name: "一年VIP",
        desc: "高性价比之选",
        default: {
          quantity: 1,
          number: 1,
        },
      },
      queenshow_person_month: {
        name: "月度VIP",
        desc: "续费价199.0元",
        default: {
          quantity: 1,
          number: 1,
        },
        quantityProps: {
          min: 1,
        },
        quantityUnit: "月",
      },
      queenshow_team_15month: {
        name: "15个月/人",
        desc: "鲲舞精心之选",
        priceTip: "团购30人以上",
        default: {
          quantity: 1,
          number: 30,
        },
        numberProps: {
          min: 30,
        },
      },
      queenshow_team_year: {
        name: "年VIP/人",
        desc: "高性价比之选",
        default: {
          quantity: 1,
          number: 1,
        },
        numberProps: {
          min: 1,
        },
      },
      queenshow_team_month: {
        name: "月VIP/人",
        desc: "续费价199.0元",
        default: {
          quantity: 1,
          number: 1,
        },
        numberProps: {
          min: 1,
        },
        quantityProps: {
          min: 1,
        },
        quantityUnit: "月",
      },
    };

    const state = reactive({
      versionIdx: 0,
      payWayIdx: 0,
      orderInfo: {
        productKey: "",
        quantity: 0,
        number: 0,
      },
      amountPrice: 0,
    });

    function changeVersion(idx: number) {
      state.versionIdx = idx;
      initOrderInfo(payVersions[idx].children[0]);
    }

    function initOrderInfo(productKey: string) {
      state.orderInfo = {
        productKey,
        ...payPointsInfo[productKey].default,
      };
    }

    function changeOrderInfo(
      type: keyof (typeof state)["orderInfo"],
      value: any
    ) {
      (state.orderInfo as any)[type] = value;
      if (type === "productKey") {
        initOrderInfo(value);
      }
      updateOrderAmount();
    }

    function updateOrderAmount() {
      https.getPayAmount(state.orderInfo).then((ret) => {
        state.amountPrice = ret.result;
      });
    }

    async function createOrderQrcode(payMod: number) {
      queenApi.showLoading("加载中");
      try {
        // const orderId = "64b764473d1915628fe24045";
        // const link = "64b764473d1915628fe24045";
        const { orderId, link } = await actions.createOrder(payMod, {
          ...state.orderInfo,
          amount: state.amountPrice,
        });

        const orderStatusCtrl = new TimeController({
          delayTime: 8000,
          durationTime: 3000,
        });
        orderStatusCtrl
          .setLoop(async () => {
            const { result } = await https.getOrderDetail({ id: orderId });
            if (result.status === 2) {
              orderStatusCtrl.stop();
              Modal.clear();
              auth.actions.getUserInfo();
            }
          })
          .start();

        queenApi
          .dialog(
            <PayQrcode orderId={orderId} link={link} />,
            {
              closable: false,
            },
            { payment }
          )
          .catch(() => {
            orderStatusCtrl.stop();
          });
      } catch (error: any) {
        queenApi.messageError(error.toString());
      } finally {
        queenApi.hideLoading();
      }
    }

    changeOrderInfo("productKey", payVersions[state.versionIdx].children[0]);

    return () => {
      const { saas } = auth.store.userInfo as any;
      const currPayInfo = payPointsInfo[state.orderInfo.productKey];
      const currPayPoint = store.payPoints.find(
        (d) => d.productKey === state.orderInfo.productKey
      );
      return (
        <div class={rootCls}>
          <header class="p-0.24rem">
            <div class="flex">
              <img
                class="w-0.48rem h-0.48rem rounded-[50%]"
                src={auth.store.userInfo.avatar}
              />
              <div class="ml-0.14rem space-y-0.08rem">
                <div class="text-0.2rem font-500 text-white">
                  {auth.store.userInfo.name}
                </div>
                <div class="text-0.16rem font-500 text-[#888]">
                  {saas ? "会员版" : "免费版"}
                </div>
              </div>
            </div>
          </header>
          <main>
            <section class="w-2.95rem mr-0.24rem space-y-0.2rem">
              <div class="flex items-center">
                <img
                  class="w-0.22rem h-0.22rem mr-0.1rem"
                  src={require("@/assets/imgs/icon-vip.png")}
                />
                <span class="text-0.22rem text-[#222]">会员版</span>
              </div>
              <p>适合个人创作设计，如个人新媒体、个人网店、直播带货等</p>
              <div class="splitline"></div>
              <ul class="pl-0.16rem leading-0.24rem space-y-0.12rem">
                <li>个人或企业商用授权（选购）</li>
                <li>VIP专属内容</li>
                <li>模版创建无上限</li>
                <li>鲲秀AI使用权限</li>
                <li>专属客服/正规发票</li>
              </ul>
            </section>
            <div class="flex-1 space-y-0.18rem">
              <section>
                <label class="">购买版本</label>
                {payVersions.map((d, i) => {
                  return (
                    <span
                      key={i}
                      class={["checkbox", i === state.versionIdx && "checked"]}
                      onClick={() => changeVersion(i)}
                    >
                      {d.label}
                    </span>
                  );
                })}
              </section>
              <section>
                <label>价格选择</label>
                <div class="mt-0.24rem">
                  {payVersions[state.versionIdx].children.map((d, i) => {
                    const item = payPointsInfo[d as keyof typeof payPointsInfo];
                    const price =
                      store.payPoints.find((p) => p.productKey === d)?.price ||
                      0;
                    return (
                      <div
                        key={i}
                        class={[
                          "checkbox priceBox",
                          state.orderInfo.productKey === d && "checked",
                        ]}
                        onClick={() => changeOrderInfo("productKey", d)}
                      >
                        {item.priceTip && (
                          <div class="priceTip">{item.priceTip}</div>
                        )}
                        <div class="text-0.16rem font-bold text-[#666] pt-0.16rem ">
                          {item.name}
                        </div>
                        <div class="text-0.3rem font-bold">
                          <span class="text-0.14rem">&yen;</span>
                          {price.toFixed(1)}
                        </div>
                        <div class="text-0.14rem text-[#666] pt-0.16rem ">
                          {item.desc}
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div class="mt-0.28rem text-[#111]">
                  {currPayInfo.numberProps && (
                    <>
                      <span class="text-0.16rem font-bold">人数选择：</span>
                      <InputNumber
                        class="inputNum"
                        value={state.orderInfo.number}
                        onChange={(v) => changeOrderInfo("number", v)}
                        {...currPayInfo.numberProps}
                      />
                      <span class="text-0.16rem text-[#666] mr-0.85rem">
                        人
                      </span>
                    </>
                  )}
                  {currPayInfo.quantityProps && (
                    <>
                      <span class="text-0.16rem font-bold">时长设置：</span>
                      <InputNumber
                        class="inputNum"
                        value={state.orderInfo.quantity}
                        onChange={(v) => changeOrderInfo("quantity", v)}
                        {...currPayInfo.quantityProps}
                      />
                      <span class="text-0.16rem text-[#666]">
                        {currPayInfo.quantityUnit}
                      </span>
                    </>
                  )}
                </div>
              </section>
              <section>
                <label class="">支付订单</label>
                <div class="payMethod flex">
                  <div class="py-0.24rem space-y-0.14rem">
                    {payWays.map((d, i) => {
                      return (
                        <div
                          class={[
                            "payTabItem",
                            state.payWayIdx === i && "checked",
                          ]}
                          key={i}
                          onClick={() => (state.payWayIdx = i)}
                        >
                          <d.icon class="mr-0.08rem" />
                          {d.label}
                        </div>
                      );
                    })}
                  </div>

                  <div class="flex-1 ml-0.3rem">
                    <div class="text-0.16rem font-bold my-0.3rem">
                      <span class="text-[#333]">实付款：</span>
                      <span class="text-0.3rem text-[#D34D39]">
                        {state.amountPrice}
                      </span>
                      <span class="text-[#D34D39]">元</span>
                    </div>
                    {state.payWayIdx === 0 && (
                      <div>
                        {currPayPoint?.payMethods.map((d, i) => {
                          const item = payMethods[d.Key];
                          const isLast =
                            currPayPoint.payMethods.length === i + 1;
                          return (
                            <>
                              <div
                                class="payBtn"
                                key={d.Key}
                                onClick={() => createOrderQrcode(d.Value)}
                              >
                                <img
                                  class="h-0.2rem mr-0.1rem"
                                  src={item.icon}
                                />
                                {item.label}
                              </div>
                              {!isLast && (
                                <span class="mx-0.1rem align-text-bottom">
                                  或
                                </span>
                              )}
                            </>
                          );
                        })}
                      </div>
                    )}
                    {state.payWayIdx === 1 && (
                      <div class="text-0.16rem space-y-0.1rem">
                        <div class="transfer-row">
                          <span>户名</span>成都中鱼互动科技有限公司
                        </div>
                        <div class="transfer-row">
                          <span>开户行</span>中国银行成都益州支行
                        </div>
                        <div class="transfer-row">
                          <span>帐号</span>1185 5686 4401
                        </div>
                        <div class="transfer-row">
                          <span>备注</span>注册手机号+购买版本+人数+时长
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </section>
            </div>
          </main>
        </div>
      );
    };
  },
});

const rootCls = css`
  margin: -24px;

  header {
    background-color: #2a2d41;
  }
  main {
    display: flex;
    padding: 0.24rem;
    background-color: #f1f2f4;
    color: #666;
  }
  section {
    padding: 0.24rem;
    background-color: #fff;
    border-radius: 0.08rem;

    label {
      margin-right: 0.4rem;
      font-size: 0.2rem;
      color: #111;
    }
  }

  .checkbox {
    display: inline-block;
    padding: 0.16rem;
    margin-right: 0.3rem;
    min-width: 1.4rem;
    border: 1px solid rgba(51, 51, 51, 0.3);
    border-radius: 0.06rem;
    font-size: 0.18rem;
    color: #333;
    text-align: center;
    cursor: pointer;

    &.priceBox {
      position: relative;
      display: inline-flex;
      flex-direction: column;
      justify-content: space-between;
      width: 1.6rem;
      height: 1.6rem;
      vertical-align: top;
      text-align: left;
    }

    &.checked {
      border: 1px solid #885428;
      background-color: #fff7e8;
      color: #885428;
      * {
        color: #885428;
      }
    }

    .priceTip {
      position: absolute;
      top: 0;
      right: 0;
      padding: 0.06rem 0.1rem;
      font-size: 0.12rem;
      line-height: 1;
      background-color: #93643d;
      color: #fff7e8;
      border-top-right-radius: 0.04rem;
      border-bottom-left-radius: 0.04rem;
    }
  }

  .splitline {
    border-bottom: 1px solid #e0e0e0;
  }

  .payTabItem {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 1.58rem;
    height: 0.58rem;
    color: #666;
    border-radius: 0.06rem;
    cursor: pointer;

    &.checked {
      background-color: #f1f2f4;
      color: #333;
    }
  }

  .payMethod {
    margin-top: 0.24rem;
    border-top: 1px solid #e0e0e0;
  }

  .payBtn {
    display: inline-flex;
    width: 2rem;
    justify-content: center;
    align-items: center;
    padding: 0.12rem;
    border: 1px solid #e0e0e0;
    border-radius: 0.06rem;
    cursor: pointer;
  }

  .inputNum {
    @apply w-1.8rem mx-0.16rem border-[#c9c9c9] text-[#111];
  }

  .transfer-row{
    span {
      display: inline-block;
      width: 0.6rem;
    }
  }
`;
