<template>
  <view>
    <u-navbar
      title-color="#fff"
      :custom-back="customBack"
      :border-bottom="false"
      back-icon-color="#CCE8FF"
      :background="{ background: '#008CFF' }"
      title="车辆管理"
    ></u-navbar>
    <view class="header">
      <view class="header-title">我的车辆</view>
    </view>
    <view class="wrap">
      <view class="statistics">
        <view class="statistics-title">车辆</view>
        <view class="statistics-center"></view>
        <view class="statistics-number-wrap"
          ><span class="number">{{ mycarsTotal }}</span
          >辆</view
        >
      </view>
      <view class="new-plate-number">
        <view class="message-input-wrap" @click="messageInputClick">
          <u-message-input :maxlength="8" width="70" font-size="50" :disabled-keyboard="true" v-model="newPlateNumber"></u-message-input>
        </view>
        <u-keyboard
          ref="uKeyboard"
          mode="car"
          @change="keyboardChange"
          @confirm="keyboardConfirm"
          @backspace="backspace"
          v-model="keyboardshow"
        ></u-keyboard>
      </view>
      <view class="add-car-btn" @click="handleAddCar">添加车辆</view>
      <view class="mycars">
        <template v-if="mycars.length">
          <view class="mycars-item" v-for="(item, index) in mycars" :key="index">
            <view class="mycars-item-name">{{ item.vehicleNo }}</view>
            <view class="mycars-item-type">{{ item.energyTpye | energyTpye }}</view>
            <view class="mycars-item-sign" v-if="item.contractStatus == 1">已签约</view>
            <view class="mycars-item-sign1" v-if="item.contractStatus == 0">未签约</view>
            <view class="mycars-item-tool">
              <span class="default" v-if="item.isDefault == 1" :class="{ isDefault: item.isDefault == 1 }" @click="handlesetDefault(item.id)"
                >默认</span
              >
              <span class="default" v-else @click="handlesetDefault(item.id)">设为默认</span>
              <span @click="handleDelCar(item.id, item.vehicleNo)">删除</span>
            </view>
          </view>
          <u-loadmore :status="status" />
        </template>
        <template v-else>
          <u-empty text="无车辆数据" mode="list"></u-empty>
        </template>
      </view>
    </view>

    <u-toast ref="uToast" />
    <u-modal v-model="delCarshow" :show-cancel-button="true" @confirm="confirmDelCar" :content="delCarContent"></u-modal>
    <u-action-sheet :list="colorList" @click="confirmColor" v-model="colorShow"></u-action-sheet>
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyboardshow: false,
      delCarshow: false,
      delCarId: null,
      delCarContent: '',
      newPlateNumber: '',
      vehicleColor: 0,
      mycars: [],
      status: 'loadmore',
      page: {
        num: 1,
        size: 10,
        total: 0
      },
      mycarsTotal: 0,
      colorShow: false,
      colorList: [
        { text: '蓝色', colorCode: 0 },
        { text: '黄色', colorCode: 1 },
        { text: '黑色', colorCode: 2 },
        { text: '白色', colorCode: 3 },
        { text: '绿色', colorCode: 4 },
        { text: '其他', colorCode: 99 }
      ]
    };
  },
  onLoad() {
    this.mycars = [];
    this.handlegetMycars();
  },
  onPullDownRefresh() {
    Object.assign(this, {
      keyboardshow: false,
      delCarshow: false,
      delCarId: null,
      delCarContent: '',
      newPlateNumber: '',
      vehicleColor: 0,
      mycars: [],
      status: 'loadmore',
      page: {
        num: 1,
        size: 10,
        total: 0
      },
      mycarsTotal: 0,
      colorShow: false,
      colorList: [
        { text: '蓝色', colorCode: 0 },
        { text: '黄色', colorCode: 1 },
        { text: '黑色', colorCode: 2 },
        { text: '白色', colorCode: 3 },
        { text: '绿色', colorCode: 4 },
        { text: '其他', colorCode: 99 }
      ]
    });
    setTimeout(() => {
      this.handlegetMycars();
      uni.stopPullDownRefresh(); //停止刷新
    }, 1000);
  },
  onReachBottom() {
    if (this.page.num >= this.page.total) return;
    this.status = 'loading';
    this.page.num = ++this.page.num;
    setTimeout(() => {
      this.handlegetMycars();
    }, 1500);
  },
  methods: {
    customBack() {
      uni.getStorage({
        key: 'messageBack',
        success: (res) => {
          this.$u.route({
            type: 'switchTab',
            url: res.data
          });
        },
        fail: () => {
          this.$u.route({
            type: 'switchTab',
            url: 'pages/index/index'
          });
        }
      });
    },
    // 获取车辆列表
    handlegetMycars() {
      const { num, size } = this.page;
      this.$u.api.getMycars({ pageNum: num, pageSize: size }).then((res) => {
        if (res.code === 200) {
          this.mycars = this.mycars.concat(res?.data?.rows ?? []);
          this.page.total = Number(res?.data?.pages ?? 0);
          this.mycarsTotal = Number(res?.data?.total ?? 0);
          if (this.page.num >= this.page.total) this.status = 'nomore';
          else this.status = 'loading';
        }
      });
    },
    // 添加车辆
    async handleAddCar() {
      const { newPlateNumber, vehicleColor } = this;
      if (!this.$u.test.carNo(newPlateNumber)) {
        this.showToast('请正确填写车牌号', 'warning');
        return;
      }
      try {
        const { code, msg } = await this.$u.api.addCar({ vehicleNo: newPlateNumber, vehicleColor });
        if (code === 200) {
          this.showToast(msg, 'success');
          Object.assign(this.page, {
            num: 1,
            size: 10,
            total: 0
          });
          this.mycars = [];
          this.newPlateNumber = '';
          this.vehicleColor = '';
          this.handlegetMycars();
        }
      } catch (error) {
        this.showToast('操作失败!', 'error');
      }
    },
    // 删除车辆
    handleDelCar(id, content) {
      this.delCarContent = `是否删除${content}`;
      this.delCarId = id;
      this.delCarshow = true;
    },
    // 确认删除
    async confirmDelCar() {
      try {
        const { code, msg } = await this.$u.api.delCar(this.delCarId);
        if (code === 200) {
          this.showToast(msg, 'success');
          Object.assign(this.page, {
            num: 1,
            size: 10,
            total: 0
          });
          this.mycars = [];
          this.handlegetMycars();
        }
      } catch (error) {
        this.showToast('操作失败!', 'error');
      }
    },
    // 点击输入框
    messageInputClick() {
      this.keyboardshow = true;
    },
    // 按键被点击(点击退格键不会触发此事件)
    keyboardChange(val) {
      // 将每次按键的值拼接到value变量中，注意+=写法
      this.newPlateNumber += val;
    },
    // 退格键被点击
    backspace() {
      // 删除value的最后一个字符
      if (this.newPlateNumber.length) this.newPlateNumber = this.newPlateNumber.substr(0, this.newPlateNumber.length - 1);
    },
    // 键盘输入完成后确认
    keyboardConfirm() {
      this.colorShow = true;
    },
    // 确认颜色
    confirmColor(e) {
      this.vehicleColor = this.colorList[e].colorCode;
    },
    // 设置默认车辆操作
    async handlesetDefault(id) {
      try {
        const { code, msg } = await this.$u.api.setDefaultCar({ id });
        if (code === 200) {
          this.showToast(msg, 'success');
          Object.assign(this.page, {
            num: 1,
            size: 10,
            total: 0
          });
          this.mycars = [];
          this.handlegetMycars();
        }
      } catch (error) {
        this.showToast('操作失败!', 'error');
      }
    },
    /**
     * @description: 显示提示
     * @param {*} title
     * @param {*} type
     * @return {*}
     */
    showToast(title = '操作失败', type = 'info') {
      this.$refs.uToast.show({ title, type });
    }
  }
};
</script>

<style lang="scss" scoped>
@import url('./myCars.scss');
</style>
