<template>
  <div>
    <scroll-view scroll-y="true" class="scroll-Y">
      <!-- 登录校验 -->
      <!-- <authorize ref="authorize"></authorize> -->
      <!-- <LoginDom></LoginDom> -->
      <div class="wrap">
        <div v-if="custTypeId === 0" class="wrap_plate">我的车牌</div>
        <div v-else class="wrap_plate">车牌号绑定</div>
        <div
          class="plate_plate"
          :style="{ position: custTypeId === 0 ? '' : 'relative' }"
          :class="
            custTypeId === 0
              ? 'linear-gradient-' + item.licensePlateType
              : 'border-change'
          "
          v-for="item in licensePlateList"
          :key="item.id"
        >
          <div class="plate_border">
            <div
              class="plate_tag"
              :class="'bgc-' + item.licensePlateType"
            ></div>
            <div
              class="plate_plate_index plate_plate_index1"
              :style="{
                padding: custTypeId === 0 ? '0 0 0 14px' : '14px 0 0 14px',
              }"
            >
              我的车牌
            </div>
            <div class="plate_plate_index plate_plate_index2">
              {{ item.vehicleNo | formatCarno }}
            </div>
            <div class="plate_plate_index plate_plate_index3 bb">
              <img
                class="car-icon"
                :src="require(`./static/images/icon-carType.png`)"
              />
              <div>车牌类型</div>
              <div class="licensePlateTypeDesc">
                {{ item.licensePlateTypeDesc }}
              </div>
            </div>
            <!-- <div class="plate_tag-icon" :class="
            item.licensePlateType === 'NEW_ENERGY_CAR_NO'
              ? 'plate_tag_icon_green'
              : item.licensePlateType === 'ORDINARY_CAR_NO'
              ? 'plate_tag_icon_blue'
              : ''
          " v-if="custTypeId > 0"></div> -->
            <div class="plate_plate_index plate_plate_index4">
              <div class="item" @click.stop="toPay(item.vehicleNo)">
                <img src="./static/images/icon-edit.png" alt="" /><span
                  >查询</span
                >
              </div>
              <div class="item" @click="toEdit(item)">
                <img src="./static/images/icon-find.png" alt="" /><span
                  >编辑</span
                >
              </div>
              <div class="item" @click="toDelete(item)">
                <img src="./static/images/icon-del-white.png" alt="" /><span
                  >删除</span
                >
              </div>
              <!-- <div class="plate_plate_index4_index2">
              <img src="static/images/money.png" @click="toPay(item.vehicleNo)" />
              <img src="static/images/update.png" class="mrg-left-20" @click="toEdit(item)" />
              <img src="static/images/delete.png" class="mrg-left-20" @click="toDelete(item)" />
            </div> -->
            </div>
          </div>
        </div>
        <div
          class="add_plate_no_data"
          v-if="!licensePlateList.length"
          @click="toAdd"
        >
          添加车牌+
        </div>
        <div class="wrap_plate mt36">
          <div class="title">温馨提示:</div>
          <div class="desc">·用户可以添加多个"燃油车牌号"或"新能源车牌号"</div>
          <div class="desc">·用户可以更改或删除已经绑定车牌</div>
        </div>
      </div>
    </scroll-view>
    <van-popup v-model="deleteDialogSwitch" position="center">
      <div class="popup-dialog">
        <div class="dialog-title">
          <span class="dialog-title-text">删除已绑定车牌</span>
        </div>
        <div class="dialog-content border-top">
          <span class="dialog-content-text">是否确认删除已经绑定车牌</span>
          <span class="dialog-content-carno">{{ activeCarno }}</span>
        </div>
        <div class="dialog-button-group">
          <div class="dialog-button" @click="cancelDelete">
            <span class="dialog-button-text">取消</span>
          </div>
          <div class="dialog-button border-left" @click="doDelete">
            <span class="dialog-button-text">确定</span>
          </div>
        </div>
      </div>
    </van-popup>
    <van-popup v-model="deleteSuccessDialogSwitch" position="center">
      <div class="popup-dialog">
        <div class="dialog-content">
          <uni-icons
            type="checkbox-filled"
            size="60"
            color="#7DB124"
          ></uni-icons>
          <span class="dialog-content-text">删除成功</span>
        </div>
        <div class="dialog-button-group">
          <div class="dialog-button" @click="confirmDialog">
            <span class="dialog-button-text">确定</span>
          </div>
        </div>
      </div>
    </van-popup>
    <div
      class="add_plate_box"
      v-if="licensePlateList.length && licensePlateList.length < 3"
      @click="toAdd"
    >
      <div class="add_plate_btn">+添加车牌号</div>
      <div class="btnpb"></div>
    </div>
  </div>
