<template>
  <view>
    <u-form-item
        :label="label"
        :prop="prop"
        :required="required"
        @click="fnShowPicker"
    >
      <view class="select_content">
        <u-input
            :value="name || '请选择'"
            border="none"
            input-align="right"
            readonly
        />
        <u-icon name="arrow-right"></u-icon>
      </view>
    </u-form-item>
    <u-line/>
    <u-picker
        :show="visible"
        :columns="[columns]"
        key-name="NAME"
        :default-index="[defaultIndex]"
        @cancel="visible = false"
        @confirm="fnConfirm"
    />
  </view>
</template>

<script>
import {getUserList} from "@/api";

export default {
  props: {
    name: {
      type: String,
      required: true,
      default: "",
    },
    id: {
      type: String,
      required: true,
      default: "",
    },
    label: {
      type: String,
      default: "人员",
    },
    prop: {
      type: String,
      default: "",
    },
    required: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    departmentId: {
      type: String,
      required: false,
    },
    corpInfoId: {
      type: String,
      required: false,
    },
    // 是否允许选择当前登录人
    isAllowSelectionCurrentPerson: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      visible: false,
      columns:[],
      defaultIndex:0
    }
  },
  methods: {
    async fnGetData() {
      const resData = await getUserList({
        DEPARTMENT_ID: this.departmentId,
        TYPE:'0',
        CORP_ID:this.$store.getters.getUserInfo.CORPINFO_ID,
        loading: false,
        // postMethod: 'application/json',
      });
      this.columns = resData.list.list;
    },
    fnShowPicker(){
      if (this.disabled) return;
      if (this.columns.length === 0) {
        uni.showToast({
          title: "暂无可选人员",
          icon: "none",
        });
        return;
      }
      this.visible = true;
      this.defaultIndex = 0;
      for (let i = 0; i < this.columns.length; i++) {
        if (this.columns[i].USER_ID === this.id) {
          this.defaultIndex = i;
          break;
        }
      }
    },
    fnConfirm(event){
      if (!this.isAllowSelectionCurrentPerson) {
        if (event.value[0].USER_ID === this.$store.getters.getUserInfo.USER_ID) {
          uni.showToast({
            title: "不能选择当前登录人",
            icon: "none",
          });
          return;
        }
      }
      this.$emit("update:id", event.value[0].USER_ID);
      this.$emit("update:name", event.value[0].NAME);
      this.$emit("confirm", event.value[0]);
      this.visible = false;
    }
  },
  watch:{
    departmentId(val) {
      if (val) this.fnGetData();
      else this.columns = [];
    }
  }
}
</script>

<style scoped lang="scss"></style>
