<template>
  <view class="content">
    <view class="c-top">
      <view class="" @click="getback()">
        <uni-icons type="left" size="18"></uni-icons>
      </view>
      <view class="c-title">{{ topName }}</view>
      <view class=""></view>
    </view>
    <view class="ail">
      <view class="on-input">
        <view class="s-huix">姓名：</view>
        <view class=""><input v-model="staff.name" type="text" placeholder="请输入姓名"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">电话：</view>
        <view class=""><input v-model="staff.tel" type="text" placeholder="请输入手机号"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">学历：</view>
        <view class="" @click="showEducation = true"><input disabled :value="getEducation" type="text"
                                                            placeholder="请选择学历"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">身份证号：</view>
        <view class=""><input v-model="staff.idNumber" type="text" placeholder="请输入身份证号"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">入职时间：</view>
        <view class="" @click="showJoinedDate = true"><input disabled :value="formattedJoinedDate" type="text"
                                                             placeholder="请选择入职时间"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">转正时间：</view>
        <view class="" @click="showFormalDate = true"><input disabled :value="formattedFormalDate" type="text"
                                                             placeholder="请选择转正时间"></view>
      </view>
      <view class="on-input">
        <view class="s-huix">购买保险时间：</view>
        <view class="" @click="showSafeDate = true"><input disabled :value="formattedSafeDate" type="text"
                                                           placeholder="请选择购买保险时间"></view>
      </view>
      <view class="">
        <view style="display: flex;justify-content: space-between;margin: 1rem auto">
          <view class="s-huix" style="text-align: left">附件：</view>
          <view class="" style="color: #3391ff" @click="addFile">添加附件</view>
        </view>
        <view v-for="(item, index) in files" style="margin-bottom: 1rem;border-bottom: 1px solid #DAE1F8;">
          <view class="on-input">
            <view class="s-huix">名称：</view>
            <view class=""><input v-model="item.fileName" type="text" placeholder="请输入附件名称"></view>
          </view>
          <u-upload v-if="!item.fileUrl"
                    @afterRead="uploadFilePromise($event, index)"
                    name="6"
                    multiple
                    :maxCount="1"
                    width="100%"
                    height="140px"
          >
          </u-upload>
          <view v-else class="image-container">
            <image :src="item.fileUrl" style="width: 100%;height: 140px;"></image>
            <view @click="deletedUrl(index)" class="close-button">
              <text>x</text>
            </view>
          </view>
        </view>
      </view>
      <view class="tjiao" @click="getyadd">
        <text>保存更改</text>
      </view>
    </view>

    <u-picker :show="showEducation" ref="uPicker" :columns="[educations]"
              @confirm="chooseEducation" @cancel="showEducation = false"
              keyName="label"></u-picker>

    <u-datetime-picker
        :show="showJoinedDate"
        v-model="staff.joinedDate"
        @cancel="showJoinedDate = false"
        @confirm="chooseJoinDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
    <u-datetime-picker
        :show="showFormalDate"
        v-model="staff.formalDate"
        @cancel="showFormalDate = false"
        @confirm="chooseFormalDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
    <u-datetime-picker
        :show="showSafeDate"
        v-model="staff.safeDate"
        @cancel="showSafeDate = false"
        @confirm="chooseSafeDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
  </view>
</template>

<script>
import request from "../../utils/request";
import {formatDate, getDictDataByType} from "../../utils/utils";
import config from '@/config'
import upload from '@/utils/upload.js'

