<template>
  <div>
    <van-overlay :show="value" :duration="0.1">
      <div class="unbuy-modal modal">
        <img src="../../../assets/img/top@2x.png" class="top" />
        <img src="../../../assets/img/unicmlogo.png" class="logo" />
        <div class="body-box">
          <div class="input-box">
            <div class="input">
              <input type="text" v-model="loginForm.phone" placeholder="手机号码" />
            </div>
          </div>
          <div class="input-box">
            <div class="input">
              <input type="text" v-model="loginForm.vcode" v-on:input="checkVcode" placeholder="验证码" />
            </div>
            <div :class="{ code: 1, number: codeState.state }" @click="getCode()">
              {{ codeState.state ? codeState.time + "s" : "获取验证码" }}
            </div>
          </div>
          <div class="input-box">
            <div class="input" style="text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">
              {{ radio === "0" ? "退订原因" : reason }}
            </div>
            <div class="code" style="color: #d6000f; text-align: end" @click="showSheet = true">
              请选择
            </div>
          </div>
          <div class="btn-box">
            <div class="btn right" @click="unbuy()">退订</div>
            <div class="btn left" @click="closeUnbuy">取消</div>
          </div>
          <div v-if="pageData.remarks.unBuyText" class="unBuyText">
            {{ pageData.remarks.unBuyText }}
          </div>
        </div>
      </div>
    </van-overlay>
    <vue-puzzle :show="showVcode" @success="onSuccessCode()"></vue-puzzle>
    <van-action-sheet lock-scroll close-on-popstate v-model="showSheet" title="退订原因" @close="closeSheet">
      <van-radio-group v-model="radio">
        <van-cell-group>
          <div class="rowList">
            <div v-for="(item, index) in resonList" style="width:50%" :key="index">
              <van-cell :key="index" :title="item.title" clickable @click="radioClick(item.value)">
                <template #right-icon>
                  <van-radio checked-color="#d6000f" :name="item.value" />
                </template>
              </van-cell>
            </div>
          </div>

        </van-cell-group>
        <div class="fileBox">
          <van-field v-model="message" rows="2" autosize type="textarea" placeholder="请描述原因，如遇到其他问题请反馈给我们" show-word-limit />
        </div>
        <!--        <div-->
        <!--          v-if=" radio === '3'"-->
        <!--          style="width: 90%; margin: 0 auto; font-size: 14px; color: #d6000f"-->
        <!--        >-->
        <!--          请填写退订原因-->
        <!--        </div>-->
        <div class="sureStyle" @click="sureClick">确定</div>
      </van-radio-group>
    </van-action-sheet>
    <!-- 挽回弹窗 -->
    <van-overlay :show="saveValue" :duration="0.1">
      <div class="opout-modal modal" @click.stop>
        <div class="text-box" v-if="memberInfo.joinTime && memberInfo.joinTime !== null">
          您于{{ memberInfo.joinTime }}已成功领取!
        </div>
        <div v-else class="text-box">
          非常抱歉给您使用带来不便，为您提供一份专属解决方案，您试试解决？
        </div>
        <div class="btn-box">
          <div v-if="radio === '1'" class="btn left" @click="saveClick(1)">
            试试解决
          </div>
          <div v-else-if="
              radio === '2' &&
              (memberInfo.joinTime === null || !memberInfo.joinTime)
            " class="btn left" @click="saveClick(2)">
            试试解决
          </div>
          <div v-else-if="
              radio === '2' &&
              memberInfo.joinTime !== null &&
              memberInfo.joinTime
            " class="btn left" @click="saveValue = false">
            确定
          </div>
          <div class="btn right" @click="savleUnbuy">坚持退订</div>
        </div>
      </div>
    </van-overlay>
    <!-- 合约提示 -->
    <van-overlay v-if="isTreaty == 1" :show="opoutShow" :duration="0.1">
      <div class="repeat-modal modal" @click.stop>
        <img src="../../../assets/img/close.png" class="close" @click="opoutShow = false" />
        <div class="text-box" v-if="text!==''">{{text}}</div>
        <div class="text-box" v-else>
          合约期外退订无需缴纳违约金，合约期内退订需一次性支付违约金话费<span style="color: red">{{ Number(product.originalPrice) - 0.01 }}</span>元，是否确认退订
        </div>
        <div class="btn-box">
          <div class="btn left" @click="unbuyClick">确定</div>
          <div class="btn right" @click="opoutShow = false">再想想</div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import {
  postBuy,
  getCode,
  login,
  outFeed,
  memberList,
  orderList,
  detMainProduct
} from "../../../api";
import addR from "../../../common/addRecord";
import vuePuzzle from "vue-puzzle-vcode";
import { Notify, Dialog, } from "vant";
import { mapState } from 'vuex';
export default {
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: Boolean,
    pageData: Object,
    isBuy: String,
  },
  components: {
    vuePuzzle,
    Notify,
  },
  data () {
    return {
      loginForm: {
        phone: "",
        vcode: "",
      },
      codeState: {
        state: false,
        time: 60,
        task: null,
      },
      showVcode: false,
      showSheet: false,
      totasShow: false,
      radio: "0",
      message: "",
      reason: "",
      resonList: [
        {
          title: "最近不用客户端",
          value: "3",
        },
        {
          title: "流量用不完",
          value: "4",
        },
        {
          title: "价格太贵",
          value: "5",
        },
        {
          title: "误点误操作",
          value: "6",
        },
        {
          title: "流量无法激活",
          value: "1",
        },
        {
          title: "会员无法领取",
          value: "2",
        },
        {
          title: "其他",
          value: "7",
        },
      ],
      saveValue: false,
      opoutShow: false,
      memberInfo: {},
      text: "",
      isTreaty: 0
    };
  },
  computed: {
    user () {
      return this.$store.state.user;
    },
    ...mapState(['product'])
  },
  created () {
    if (this.pageData.remarks.treatyText && this.pageData.remarks.treatyText !== '') {
      this.text = this.pageData.remarks.treatyText
    }
  },
  methods: {
    closeUnbuy () {
      this.reason = "";
      this.message = "";
      this.radio = "0";
      this.$emit("change", false);
    },
    checkVcode () {
      if (this.loginForm.vcode.length > 6) {
        this.loginForm.vcode = this.loginForm.vcode.slice(0, 6);
      }
    },
    getCode () {
      if (this.codeState.state) return;
      let { phone } = this.loginForm;
      if (!/^1[23456789]\d{9}$/.test(phone)) {
        return this.$toast("请输入正确手机号");
      }
      this.showVcode = true;
    },
    onSuccessCode () {
      this.showVcode = false;
      let { phone } = this.loginForm;
      getCode({
        phone,
      }).then(
        (res) => {
          this.$toast("验证码已发送");
          this.codeState.state = true;
          this.codeState.task = setInterval(() => {
            if (this.codeState.time <= 0) {
              clearInterval(this.codeState.task);
              this.codeState.task = null;
              this.codeState.state = false;
              this.codeState.time = 60;
            } else {
              this.codeState.time--;
            }
          }, 1000);
        },
        (res) => {
          this.$toast(res.message);
        }
      );
    },
    async getOrderList (userid) {
      // 查询主产品订购关系
      orderList({
        cpid: this.product.cpid,
        spid: this.product.spid,
        userid: userid,
      }).then(async (res) => {
        // 主产品查询有订购关系
        if (res.data.length > 0) {
          //主产品为订购状态 根据合约期条件显示合约期提示
          if (res.data[0].STATUS === "0") {
            this.getOpout(res)
          } else {
            // 主产品为退订
            //有关联产品 根据合约期条件显示合约期提示
            if (this.product.cacheSeatOne[0].relationIds != '') {
              let ids = this.product.cacheSeatOne[0].relationIds.split(',')
              for (let j = 0; j < ids.length; j++) {
                let info = await detMainProduct({ productId: ids[j] })
                let obj = {
                  userid: userid,
                  spid: info.data.spid,
                  cpid: info.data.cpid
                }
                await orderList(obj).then(res => {
                  if (res.data.length > 0) {
                    if (res.data[0].STATUS === '0') {
                      this.getOpout(res)
                      return false
                    }
                  }
                })
              }
            } else {
              // 无关联产品直接退订
              this.$emit('change', false)
              this.unbuyClick();
            }
          }
        } else {
          // 主产品没有订购关系
          // 有关联产品   根据合约期条件显示合约期提示
          if (this.product.cacheSeatOne[0].relationIds != '') {
            let ids = this.product.cacheSeatOne[0].relationIds.split(',')
            for (let j = 0; j < ids.length; j++) {
              let info = await detMainProduct({ productId: ids[j] })
              let obj = {
                userid: userid,
                spid: info.data.spid,
                cpid: info.data.cpid
              }
              await orderList(obj).then(res => {
                if (res.data.length > 0) {
                  if (res.data[0].STATUS === '0') {
                    this.getOpout(res)
                  }
                  return false
                }
              })
            }
          } else {
            // 无关联产品直接退订
            this.$emit('change', false)
            this.unbuyClick();
          }
        }
      });
    },
    getOpout (res) {
      this.$emit('change', false)
      let orderTime = res.data[0].ORDERTIME.substring(0, 8)
      let date = new Date()
      let year = parseInt(date.getFullYear())
      let month = parseInt(date.getMonth() + 1)
      let day = parseInt(date.getDate())
      let orderYear = parseInt(orderTime.substring(0, 4))
      let orderMonth = parseInt(orderTime.substring(4, 6))
      let orderDay = parseInt(orderTime.substring(6, 8))
      if (orderYear == year) {
        if ((month - orderMonth) < 5) {
          this.opoutShow = true
        } else {
          this.unbuyClick()
        }
      } else if ((year - orderYear) == 1) {
        let number = (12 - orderMonth) + month
        if (number < 5) {
          this.opoutShow = true
        } else {
          this.unbuyClick()
        }
      } else {
        this.unbuyClick()
      }
    },
    unbuy () {
      // this.getOrderList(this.$store.state.user.userid)
      let { phone, vcode } = this.loginForm;
      if (!vcode) {
        return this.$toast("请输入验证码");
      }
      if (!/^1[23456789]\d{9}$/.test(phone)) {
        return this.$toast("请输入正确手机号");
      }
      if (this.radio === "0") {
        return this.$toast("请选择退订原因");
      }
      login({ phone, vcode }).then(
        async (res) => {
          if (res.code === 500 || res.data === "") {
            this.$toast.fail("登录失败");
          } else {
            clearInterval(this.codeState.task);
            this.codeState.task = null;
            this.codeState.state = false;
            this.codeState.time = 60;
            this.$store.commit("setUser", {
              userid: res.data.userid,
              phone: this.loginForm.phone,
            });
            if (this.pageData.remarks.treaty === '1') {
              if (this.$store.state.product.cacheSeatOne[0].isTreaty == "1") {
                this.isTreaty = 1
                this.getOrderList(res.data.userid)
              } else {
                this.isTreaty = 0
                this.unbuyClick()
              }

            } else {
              this.unbuyClick()
            }
            // this.opoutShow = true;
            this.loginForm = {};
          }
        },
        (response) => {
          if (response.code === 500) {
            this.$toast(response.message);
          }
        }
      );
    },
    closeSheet () {
      if (this.radio !== "0" && this.reason !== "") {
        this.showSheet = false;
      } else {
        this.radio = "0";
        this.message = "";
        this.reason = "";
        this.totasShow = false;
      }
    },
    async unbuyClick () {
      this.opoutShow = false
      let updata = {
        cpid: this.product.cpid,
        spid: this.product.spid,
        productId: this.product.id,
        channelKey: this.pageData.channl.channelKey,
        token: "00011223360000011223360012233600",
        type: "1",
        userid: this.$store.state.user.userid,
      };
      await this.postReson(this.$store.state.user.userid, this.$store.state.user.phone);
      this.$toast.loading({
        type: "loading",
        message: "退订中",
        duration: 0
      })
      postBuy(updata).then((res) => {
        if (res.code === 10000) {
          addR.unBuySuccess();
          this.$toast.success("退订成功");
          this.$emit("change", false);
          this.$emit("childData", "已退订");
        }
      }, (res) => {
        addR.unBuyFail(res);
        if (res.message === "退订失败,该用户没有订购该产品或者已失效") {
          Dialog({
            message: "退订失败:经查询没有您订购本产品的记录。",
            theme: "round-button",
          });
        } else {
          Dialog({
            message: res.message,
            theme: "round-button",
          });
        }
        this.$emit("change", false);
        this.$toast.clear()
      }
      );
    },
    sureClick () {
      if (this.radio !== "0") {
        this.reason = this.resonList.find((item) => {
          if (item.value === this.radio) {
            return item;
          }
        }).title;
        this.showSheet = false;
      }
    },
    postReson (userid, phone) {
      // let {userid , phone} = this.$store.state.users
      let feedBack = {
        phone: phone,
        content: "",
        reason: "",
        channelName: this.pageData.channl.channelName,
        productName: this.product.productName,
        spid: this.product.spid,
        userid: userid,
      };
      let msg = "";
      this.resonList.forEach((item) => {
        if (item.value === this.radio) {
          msg = item.title;
        }
      });
      feedBack.reason = msg;
      feedBack.content = this.message;
      outFeed(feedBack).then((res) => {
        if (res.code === 10000) {
          this.radio = "0";
          this.message = "";
          this.reason = "";
        }
      });
    },
    radioClick (value) {
      this.memberInfo = {};
      this.radio = value;
      if (value === "3") {
        addR.unbuyReason();
      } else if (value === "4") {
        addR.unbuyReason1();
      } else if (value === "5") {
        addR.unbuyReason2();
      } else if (value === "6") {
        addR.unbuyReason3();
      } else if (value === "7") {
        addR.unbuyReason4();
      } else if (value === "1") {
        addR.unbuyReason5();
        this.saveValue = true;
        this.sureClick();
      } else if (value === "2") {
        addR.unbuyReason6();
        if (this.product.isCompositeProduct === 0 && this.user.userid) {
          let { cpid, spid, isCompositeProduct, activeType } =
            this.product;
          memberList({
            userid: this.user.userid,
            cpid,
            spid,
            isCompositeProduct,
            activeType,
          }).then((res) => {
            if (res.data.length > 0 && res.data !== null) {
              this.memberInfo = res.data[0];
              this.saveValue = true;
              this.sureClick();
            }
          });
        } else {
          this.saveValue = true;
          this.sureClick();
        }
      }
    },
    saveClick (num) {
      this.saveValue = false;
      this.reason = "";
      this.radio = "0";
      this.$emit("change", false);
      if (num === 1) {
        addR.jihuoSolve();
        this.$emit("jihuo");
      } else {
        addR.memberSolve();
        this.$emit("memberClick", "member");
      }
    },
    savleUnbuy () {
      this.saveValue = false;
      if (this.radio === "1") {
        addR.jihuoUnbuy();
      } else if (this.radio === "2") {
        addR.memberUnbuy();
      }
    },
  },
};
</script>
<style lang="scss">
.fileBox {
  margin: 10px 40px;
  box-sizing: border-box;
  border: 1px solid #c4c4c4;
}
.rowList {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.modal {
  box-sizing: border-box;
  position: absolute;
  left: 50%;
  top: 333px;
  transform: translateX(-50%);
  width: 530px;
  background-color: #fff;
  border-radius: 8px;

  .close {
    width: 80px;
    height: 80px;
    position: absolute;
    bottom: -130px;
    left: 50%;
    transform: translateX(-50%);
  }

  .top {
    width: 100%;
    height: 96px;
  }

  .logo {
    width: 92px;
    height: 50px;
    position: absolute;
    top: 22px;
    left: 37px;
  }
}

.unbuy-modal {
  top: 366px;

  .body-box {
    padding: 40px 50px 70px;

    .input-box {
      display: flex;
      line-height: 75px;
      margin-bottom: 25px;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #d6000f;

      .input {
        font-size: 32px;
        color: #000;
        flex: 1;
        background-color: transparent;

        input {
          margin: 0;
          padding: 0;
          border: none;
          outline: none;
          width: 100%;
        }
      }

      .code {
        font-size: 28px;
        width: 150px;
        margin: 0 10px;
        color: #d6000f;

        &.number {
          color: #a7a7a7;
        }
      }
    }

    .btn-box {
      display: flex;
      justify-content: space-between;

      .btn {
        width: 190px;
        margin-top: 20px;
        height: 80px;
        line-height: 80px;
        border-radius: 40px;
        font-size: 34px;
        font-weight: bold;
        text-align: center;
      }

      .left {
        background: #ffffff;
        border: 2px solid #bfbfbf;
        border-radius: 8px;
      }

      .right {
        color: #d6000f;
        background: #ffffff;
        border: 2px solid #d6000f;
        border-radius: 8px;
      }
    }

    .unBuyText {
      margin-top: 40px;
      text-align: left;
      font-size: 26px;
      line-height: 40px;
    }
  }

  .btn {
    margin-top: 40px;
    height: 80px;
    line-height: 80px;
    background: #fdc51b;
    border-radius: 40px;
    font-size: 34px;
    font-weight: bold;
    color: #0d0d0d;
    text-align: center;
  }
}
.repeat-modal {
  top: 412px;
  padding: 60px 51px;
  font-size: 30px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #222222;

  .text-box {
    line-height: 48px;
    text-align: center;
  }

  .btn-box {
    display: flex;
    justify-content: space-between;

    .btn {
      width: 190px;
      margin-top: 60px;
      height: 80px;
      line-height: 80px;
      border-radius: 40px;
      font-size: 34px;
      font-weight: bold;
      text-align: center;
    }

    .left {
      border: 2px #fdc51b solid;
      color: #fdc51b;
      background-color: #ffffff;
    }

    .right {
      color: #0d0d0d;
      background: #fdc51b;
    }
  }
}
.opout-modal {
  top: 412px;
  padding: 60px 51px;
  font-size: 30px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #222222;

  .text-box {
    line-height: 48px;
    text-align: center;
  }

  .btn-box {
    display: flex;
    justify-content: space-between;

    .btn {
      width: 190px;
      margin-top: 60px;
      height: 80px;
      line-height: 80px;
      border-radius: 40px;
      font-size: 34px;
      font-weight: bold;
      text-align: center;
    }

    .left {
      border: 2px #fdc51b solid;
      color: #fdc51b;
      background-color: #ffffff;
    }

    .right {
      color: #0d0d0d;
      background: #fdc51b;
    }
  }

  // .btn {
  //     margin-top: 40px;
  //     height: 80px;
  //     line-height: 80px;
  //     background: #fdc51b;
  //     border-radius: 40px;
  //     font-size: 34px;
  //     font-weight: bold;
  //     color: #0d0d0d;
  //     text-align: center;
  // }
}

.sureStyle {
  width: 90%;
  margin: 50px auto;
  border-radius: 40px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  background-color: #dc2633;
  color: #fff;
}
</style>
