<template>
  <div class="handleContainer">
    <navBar />
    <div class="title">当前帐号信息</div>
    <div class="formContent">
      <div class="item">
        <div class="desc">业务员</div>
        <div class="content">{{ name }}</div>
      </div>
      <div class="item">
        <div class="desc">办理帐号</div>
        <div class="content">{{ phoneNo }}</div>
      </div>
    </div>
    <div class="title">推广员信息</div>
    <div class="formContent">
      <div class="item">
        <div class="desc">推广员手机号</div>
        <div class="content">
          <input
            v-model="promoterMobile"
            placeholder="请填写推广员手机号"
            type="text"
            class="normal"
          />
        </div>
      </div>
    </div>
    <div class="title">用户充值信息</div>
    <div class="formContent">
      <div class="item">
        <div class="desc">办单手机号</div>
        <div class="content">
          <input v-model="mobile" placeholder="请填写办单手机号" type="text" class="normal" />
        </div>
      </div>
      <div class="item select">
        <div class="desc">办理套餐</div>
        <div class="content" @click="showPackagePopup">
          <input
            v-model="packageText"
            type="text"
            placeholder="请选择套餐"
            class="normal"
            readonly
          />
          <i class="arrow iconfont icon-arrow" />
        </div>
      </div>
      <div class="item">
        <div class="desc">赠送礼品卡</div>
        <div class="content">
          <input v-model="giftCardText" type="text" class="normal" readonly />
        </div>
      </div>
    </div>

    <div class="uploadPic">
      <div class="uploadPicTitle">
        <span>上传凭证</span>
        <span>（最多6张, 仅支持jpg、png格式）</span>
      </div>
      <cr-uploader
        v-model="picList"
        accept="image/jpeg,image/jpg,image/png"
        :before-read="
          file => {
            asyncRead(file);
          }
        "
        max-number="6"
      />
    </div>
    <div class="submit">
      <cr-button shape="circle" type="primary" :disabled="disableOperation" @click="submit">
        提交
      </cr-button>
    </div>
    <cr-popup v-model="showPopup" position="bottom" round :style="{ height: '40%' }" closeable>
      <div class="popupTitle">选择已办理的套餐</div>
      <div class="listContainer">
        <cr-radio-group v-model="phoneBillPackage" direction="vertical" @change="selectValChanged">
          <cr-cell-group>
            <cr-cell
              v-for="(item, index) in list"
              :key="index"
              clickable
              :class="{ selected: phoneBillPackage == item.phoneBillPackage }"
              :title="`${item.phoneBillPackage}元套餐`"
              @click="changeSelect(item)"
            >
              <template #right-icon>
                <cr-radio ref="checkboxes" :name="item.phoneBillPackage" />
              </template>
            </cr-cell>
          </cr-cell-group>
        </cr-radio-group>
      </div>
    </cr-popup>
  </div>
