<template>
  <div>
    <div class="select" @click="openPicker">
      <div class="proName">{{ project.proName }}</div>
      <div class="tip">
        <div>请选择</div>
        <u-icon name="arrow-right" />
      </div>
    </div>

    <u-picker
      :show="showPro"
      :columns="columns"
      keyName="label"
      @cancel="showPro = false"
      @confirm="handleSelect"
    ></u-picker>
  </div>
</template>

<script>
import { selectProAddress } from '@/api/educationTraining'

export default {
  data() {
    return {
      showPro: false,
      project: {}, // 选中的工程
      proName: '', // 工程名称
      columns: [] // 下拉数据
    }
  },
  created() {
    this.getProOptions()
    setTimeout(() => {
      if (this.project) {
        this.$emit('selectPro', this.project)
      }
    }, 500)
  },
  methods: {
    // 打开下拉
    openPicker() {
      this.showPro = true
      this.getProOptions()
    },
    // 获取工程-下拉
    async getProOptions() {
      const params = {
        userId: uni.getStorageSync('userInfo').userId,
        userType: uni.getStorageSync('userInfo').userType
      }
      console.log('🚀 ~ getProOptions ~ params:', params)
      const res = await selectProAddress(params)
      res.data.forEach(item => {
        item.label = item.proName
        item.value = item.proId
      })
      console.log('🚀 ~ 工程下拉 ~ res:', res)
      this.columns = [res.data]
      console.log('🚀 ~ getProOptions ~ this.columns:', this.columns)
      if (uni.getStorageSync('selectProId')) {
        // 如果能够查到上次选择的工程 则默认上次选择的工程, 否则默认第一个工程
        const lastPro = res.data.find(item => item.proId == uni.getStorageSync('selectProId'))
        console.log('🚀 ~ getProOptions ~ lastPro:', lastPro)
        if (lastPro) {
          this.project = lastPro
        } else {
          this.project = res.data[0]
        }
      } else {
        // this.proName 默认第一个工程
        this.project = res.data[0]
      }
      console.log('🚀 ~ getProOptions ~ this.project:', this.project)
    },
    // 选择工程
    handleSelect(item) {
      console.log('handleSelect', item.value[0])
      this.project = item.value[0]
      this.showPro = false
      this.$emit('selectPro', item.value[0])
      uni.setStorageSync('selectProId', item.value[0].proId)
    }
  }
}
</script>

<style lang="scss" scoped>
.select {
  height: 40px;
  border: 1px solid #ebeef5;
  border-radius: 40px;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .proName {
    width: 70%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .tip {
    display: flex;
    align-items: center;
    color: #c0c4cc;
    u-icon {
      margin-left: 10px;
    }
  }
}
</style>