</template>

<script>
import uniPop from '@/components/uni-popup/uni-popup.vue';
import { Dialog } from 'vant';
import LoginDom from '@/components/Login/Login.vue';
// const app = getApp()
const app = {};
import {
  kipGetMemberVehicles,
  kipDeleteMemberVehicles,
} from '@/utils/api-kip.js';
import { LICENSE_PLATE_TYPE_ARR } from '@/constants.js';
import { mapState } from 'vuex';
// import authorize from '@/components/authorize/authorize.vue';
import { isCruMarketByKey } from '@/utils/location-util.js';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import { REG_SOURCE } from '@/constants.js';
import uni from '@/utils/uniHooks.js';
import { vehicles as vehiclesList } from './list';
import { wxToLoginCallback } from '@/utils/index';
import { Toast } from 'vant';

export default {
  components: {
    uniPop,
    // authorize,
    LoginDom,
  },
  computed: {
    ...mapState({
      custTypeId: (state) => state.custTypeId,
      member: (state) => state.member,
      groupId: (state) => state.groupId,
      openid: (state) => state.openid,
      mallid: (state) => state.mallId,
      mobile: (state) => state.mobile,
    }),
  },
  data() {
    return {
      list: [],
      activeId: '',
      activeCarno: '',
      licensePlateList: [],
      isBeijing: false,
      options: null,
      preUrl: '',
      deleteDialogSwitch: false,
      deleteSuccessDialogSwitch: false,
    };
  },

  async created() {
    const option = this.$route.query;
    this.options = option;
    await this.$onLaunched;
    this.localimgPic = this.$staticPicUrl + '/wxminilocalimg/parkingFee/';
    // #ifdef H5
    app.globalData.member = JSON.parse(uni.getStorageSync('member'));
    // #endif
    // 场景二维码记录(是否扫码进入)
    app.globalData.paramsScene = {};
    this.$saveSceneQrcodeDetail(
      'page',
      'vehicleManagement',
      '车牌管理',
      '',
      '',
      '',
      ''
    );
    // 埋点本地化
    this.preUrl = uni.getStorageSync('previousUrl');
    uni.setStorageSync(
      'previousUrl',
      '/pages/parkingFee/vehicleManagement.vue'
    );
  },
  async mounted() {
    setTimeout(() => {
      uni.setNavigationBarTitle({
        title: '车辆管理',
      });
    }, 300);
    // await this.$onLaunched
    this.isBeijing = isCruMarketByKey('北京');
    const member = uni.getStorageSync('member');
    if (JSON.stringify(this.member) !== '{}') {
      this.getKipMemberVehicles();
    } else {
      wxToLoginCallback('vehicleManagement', () => {
        Toast({
          message: '您还未登录，请登录',
          icon: 'none',
          onClose: () => {
            this.$router.back();
          },
        });
      });
      // const regSource = REG_SOURCE.PARKING;
      // app.globalData.regSource = regSource;
      // if (this.options?.regSource) {
      //   app.globalData.regSource = REG_SOURCE[this.options?.regSource];
      // }
      // if (this.options?.tpName) {
      //   app.globalData.tpName = this.options?.tpName;
      // }
      // // this.$refs.authorize.login('/pages/parkingFee/parkingFee', () => {
      // //   this.getKipMemberVehicles()
      // // })
      // this.getKipMemberVehicles();
    }
  },
  onUnload() {
    // #ifdef MP-WEIXIN
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    console.log('==> 车牌管理-返回上一页');
    prevPage.setData({
      parkData: 'parkData',
    });
    // #endif
    // #ifdef H5
    uni.setStorage({
      key: 'parkData',
      data: 'parkData',
      success: function () {
        console.log('parkData-success');
      },
    });
    // #endif
  },
  methods: {
    // 添加车牌号
    toAdd() {
      this.$router.push({ path: 'vehicleAddOrEdit' });
    },
    // 跳转支付页面
    toPay(carno) {
      // 查询车费信息
      uni.showLoading({
        title: '加载中',
      });
      // const openId = MemberCacheTool.getOpenId(app)
      const params = {
        carno,
        mallid: this.mallid,
        openid: this.openid,
        vipcode: this.member?.vipcode,
        mobile: this.mobile,
        groupId: this.groupId,
        createuser: 'sys_miniprogram',
      };
      this.$md(params);
      this.$request({
        url: this.$baseURL + 'api/1.0/park/checkCarIsInPark',
        data: params,
        method: 'POST',
        header: JSON.parse(uni.getStorageSync('handleUser')),
        timeout: 10000,
      })
        .then((res) => {
          console.log(227, res);
          uni.hideLoading();
          if (res.data.code === 0) {
            this.$router.push({
              path: 'parkingFeeDetail?carno=' + carno,
            });
          } else if (res.data.code === 1) {
            // 当前车辆没有查到账单
            this.$router.push({
              path: 'parkingFeePayment?msg=' + res.data.msg + '&carno=' + carno,
            });
          } else if (res.data.code === 2) {
            // 月租车
            this.$router.push({
              path: './parkingFeeHint/parkingFeeHint?carno=' + carno,
            });
          } else {
            uni.showToast({
              title: res.data.msg,
              duration: 2000,
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: '网络超时请稍后再试',
            duration: 2000,
            icon: 'none',
          });
          console.log(err);
        });
    },
    // 编辑
    toEdit(item) {
      if (!item) {
        return;
      }
      const { id, vehicleNo, licensePlateType } = item;
      const carType = LICENSE_PLATE_TYPE_ARR.findIndex(
        (e) => e.value == licensePlateType
      );
      this.sensorsClick('$ClickEditLicensePlate', {
        carno_old: item.vehicleNo,
        redirect_url: 'pages/parkingFee/vehicleAddOrEdit',
      });
      this.$router.replace({
        path: `vehicleAddOrEdit?id=${id}&carno=${vehicleNo}&carType=${carType}`,
      });
    },
    // 删除
    toDelete(item) {
      this.activeId = item.id;
      this.activeCarno = item.vehicleNo;

      Dialog.confirm({
        title: '删除已绑定车牌',
        message: '是否确认删除已经绑定车牌' + '\n' + this.activeCarno,
        confirmButtonColor: '#333',
      })
        .then(() => {
          // on confirm
          this.doDelete();
        })
        .catch(() => {
          // on cancel
          // this.cancelDelete();
        });
      // this.deleteDialogSwitch = true;
    },
    doDelete() {
      uni.showLoading({
        title: '加载中',
      });
      const _this = this;
      kipDeleteMemberVehicles(this.activeId)
        .then((result) => {
          uni.hideLoading();
          // console.log(resp)
          // const result = resp.data
          if (result && result.code == '000000') {
            this.sensorsClick('$ClickDeleteLicensePlate', {
              carno_old: this.activeCarno,
              redirect_url: '',
            });
            if (result.data) {
              // this.deleteDialogSwitch = false;
              // this.deleteSuccessDialogSwitch = true;

              Dialog.alert({
                message: '删除成功',
                confirmButtonColor: '#333',
              }).then(() => {
                // on confirm
                // this.doDelete();
                this.getKipMemberVehicles();
              });
              // _this.$refs.deleteSuccessDialog.open()
              return;
            }
          }
          const message = result.message || '删除失败';
          uni.showToast({
            title: message,
            duration: 2000,
            icon: 'none',
          });
        })
        .catch((err) => {
          uni.hideLoading();
          console.log(err);
          uni.showToast({
            title: '删除失败',
            duration: 2000,
            icon: 'none',
          });
        });
    },
    // 埋点方法
    sensorsClick(eventName, params) {
      let optionsQuery = uni.getStorageSync('options_query');
      let fixedParams = {
          cta_itemno: '',
          cta_name: '',
          previous_url: this.preUrl || '',
          // 原previous_url: uni.getStorageSync('previousUrl') || ''
          // previous_url: 使用sdk预置参数$referrer,
          $brand_id: this.groupId,
          redirect_url: params.redirect_url || '',
          $location: this.mallid,
          $channel: optionsQuery.channel || '',
          // $utm_lbs: this.optionsQuery.utm_lbs || '',
          $utm_channel: optionsQuery.utm_channel || '',
          $utm_method: optionsQuery.utm_method || '',
          $utm_source: optionsQuery.utm_source || '',
          $utm_function: optionsQuery.utm_function || '',
          $utm_user: optionsQuery.utm_user || '',
        },
        finalParams = Object.assign(fixedParams, params);
      this.$sensors.track(eventName, finalParams);
    },
    cancelDelete() {
      this.deleteDialogSwitch = true;
    },
    confirmDialog() {
      // this.$refs.deleteSuccessDialog.close()
      this.deleteSuccessDialogSwitch = false;

      this.getKipMemberVehicles();
    },
    // 获取会员绑定的车牌列表
    getKipMemberVehicles() {
      console.log(453);
      uni.showLoading({
        title: '加载中',
      });
      kipGetMemberVehicles()
        .then((result) => {
          uni.hideLoading();
          console.log(result);
          // const result = resp.data
          if (result && result.code == '000000') {
            const data = result.data || [];
            if (data && data.length > 0) {
              // data.forEach((item) => {
              //   const curLicensePlateType = LICENSE_PLATE_TYPE_ARR.find(
              //     (e) => e.value == item.licensePlateType
              //   )
              //   if (curLicensePlateType) {
              //     item.licensePlateTypeDesc = curLicensePlateType.label
              //   }
              // })
              this.licensePlateList = this.setLicensePlateList(data);
            } else {
              this.licensePlateList = [];
            }
            // this.licensePlateList = vehiclesList.data;
          } else {
            const message = result.message || '获取信息失败';
            uni.showToast({
              title: message,
              duration: 2000,
              icon: 'none',
            });
          }
          console.log(380, this.licensePlateList);
        })
        .catch((err) => {
          uni.hideLoading();
          console.error(err);
        });
      // this.licensePlateList = this.setLicensePlateList(vehiclesList.data);
    },
    setLicensePlateList(data) {
      if (!data.length) return [];
      return data.map((item) => {
        const curLicensePlateType = LICENSE_PLATE_TYPE_ARR.find(
          (e) => e.value == item.licensePlateType
        );
        if (curLicensePlateType) {
          item.licensePlateTypeDesc = curLicensePlateType.label;
        }
        return item;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.scroll-Y {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f4f7ff;
}

.wrap {
  display: flex;
  flex-direction: column;
  width: 100%;

  .wrap_plate {
    margin-top: 24px;
    margin-left: 40px;
    font-size: 30px;

    &.mt36 {
      margin-top: 36px;
    }

    .title {
      // width: 180px;
      // height: 50px;
      font-size: 36px;
      // font-family: PingFangHK-Semibold, PingFangHK;
      font-weight: 600;
      color: #333333;
      line-height: 50px;
      margin-bottom: 20px;
    }

    .desc {
      font-size: 30px;
      font-weight: 400;
      color: #999999;
      line-height: 45px;
    }
  }

  .border-change {
    border: 4px solid #707070;
  }

  .plate_tag-icon {
    position: absolute;
    left: 0;
    top: 40px;
    width: 20px;
    height: 13px;
    opacity: 1;
    border-radius: 0px 12px 1px 0px;
  }

  .plate_tag_icon_green {
    background: #39b54a;
  }

  .plate_tag_icon_blue {
    background: #29abe2;
  }

  .plate_plate {
    width: 670px;
    margin-left: 40px;
    margin-top: 20px;
    padding: 4px;
    border-radius: 20px 128px 20px 20px;

    .plate_border {
      // border-radius: 17px 125px 17px 17px;
      background-color: #064c8a;
      border-radius: 4px;
      padding: 30px;
      color: #ffffff;

      .plate_tag {
        display: inline-block;
        width: 23px;
        height: 14px;
        border-top-right-radius: 18px;
      }

      .bgc-0 {
        background-color: #29abe2;
      }

      .bgc-1 {
        background-color: #39b54a;
      }

      .bgc-2 {
        background-color: #bc9f6d;
      }
    }

    .plate_plate_index {
      padding-left: 37px;
      padding-top: 10px;
      font-size: 26px;
    }

    .plate_plate_index1,
    .plate_plate_index3 {
      font-size: 28px;
      font-weight: 400;
      color: #ffffff;
      line-height: 40px;
      display: flex;
      align-items: center;

      .car-icon {
        width: 40px;
        height: 40px;
        margin-right: 10px;
      }

      .licensePlateTypeDesc {
        margin-left: 5px;
        font-size: 28px;
        font-weight: 500;
        color: #ffffff;
        line-height: 40px;
        margin-left: 20px;
      }

      &.bb {
        padding-bottom: 23px;
        margin-bottom: 23px;
        border-bottom: 1px solid #ffffff;
      }
    }

    .plate_plate_index1 {
      display: inline-block;
      padding-left: 14px;
    }

    .plate_plate_index2 {
      font-weight: 500;
      font-size: 38px;
      font-weight: 600;
      color: #ffffff;
      line-height: 53px;
    }

    .plate_plate_index4 {
      display: flex;
      justify-content: space-around;

      .plate_plate_index4_index2 {
        width: 164px;
      }

      .item {
        width: 33.33%;
        font-size: 28px;
        font-weight: 400;
        color: #ffffff;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        &::after {
          content: '';
          width: 1px;
          height: 30px;
          position: absolute;
          right: 8%;
          background-color: rgba(255, 255, 255, 0.3);
        }

        &:last-child {
          &::after {
            width: 0px;
          }
        }

        img {
          width: 45px;
          height: 45px;
          // margin-right: 10px;
        }

        span {
          flex: 0 0 50%;
          text-align: left;
        }
      }
    }
  }

  .linear-gradient-ORDINARY_CAR_NO {
    // background-image: linear-gradient(#29abe2, #2e3393);
  }

  .linear-gradient-NEW_ENERGY_CAR_NO {
    // background-image: linear-gradient(#8bc63f, #026937);
  }

  .linear-gradient-SPECIAL_CAR_NO {
    // background-image: linear-gradient(#caa86e, #666666);
  }

  .mrg-left-20 {
    margin-left: 20px;
  }
}

.popup-dialog {
  // width: 300px;
  border-radius: 10px;
  background-color: #fff;
}

.dialog-title {
  flex-direction: row;
  justify-content: center;
  padding-top: 10px;
  padding-bottom: 10px;
}

.dialog-title-text {
  font-size: 16px;
  font-weight: 500;
}

.dialog-content {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 15px;
}

.border-top {
  border-top-color: #f5f5f5;
  border-top-style: solid;
  border-top-width: 1px;
}

.dialog-content-text {
  font-size: 14px;
}

.dialog-content-carno {
  font-weight: 500;
  font-size: 16px;
  margin-top: 8px;
}

.dialog-button-group {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  border-top-color: #f5f5f5;
  border-top-style: solid;
  border-top-width: 1px;
}

.dialog-button {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */

  flex: 1;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 45px;
}

.border-left {
  border-left-color: #f0f0f0;
  border-left-style: solid;
  border-left-width: 1px;
}

.dialog-button-text {
  font-size: 14px;
  color: #6e6e6e;
}

.add_plate_no_data {
  width: 90%;
  height: 200px;
  text-align: center;
  line-height: 200px;
  // border: 1px dashed #eaeaea;
  border: 1px solid #d8dae0;
  margin-left: 40px;
  margin-top: 20px;
  color: #999999;
  background-color: #fafbff;
}
.add_plate_box {
  text-align: center;
  // border: 1px dashed #eaeaea;
  background-color: #fafbff;
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  z-index: 999;
  padding: 30px 30px 0 30px;
  box-shadow: 0px 13px 33px 0px rgba(190, 187, 187, 0.2);
  .btnpb {
    width: 100%;
    padding-bottom: 30px;
    margin-bottom: 30px;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
  .add_plate_btn {
    width: 100%;
    // margin-left: 30px;
    height: 90px;
    line-height: 90px;
    background: #064c8a;
    border-radius: 45px;
    font-size: 34px;
    font-weight: 400;
    color: #ffffff;
  }
}
</style>
