<template>
  <div>
    <el-dialog width="400px" :title="title" v-model="show" @close="reset">
      <div class="u-p-15">
        <div v-if="openSwitch" class="openSwitch">
          <el-button size="large" @click="changeKey('paysSel', index)" v-for="(item, index) in pays" :key="index"
            :type="paysSel == index ? 'primary' : ''">
            <img :src="item.icon" alt="" style="width: 30px; height: 30px; margin-right: 10px" />
            <span>
              {{ item.text }}
            </span>
          </el-button>
        </div>
        <div class="u-m-t-20 flex flex-col">
          <el-alert :closable="false" v-if="tips" :title="tips" type="warning" show-icon></el-alert>
        </div>
        <div class="u-m-t-20 flex justify-center">
          <el-form label-width="90px" label-position="left">
            <el-form-item label="" label-width="0">
              <el-input v-model="form.code" @change="codeInputChange" placeholder="请扫码或者输入券码" ref="refInputCode"
                :disabled="!pays[this.paysSel].status"></el-input>
            </el-form-item>
            <div class="u-flex u-row-center u-m-t-50">
              <el-button @click="close">取消</el-button>
              <el-button type="primary" :disabled="!pays[this.paysSel].status" @click="confirm">确定</el-button>
            </div>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <bind-shop ref="refBindShop"></bind-shop>
    <choose-goods ref="refChooseGoods" @hexiaoSuccess="hexiaoSuccess"></choose-goods>
  </div>
</template>
<script>
import { useUserStore } from "@/store/modules/user";
import { getDouyinToken, setDouyinToken } from "@/utils/auth";
import meituanIcon from "@/assets/icons/meituan.png";
import tiktokIcon from "@/assets/icons/douyin.png";