</template>
<script>
import { upload } from 'qiniu-js';
import orderApi from '@/api/order.api';
import { getJSuPackageDenominations, getGroupPushUserInfo, submit } from '@/api/promotion';
import navBar from './components/navBar.vue';
import config from '../../config/index';
import compress from '@/service/compressImg.service';
export default {
  components: {
    navBar
  },
  data() {
    return {
      showPopup: false,
      picList: [],
      maxLimit: 6,
      token: '',
      name: '', // 用于展示用，业务员名称
      phoneNo: '', // 用于展示用，业务员手机号码
      promoterMobile: '', // 推广员手机号
      mobile: '', // 客户手机号
      phoneBillPackage: '', // 套餐资费
      denomination: '', // 赠送礼品卡
      certification: '', // 图片证明
      packageText: '', // 套餐文字
      giftCardText: '', // 礼品卡文字
      list: [],
      disableOperation: false
    };
  },
  created() {
    this.getDenominations();
    this.getSalesManInfo();
    this.getToken();
  },
  methods: {
    validate() {
      const phoneReg = /(^1[3|4|5|6|7|8][0-9]{9}$)/;
      // 校验手机号
      if (!this.promoterMobile) {
        this.$toast('请填写推广员手机号');
        return false;
      }
      if (!phoneReg.test(this.promoterMobile)) {
        this.$toast('推广员手机号格式错误');
        return false;
      }
      if (!this.mobile) {
        this.$toast('请填写办单手机号');
        return false;
      }
      if (!phoneReg.test(this.mobile)) {
        this.$toast('办单手机号格式错误');
        return false;
      }
      // 校验套餐、礼品卡
      if (!this.phoneBillPackage || !this.denomination) {
        this.$toast('请选择套餐');
        return false;
      }
      // 校验凭证
      if (this.picList.length == 0) {
        this.$toast('请上传凭证');
        return false;
      }
      return true;
    },
    async submit() {
      this.disableOperation = true;
      // 提交审核单
      const validate = this.validate();
      if (validate) {
        const certification = this.picList.map(v => v.url).join(',');
        const [, error] = await submit({
          promoterMobile: this.promoterMobile,
          mobile: this.mobile,
          phoneBillPackage: this.phoneBillPackage,
          denomination: this.denomination,
          certification
        });
        if (!error) {
          this.$router.replace({ name: 'PromotionResult' });
        } else {
          this.disableOperation = false;
        }
      } else {
        this.disableOperation = false;
      }
    },
    selectValChanged(val) {
      this.phoneBillPackage = val;
      this.packageText = `${val}元套餐`;
      for (let i = 0; i < this.list.length; i++) {
        if (+this.list[i].phoneBillPackage === +val) {
          this.denomination = this.list[i].denomination;
          this.giftCardText = `${this.list[i].denomination}元礼品卡`;
          break;
        }
      }
      this.showPopup = false;
    },
    changeSelect(item) {
      this.phoneBillPackage = item.phoneBillPackage;
      this.packageText = `${item.phoneBillPackage}元套餐`;
      for (let i = 0; i < this.list.length; i++) {
        if (+this.list[i].phoneBillPackage === +item.phoneBillPackage) {
          this.denomination = this.list[i].denomination;
          this.giftCardText = `${this.list[i].denomination}元礼品卡`;
          break;
        }
      }
    },
    showPackagePopup() {
      this.showPopup = true;
    },
    async getSalesManInfo() {
      // 获取业务员信息
      const [info] = await getGroupPushUserInfo();
      if (info) {
        this.name = info.salesmanName;
        this.phoneNo = info.mobile;
      }
    },
    async getDenominations() {
      // 获取套餐级联关系
      const [list] = await getJSuPackageDenominations();
      if (list) this.list = list;
    },
    getToken() {
      orderApi.getQiniuToken().then(res => {
        this.token = res[0].token;
      });
    },
    async asyncRead(file) {
      const compressImg = await compress.compressImg(file[0]);
      const that = this;
      let idx = that.picList.length;
      if (file.length + idx >= +this.maxLimit) {
        file = file.splice(0, this.maxLimit - idx);
      }
      const observable = upload(compressImg, null, that.token);
      const observer = {
        next() {
          that.picList[idx] = {
            status: 'uploading'
          };
          that.picList = [...that.picList];
        },
        error(err) {
          console.log(err);
        },
        complete({ hash }) {
          const fileLink = config.qiniuHost + '/' + hash;
          that.picList[idx] = {
            url: fileLink,
            isImage: true,
            status: 'done'
          };
          that.picList = JSON.parse(JSON.stringify([...that.picList]));
          idx = idx + 1;
        }
      };
      observable.subscribe(observer); // 上传开始
      return;
    }
  }
};
</script>
<style scoped lang="less">
.handleContainer {
  width: 100%;
  height: 100%;
  padding: 45px 0 60px;
  box-sizing: border-box;
  overflow-y: auto;
  .title {
    display: flex;
    align-items: center;
    height: 32px;
    padding-left: 20px;
    .text-size(12);
    color: #faab0c;
  }
  .formContent {
    width: 100%;
    background: @white;
    padding-left: @padding-lg;
    box-sizing: border-box;
    .item {
      display: flex;
      align-items: center;
      width: 100%;
      height: 48px;
      // padding-left: @padding-xs;
      padding-right: @padding-lg;
      box-sizing: border-box;
      border-bottom: 1px solid @grey-border;
      &.select {
        padding-right: @padding-xl;
      }
      &:last-child {
        border-bottom: 0;
      }
      .desc {
        flex-shrink: 0;
        width: 94px;
        height: 100%;
        display: flex;
        align-items: center;
        color: @black;
        .text-size(14);
      }
      .content {
        flex: 1;
        display: flex;
        align-items: center;
        height: 100%;
        color: @black;
        position: relative;
        .text-size(14);
        input.normal {
          width: 100%;
          border: 0;
          background: transparent;
        }
        i {
          position: absolute;
          right: -16px;
          top: 50%;
          transform: translateY(-50%);
          color: @gray-3;
        }
      }
    }
  }
  .uploadPic {
    background: @white;
    margin-top: @padding-xs+1;
    padding: @padding-md+1 @padding-lg;
    /deep/ .cr-uploader--preview,
    /deep/ .cr-uploader--upload {
      width: 74px;
      height: 74px;
      margin: 0 6px 6px 0;
    }
    .uploadPicTitle {
      .text-size(14);
      padding-bottom: @padding-sm+1;
      span:last-child {
        color: @gray-4;
      }
    }
  }
  .submit {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 60px;
    padding: 0 10px;
    box-sizing: border-box;
    background: @white;
    button {
      width: 100%;
      height: 40px;
    }
  }
  .popupTitle {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    .text-size(16);
    border-bottom: 1px solid @grey-border;
  }
  .listContainer {
    height: calc(100% - 50px);
    overflow-y: auto;
    /deep/ .cr-radio-group .cr-radio {
      margin-right: 0;
    }
    /deep/ .cr-cell::after {
      border: 0;
    }
    .selected {
      /deep/ .cr-cell__title {
        color: @red;
      }
    }
    .listItem {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 @padding-md;
      box-sizing: border-box;
      .desc {
        .text-size(14);
        color: @black;
      }
    }
  }
}
</style>
