<template>
  <zj-page-layout :hasFooter="true">
    <view class="all-container">
      <view class="address-container card" @tap="chooseAddress">
        <view class="common-title"><text>*</text>客户信息</view>
        <view class="main">
          <view class="left">
            <view class="icon"><text class="iconfont icon-dingwei1"></text></view>
            <view class="nodata" v-if="!addressInfo">选择联系人地址</view>
            <view class="hasdata" v-else>
              <view class="name">{{ addressInfo.name }}<text>{{ addressInfo.phone }}</text></view>
              <view class="address ellipsis-2">
                {{ addressInfo.province }}{{ addressInfo.city }}{{ addressInfo.area }}{{ addressInfo.street }}{{ addressInfo.address }}{{ addressInfo.houseNo }}
              </view>
            </view>
          </view>
          <text class="right iconfont icon-jinru"></text>
        </view>
      </view>

      <view class="service-container card">
        <view class="common-title">服务信息</view>
        <view class="item">
          <view class="label"><text>*</text>服务类型</view>
          <view class="picker">
            <text class="value">延保</text>
            <!--            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text> -->
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>使用类型</view>
          <view class="value">按使用年限</view>
        </view>
        <view class="item" @tap="isShowBrandDialog = true">
          <view class="label"><text>*</text>产品品牌</view>
          <view class="picker">
            <text class="value" v-if="brand">{{ brand.brandName }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item" @tap="changeCategory">
          <view class="label"><text>*</text>产品大类</view>
          <view class="picker">
            <text class="value" v-if="category">{{ category.name }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item" @tap="changeService">
          <view class="label"><text>*</text>服务内容</view>
          <view class="picker">
            <text class="value" v-if="service">{{ service.content }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>使用限值</view>
          <view class="picker">
            <view class="value" v-if="service && service.limitNum">{{ service.limitNum }}</view>
            <text class="placeholder" v-else>选择服务内容自动带入</text>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>服务金额</view>
          <view class="picker">
            <view class="value" v-if="service && service.amount">¥{{ service.amount }}</view>
            <text class="placeholder" v-else>选择服务内容自动带入</text>
          </view>
        </view>
        <view class="item" @tap="changeWebsit()">
          <view class="label"><text>*</text>销售网点</view>
          <view class="picker">
            <text class="value" v-if="websit">{{ websit.name }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <view class="service-container card">
        <view class="common-title">产品信息</view>
        <view class="item">
          <view class="label"><text>*</text>内机条码</view>
          <view class="input">
            <u-input placeholder="请输入" border="none" inputAlign="right" v-model="insideCode">
              <template slot="suffix">
                <u-icon @click="scanInsideCode" name="scan" size="24"></u-icon>
              </template>
            </u-input>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>发票价格</view>
          <view class="input">
            <u-input placeholder="请输入" border="none" inputAlign="right" v-model="invoiceAmount"></u-input>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>原保到期</view>
          <view class="picker" @tap="isShowDatePicker = true">
            <text class="value" v-if="insureTime">{{ insureTime }}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>服务期限</view>
          <view class="value">{{ date }}</view>
        </view>
        <view class="imgs">
          <!-- 内机条码 -->
          <view class="it">
            <block v-if="insideCodeImg">
              <text class="iconfont icon-guanbi1 close" @tap="delImg('insideCodeImg')"></text>
              <image mode="aspectFill" :src="insideCodeImg" @tap="prevImg(insideCodeImg)">
              </image>
            </block>
            <view class="empty" v-else @tap="chooseImg('insideCodeImg')">
              <text class="iconfont icon-xiangji"></text>
              <text class="text">添加图片</text>
            </view>
            <view class="name"><text>*</text>内机条码</view>
          </view>
          <!-- 机器铭牌 -->
          <view class="it">
            <block v-if="machineImg">
              <text class="iconfont icon-guanbi1 close" @tap="delImg('machineImg')"></text>
              <image mode="aspectFill" :src="machineImg" @tap="prevImg(machineImg)">
              </image>
            </block>
            <view class="empty" v-else @tap="chooseImg('machineImg')">
              <text class="iconfont icon-xiangji"></text>
              <text class="text">添加图片</text>
            </view>
            <view class="name"><text>*</text>机器铭牌<br />(含出厂日期)</view>
          </view>
          <!-- 购机凭证 -->
          <view class="it">
            <block v-if="buyCertImg">
              <text class="iconfont icon-guanbi1 close" @tap="delImg('buyCertImg')"></text>
              <image mode="aspectFill" :src="buyCertImg" @tap="prevImg(buyCertImg)">
              </image>
            </block>
            <view class="empty" v-else @tap="chooseImg('buyCertImg')">
              <text class="iconfont icon-xiangji"></text>
              <text class="text">添加图片</text>
            </view>
            <view class="name"><text>*</text>购机凭证</view>
          </view>
        </view>
      </view>
    </view>

    <template slot="footer">
      <view class="footer-btn-group">
        <u-button type="primary" plain text="查看延保服务" @click="toOrderList"></u-button>
        <u-button @click="confirm" type="primary" text="立即下单"></u-button>
      </view>
    </template>

    <zjDialogPicker ref="brandDialog" :isShow="isShowBrandDialog" :multiple="false" :styleType="2" :title="'品牌'"
      :list="brandList" :keyName="'brandName'" @cancel="isShowBrandDialog = false" @confirm="confirmBrandDialog">
    </zjDialogPicker>
    <zjDialogPicker ref="categoryDialog" :isShow="isShowCategoryDialog" :multiple="false" :styleType="2" :title="'产品大类'"
      :list="categoryList" :keyName="'name'" @cancel="isShowCategoryDialog = false" @confirm="confirmCategoryDialog">
    </zjDialogPicker>
    <zjDialogPicker ref="serviceDialog" :isShow="isShowServiceDialog" :multiple="false" :styleType="2" :title="'服务内容'"
      :list="serviceList" :keyName="'content'" @cancel="isShowServiceDialog = false" @confirm="confirmServiceDialog">
    </zjDialogPicker>
    <zjDialogPicker ref="websitDialog" :isShow="isShowWebsitDialog" :multiple="false" :styleType="2" :title="'所属网点'"
      :list="websitList" :keyName="'name'" @cancel="isShowWebsitDialog = false" @confirm="confirmWebsitDialog">
    </zjDialogPicker>
    <u-datetime-picker :show="isShowDatePicker" v-model="datePickerValue" mode="date" :formatter="formatter"
      @cancel="isShowDatePicker = false" @close="isShowDatePicker = false" @confirm="confirmDate"
      :minDate="minDate"></u-datetime-picker>
    <u-popup :show="isShowPay" mode="bottom">
      <view class="pay">
        <image class="close" @click="closePay()" src="/static/icon/close.png" mode="aspectFill"></image>
        <view class="title">请支付</view>
        <view class="item">
          服务类型: <text class="text">延保</text>
        </view>
        <view class="item">
          使用类型: <text class="text">按使用年限</text>
        </view>
        <view class="item">
          产品品牌: <text class="text">{{ brand ? brand.brandName : '' }}</text>
        </view>
        <view class="item">
          产品大类: <text class="text">{{ category ? category.name : '' }}</text>
        </view>
        <view class="item">
          服务内容: <text class="text">{{ service ? service.content : '' }}</text>
        </view>
        <view class="item">
          使用限制: <text class="text">{{ service ? service.limitNum : '' }}</text>
        </view>
        <view class="item">
          服务金额: <text class="text">{{ service ? service.amount : '' }}</text>
        </view>
        <view class="title" style="text-align: left;">选择支付方式</view>
        <view class="payType">
          <view style="margin-bottom: 20rpx;">
            <u-button type="primary" @click="scanCode" text="扫码支付 (推荐)"></u-button>
          </view>
          <u-button type="primary" @click="workerPay" :plain="true" text="代客支付"></u-button>
        </view>
      </view>
    </u-popup>
  </zj-page-layout>
</template>

<script>
import zjDialogPicker from "@/components/zj-dialog/zj-dialog-picker.vue";
import { uploadImgFull, weixinPay, mini_env, wxScanCode } from '@/common/utils/util.js';

export default {
  components: {
    zjDialogPicker
  },
  data() {
    return {
      addressInfo: null,
      insideCode: '',
      insideCodeImg: '',
      buyCertImg: '',
      machineImg: '',
      invoiceAmount: '',
      isShowBrandDialog: false,
      brand: null,
      brandList: [],
      categoryList: [],
      category: null,
      isShowCategoryDialog: false,
      serviceList: [],
      service: null,
      isShowServiceDialog: false,
      websit: null,
      websitList: [],
      isShowWebsitDialog: false,
      date: '',
      insureTime: '',
      datePickerValue: Number(new Date()),
      minDate: Number(new Date()),
      isShowDatePicker: false,
      isShowPay: false,
      is_confirm: true,
      canScanCode: 0,
      timeout: null,
      timeoutNum: 0,
      orderId: ''
    }
  },

  onLoad() {
    // 接收地址信息
    this.crossPage.$on('chooseAddress', result => {
      this.addressInfo = result;
    })
    this.getBrandList();
  },

  onUnload() {
    this.crossPage.$off('chooseAddress');
    clearTimeout(this.timeout);
  },

  computed: {
    formatter() {
      return function (type, value) {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        return value
      }
    },
    deadline() {
      return function (time, num) {
        let date = new Date(time)
        date.setFullYear(date.getFullYear() + num);
        let y = date.getFullYear(),
          m = date.getMonth() + 1,
          d = date.getDate()
        return `${y}-${m > 9 ? m : '0' + m}-${d > 9 ? d : '0' + d}`
      }
    }
  },

  methods: {
    // 去选择地址
    chooseAddress() {
      this.$navToPage({
        url: '/packageMine/pages/address/list?isChoose=' + true
      })
    },
    getBrandList() {
      this.$api.post('/increConfig/getBrand').then(res => {
        this.brandList = res.data;
      })
    },

    getCategoryList() {
      this.$api.post('/increConfig/getCategoryList', {
        brand: this.brand.brandName
      }).then(res => {
        this.categoryList = res.data;
      })
    },

    getServiceList() {
      if (!this.brand || !this.category) { return false }
      this.$api.post('/increConfig/getIncreItem', {
        brand: this.brand.brandName,
        mainName: this.category.name
      }).then(res => {
        this.serviceList = res.data;
      })
    },
    getWebsitList() {
      this.$api.get('/user/apply/websit', {
        isIncre: true,
        increId: this.service.increId
      }).then(res => {
        this.websitList = res.data;
      })
    },

    changeCategory() {
      if (this.brand) {
        this.isShowCategoryDialog = true
      } else {
        return this.$toast('请先选择产品品牌！')
      }
    },

    changeService() {
      if (this.brand || this.category) {
        this.isShowServiceDialog = true
      } else {
        return this.$toast('请先选择产品品牌或产品大类！')
      }
    },

    changeWebsit() {
      if (!this.service) {
        return this.$toast('请先选择服务内容！')
      } else {
        this.isShowWebsitDialog = true
      }
    },

    confirmBrandDialog(e) {
      this.service = null
      this.category = null
      this.brand = this.brandList[e[0]];
      this.isShowBrandDialog = false;
      this.getServiceList()
      this.getCategoryList();
    },

    confirmCategoryDialog(e) {
      this.service = null
      this.category = this.categoryList[e[0]];
      this.isShowCategoryDialog = false;
      this.getServiceList()
    },

    confirmServiceDialog(e) {
      this.service = this.serviceList[e[0]];
      this.increContent = this.serviceList[e[0]].content
      this.isShowServiceDialog = false;
      this.date = this.insureTime ? this.deadline(`${y}-${m}-${d}`, this.service.limitNum) : ''
      this.getWebsitList();
    },

    confirmWebsitDialog(e) {
      this.websit = this.websitList[e[0]];
      this.isShowWebsitDialog = false;
    },

    confirmDate(e) {
      this.isShowDatePicker = false;
      let time = new Date(e.value);
      let y = time.getFullYear();
      let m = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
      let d = (time.getDate()) < 10 ? '0' + (time.getDate()) : time.getDate();
      let hh = (time.getHours()) < 10 ? '0' + (time.getHours()) : time.getHours();
      let mm = (time.getMinutes()) < 10 ? '0' + (time.getMinutes()) : time.getMinutes();
      let ss = (time.getSeconds()) < 10 ? '0' + (time.getSeconds()) : time.getSeconds();
      this.insureTime = `${y}-${m}-${d}`;
      this.date = this.deadline(`${y}-${m}-${d}`, this.service.limitNum)
    },

    // 上传图片
    chooseImg(name) {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          let data = await uploadImgFull(res.tempFilePaths[0]);
          this[name] = data.url
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },

    // 预览图片
    prevImg(url) {
      uni.previewImage({
        current: url,
        urls: [url],
      });
    },

    delImg(name) {
      this[name] = ''
    },

    confirm() {
      if (!this.addressInfo) {
        return this.$toast('请选择客户信息！')
      } else if (!this.brand) {
        return this.$toast('请选择产品品牌！')
      } else if (!this.category) {
        return this.$toast('请选择产品大类！')
      } else if (!this.service) {
        return this.$toast('请选择服务内容！')
      } else if (!this.websit) {
        return this.$toast('请选择销售网点！')
      } else if (!this.insideCode) {
        return this.$toast('请输入内机条码！')
      } else if (!this.invoiceAmount) {
        return this.$toast('请输入发票价格！')
      } else if (!/^\d+(\.\d+)?$/.test(this.invoiceAmount)) {
        return this.$toast('发票价格只能输入数字！')
      } else if (!this.insureTime) {
        return this.$toast('请选择原保到期时间！')
      } else if (!this.insideCodeImg) {
        return this.$toast('请上传内机条码图！')
      } else if (!this.machineImg) {
        return this.$toast('请上传机器铭牌图！')
      } else if (!this.buyCertImg) {
        return this.$toast('请上传购机凭证图片！')
      } else {
        if (!this.is_confirm) { return this.$toast('请勿频繁点击！') }
        this.is_confirm = false
        setTimeout(() => {
          this.is_confirm = true
        }, 3000)
        this.$api.postJson('/increConfig/buy', {
          increType: 1,
          pgIncreId: this.service.increId,
          pgIncreItemId: this.service.id,
          brandId: this.brand.id,
          brandName: this.brand.brandName,
          mainId: this.category.categoryId,
          mainName: this.category.name,
          increContent: this.service.content,
          limitNum: this.service.limitNum,
          amount: this.service.amount,
          websitId: this.websit.websitId,
          websitName: this.websit.name,
          insideCode: this.insideCode,
          invoiceAmount: this.invoiceAmount,
          insureTime: this.insureTime + ' 00:00:00',
          insideCodeImg: this.insideCodeImg,
          machineImg: this.machineImg,
          buyCertImg: this.buyCertImg,
          userName: this.addressInfo.name,
          userMobile: this.addressInfo.phone,
          userAddress: this.addressInfo.province + this.addressInfo.city + this.addressInfo.area + this.addressInfo.street + this.addressInfo.address + this.addressInfo.houseNo,
          userAddressId: this.addressInfo.userAddressId
        }).then(res => {
          if (res.code == 200) {
            this.orderId = res.data
            this.isShowPay = true
          }
        })
      }
    },

    // 扫码
    async scanCode() {
      if (this.canScanCode > 0) return this.$toast(`请等待${this.canScanCode}秒后重试`);
      var codeVal = await wxScanCode();
      this.userPay(codeVal);
    },

    async scanInsideCode() {
      var codeVal = await wxScanCode();
      this.insideCode = codeVal;
    },

    // 用户支付
    userPay(code) {
      this.$api.post('/increConfig/paid', {
        authCode: code,
        id: this.orderId,
      }).then((res) => {
        // 返回true，则支付成功
        if (res.data) {
          this.timeoutNum = 0;
          clearTimeout(this.timeout);
          this.$navToPage({
            url: `/packageHome/pages/addvalue/orderList`
          }, "reLaunch")
        }
        // 返回false，轮询3次
        else {
          if (this.timeoutNum < 4) {
            this.timeoutNum = this.timeoutNum + 1;
            this.timeout = setTimeout(() => {
              this.userPay(code);
            }, 1000);
          } else {
            this.timeoutNum = 0;
            clearTimeout(this.timeout);
            this.$navToPage({
              url: `/packageHome/pages/addvalue/orderList`
            }, "reLaunch")
          }
        }
      }).catch((res) => {
        this.timeoutNum = 0;
        clearTimeout(this.timeout);
        this.$tips(res.message);
      }).finally(() => {
        this.canScanCode = 15;
        let time = setInterval(() => {
          if (this.canScanCode > 0) {
            this.canScanCode = this.canScanCode - 1;
          } else {
            clearInterval(time);
          }
        }, 1000);
      });
    },

    //代客支付
    workerPay() {
      mini_env((bool) => {
        const that = this
        this.$api.post('/increConfig/pay', {
          id: this.orderId,
          ...(() => {
            if (bool) {
              return {
                miniPay: true,
                openId: this.$store.state.user.miniOpenId
              }
            }
            return {}
          })()
        }).then((res) => {
          if (!res.data) return false;
          if (bool) {
            uniWebview.navigateTo({
              url: `/pages/pay/pay?${Object.entries({
                ...res.data,
                payPackage: res.data.payPackage.split("=")[0] || "",
                payPackageVal: res.data.payPackage.split("=")[1] || ""
              }).map(item => item.join("=")).join("&")}`
            })
          } else {
            weixinPay(res.data, function (res) {
              that.$successToast('支付成功');
              setTimeout(() => {
                that.$navToPage({
                  url: `/packageHome/pages/addvalue/orderList`
                }, "reLaunch")
              }, 1000)
            })
          }
        })
      })
    },

    closePay() {
      this.isShowPay = false
    },
    toOrderList() {
      this.$navToPage({
        url: `/packageHome/pages/addvalue/explainList`
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.card {
  @include zj-card;
  margin-top: 20rpx;
  padding: 30rpx;
}

.common-title {
  font-size: 32rpx;
  font-weight: 500;

  text {
    color: $error-color;
    font-weight: normal;
  }
}

.all-container {
  padding: 0 20rpx;
}

.address-container {
  .main {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
  }

  .right {
    font-size: 32rpx;
    color: $sec-font;
    flex-shrink: 0;
  }

  .left {
    display: flex;
    align-items: center;
    margin-right: 20rpx;

    .icon {
      width: 52rpx;
      height: 52rpx;
      border-radius: 50%;
      background: $theme-color;
      display: flex;
      flex-shrink: 0;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;

      .iconfont {
        font-size: 36rpx;
        color: #ffffff;
      }
    }

    .nodata {
      font-size: 28rpx;
      color: #999999;
    }

    .hasdata {
      .name {
        font-size: 32rpx;
        color: #333333;

        text {
          color: #999999;
          font-size: 28rpx;
          margin-left: 16rpx;
        }
      }

      .address {
        font-size: 28rpx;
        color: #666666;
        line-height: 34rpx;
        margin-top: 10rpx;
      }
    }
  }
}

.service-container {
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50rpx;
    margin-top: 30rpx;

    .label {
      margin-right: 30rpx;

      text {
        color: $error-color;
      }
    }

    .picker {
      .placeholder {
        color: $sec-font;
      }

      .iconfont {
        margin-left: 12rpx;
        color: $sec-font;
      }
    }
  }

  .imgs {
    display: flex;
    flex-wrap: wrap;

    .it {
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      margin-top: 30rpx;
      margin-right: 30rpx;

      &:nth-child(3n) {
        margin-right: 0;
      }

      .close {
        position: absolute;
        right: -20rpx;
        top: -20rpx;
        z-index: 99;
        width: 42rpx;
        height: 42rpx;
        background: $minor-color;
        color: #ffffff;
        text-align: center;
        line-height: 42rpx;
        border-radius: 50%;
        font-size: 28rpx;
      }

      image {
        width: 190rpx;
        height: 190rpx;
        background: #f4f4f7;
        border-radius: 20rpx;
        overflow: hidden;
      }

      .empty {
        width: 190rpx;
        height: 190rpx;
        border: 1px dashed #e5e5e5;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        position: relative;
        border-radius: 20rpx;
        overflow: hidden;

        .iconfont {
          font-size: 52rpx;
          color: $sec-font;
        }

        .text {
          margin-top: 12rpx;
          font-size: 28rpx;
          color: $sec-font;
        }
      }

      .name {
        margin-top: 24rpx;
        color: $sec-font;

        text {
          color: $minor-color;
        }
      }
    }
  }
}

.pay {
  padding: 30rpx;
  padding-bottom: 0;
  box-sizing: border-box;
  position: relative;

  .title {
    font-size: 34rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 50rpx;
  }

  .item {
    color: #666666;
    margin-bottom: 20rpx;

    .text {
      margin-left: 30rpx;
      color: #000000;
    }
  }

  .payType {
    margin: 40rpx 0;
  }

  .close {
    width: 30rpx;
    height: 30rpx;
    position: absolute;
    top: 30rpx;
    right: 30rpx;
  }
}
</style>