const user = useUserStore();
import * as $Api from "@/api/coup/index.js";
import { searchstorestatus, thirdPartyCoupon_bindUrl, getuisdk } from '@/api/coup/group'
import orderApi from "@/api/order/order";
import bindShop from "./douyin-quan-bind-shop.vue";
import chooseGoods from "./choose-quan-goods.vue";
import { ElMessage, ElMessageBox } from "element-plus";
export default {
  components: { bindShop, chooseGoods },
  props: {
    openSwitch: {
      type: Boolean,
      default: true,
    },
    order: {
      type: Object,
      default: () => ({}),
    },
    title: {
      type: String,
      default: "团购券核销",
    },
    price: {
      type: [String, Number],
      default: 0,
    },
    defaultTips: {
      type: String,
      default: "请使用扫码枪扫描付券码",
    },
  },
  filters: {
    to2(n) {
      return n.toFixed(2);
    },
  },
  data() {
    return {
      tips: "",
      paysSel: 0,
      form: {
        code: "",
      },
      pays: [
        {
          text: "美团",
          clint_type: 1,
          status: 0,
          icon: meituanIcon,
        },
        {
          text: "抖音",
          clint_type: 2,
          status: 0,
          icon: tiktokIcon,
        },
      ],
      show: false,
    };
  },
  watch: {
    defaultTips(val) {
      this.tips = val;
    },
    price(val) {
      console.log(val);
      this.form.money = Number(val).toFixed(2);
    },
    number(newval) {
      this.$emit("input", newval);
    },
  },
  methods: {
    // 查询抖音/美团绑定的状态
    async searchstorestatus() {
      try {
        const { mt_status, dy_status } = await searchstorestatus(this.pays[this.paysSel].clint_type)
        // console.log('查询抖音/美团绑定的状态', mt_status, dy_status);

        this.pays.forEach(item => {
          if (item.clint_type == 1) {
            item.status = mt_status
          }
          if (item.clint_type == 2) {
            item.status = dy_status
          }
        })

        if (this.pays[this.paysSel].clint_type == 1 && this.pays[this.paysSel].status == 0) {
          // 如果没有绑定，先提示用户去绑定
          const res = await thirdPartyCoupon_bindUrl()
          ElMessageBox.confirm('您的店铺还未绑定美团，请绑定后操作！', '注意', {
            confirmButtonText: '去绑定'
          }).then(() => {
            window.open(res)
          }).catch(() => { })
        }

        if (this.pays[this.paysSel].clint_type == 2 && this.pays[this.paysSel].status == 0) {
          // 如果没有抖音，先提示用户去绑定
          const res = await getuisdk()
          ElMessageBox.confirm('您的店铺还未绑定抖音，请绑定后操作！', '注意', {
            confirmButtonText: '去绑定'
          }).then(() => {
            window.open(res)
          }).catch(() => { })
        }
      } catch (error) {
        console.log(error);
      }
    },
    refChooseGoodsOpen(data, types) {
      this.$refs.refChooseGoods.open(data, types);
    },
    refBindShopOpen() {
      this.$refs.refBindShop.open();
    },
    clear() {
      clearInterval(this.timer);
    },
    hexiaoSuccess() {
      this.reset();
      this.close();
    },
    async getOrderDetail() {
      const res = await tbOrderInfoDetail(this.order.id);
      if (res.status == "closed") {
        this.clear();
        this.$emit("paySuccess");
      }
    },
    codeInputChange(e) {
      console.log(e);
      // this.$emit("confirm", this.form.code);
    },
    reset() {
      // this.form.money=''
      this.form.code = "";
      this.paysSel = 0;
      this.clear();
    },
    changeKey(key, val) {
      this[key] = val;
      this.$nextTick(() => {
        this.$refs.refInputCode.focus(); //获取焦点
      });

      this.searchstorestatus()
    },

    async confirm() {
      if (!this.form.code) {
        return ElMessage.error("请输入或扫付券码");
      }

      if (this.paysSel === 1) {
        //抖音
        const res = await $Api.$douyin_fulfilmentcertificateprepare({
          object_id: this.form.code,
        });
        if (res.code == 4399) {
          this.refBindShopOpen();
        } else {
          console.log(res, 1111);
          // if (res.code == 1) {
          this.refChooseGoodsOpen(res);
          // }
        }
        return;
      }
      if (this.paysSel === 0) {
        //美团
        const res = await $Api.$meituan_searchstorestatus({});
        if (res.status == 0) {
          const res2 = await $Api.$meituan_getuisdkurl({});
          ElMessageBox.confirm("未绑定美团店铺，是否立即绑定", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then((action) => {
              if (action == "confirm") {
                window.open(res2);
              }
            })
            .catch(() => { });
          return;
        }
        const res1 = await $Api.$meituan_fulfilmentcertificateprepare({
          code: this.form.code,
        });
        if (res1) {
          const types = "meituan";
          this.refChooseGoodsOpen(res1, types);
        }
      }
      //   ElMessage.success("核销成功");
    },
    open(data) {
      this.show = true;
      $Api
        .$douyin_checkIn({
          loginName: user.userInfo.phone,
        })
        .then((res) => {
          console.log(res);
          setDouyinToken(res.userInfo.token);
        });
      setTimeout(() => {
        this.$refs.refInputCode.focus();
      }, 100);

      this.searchstorestatus()
    },
    close() {
      this.show = false;
    },
    numberInput(val) {
      console.log(val);
      this.number = `${Number(val)}`;
    },
    keyboradConfirm() {
      this.$emit("confirm", this.number);
    },
  },
  mounted() {
    this.number = `${this.value}`;
    this.tips = this.defaultTips;
  },
};
</script>

<style lang="scss" scoped>
.codeImg {
  width: 164px;
  border: 1px solid rgb(220, 223, 230);
  height: 164px;
  overflow: hidden;
}

.openSwitch {
  display: flex;
  justify-content: center;
}

.flex {
  display: flex;
}

.justify-center {
  justify-content: center;
}

:deep(.el-form) {
  width: 200px;
}

:deep(.el-alert) {
  width: inherit;
}

.flex-col {
  flex-direction: column;
}
</style>