export default {
  name: "StaffInfo",
  data(){
    return{
      userId: null,
      staff: {},
      user: {},
      educations: [],
      files: [],
      showEducation: false,
      showJoinedDate: false,
      showFormalDate: false,
      showSafeDate: false,
      topName: null
    }
  },
  onLoad(data){
    if (data.id){
      this.userId = data.id
      this.getInfoByUserId()
    }
  },
  computed:{
    getEducation(){
      if (!this.educations || this.educations.length === 0){
        this.getEducations()
      }
      const index = this.educations.findIndex(item => item.value === this.staff.education)
      if (index !== -1){
        return this.educations[index].label
      }
      return ''
    },
    formattedJoinedDate() {
      if (!this.staff.joinedDate) return '';
      return formatDate(this.staff.joinedDate); // 确保formatDate返回'yyyy-MM-dd'格式
    },
    formattedFormalDate() {
      if (!this.staff.formalDate) return '';
      return formatDate(this.staff.formalDate); // 确保formatDate返回'yyyy-MM-dd'格式
    },
    formattedSafeDate() {
      if (!this.staff.safeDate) return '';
      return formatDate(this.staff.safeDate); // 确保formatDate返回'yyyy-MM-dd'格式
    },
  },
  methods:{
    getyadd(){
      if (!this.staff.name || !this.staff.tel) {
        uni.showToast({
          title: '姓名和电话不能有空',
          icon: 'none'
        })
        return
      }
      const data = {
        ...this.staff,
        fileNames: this.files.length > 0 ? this.files.map(item => item.fileName).join(",") : null,
        fileUrls: this.files.length > 0 ? this.files.map(item => {
          return item.fileUrl.replace(config.baseImageUrl + "/", "")
        }).join(",") : null
      }
      request({
        url: '/company/staff/updateByExistUser',
        method: 'post',
        data: data
      }).then(res => {
        uni.showToast({
          title: "保存成功"
        })
        this.getInfoByUserId()
      })
    },
    addFile() {
      if (this.files.length === 0 || this.files[0].fileUrl !== null) {
        this.files.unshift({
          fileName: "未命名",
          fileUrl: null
        })
      }
    },
    uploadFilePromise(event, index) {
      upload({
        url: '/common/upload',
        filePath: event.file[0].url,
      }).then((res) => {
        this.files[index].name = event.file[0].name
        this.files[index].fileUrl = config.baseImageUrl + "/" + res.data.url
      })
    },
    deletedUrl(index) {
      this.files.splice(index, 1)
    },
    chooseJoinDate(e) {
      this.staff.joinedDate = formatDate(e.value)
      this.showJoinedDate = false
    },
    chooseFormalDate(e) {
      this.staff.formalDate = formatDate(e.value)
      this.showFormalDate = false
    },
    chooseSafeDate(e) {
      this.staff.safeDate = formatDate(e.value)
      this.showSafeDate = false
    },
    chooseEducation(e) {
      this.$set(this.staff, 'education', e.value[0].value)
      // this.staff['education'] = e.value[0].value
      this.showEducation = false
    },
    async getEducations(){
      this.educations = await getDictDataByType("company_staff_edu")
    },
    async getInfoByUserId(){
      const res = await request({
        url: '/company/staff/getByUserId?id=' + this.userId,
        method: 'get'
      })
      const data = res.data
      this.staff = data?.staff || this.staff
      this.user = data?.user
      this.topName =  this.user?.nickname || this.staff?.name || this.user?.username
      this.staff.name = this.user?.nickname || this.user?.username
      if (!data?.staff){
        this.staff.tel = this.user?.username || this.user?.mobile
        this.staff.userId = this.user.id
      }
      if (this?.staff?.fileNames){
        this.files = []
        const names = this.staff.fileNames.split(",")
        const urls = this.staff.fileUrls.split(",")
        names.forEach((item, index) => {
          const temp = {
            fileName: item,
            fileUrl: config.baseImageUrl + (urls[index][0] === "/" ? urls[index] : "/" + urls[index])
          }
          this.files.push(temp)
        })
      }
    },
    getback(){
      uni.navigateBack()
    },
  }
}
</script>

<style scoped lang="scss">
.content {
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh);
  background: white;
}
.c-top{
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
  padding-top: 55px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
}
.c-title{
  font-size: 18px;
  font-weight: bold
}
.ail{
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
}
.on-input {
  width: 100%;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #DAE1F8;;
  box-sizing: border-box;
  padding-bottom: 5px;
  margin: 10px;
  justify-content: space-between;
}
.on-input input {
  text-align: right;
  padding-right: 1rem
}
.s-huix {
  width: 30%;
  text-align: right;
}
.image-container {
  position: relative; /* 使子元素可以相对于此容器进行绝对定位 */
  width: 100%;
  height: 140px;
}

.close-button {
  position: absolute;
  top: 5px; /* 调整距离顶部的距离 */
  right: 5px; /* 调整距离右侧的距离 */
  width: 24px; /* 圆的直径 */
  height: 24px;
  background-color: #ff0000;
  color: white;
  border-radius: 50%; /* 使按钮呈现圆形 */
  display: flex;
  //align-items: center;
  justify-content: center;
  font-size: 16px; /* 调整“X”的字体大小 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
}

.tjiao {
  width: 40%;
  height: 30px;
  margin: 5px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #0D2E8D;
  color: white;
  border-radius: 50px;
}
</style>
