<template>
  <view class="content">
    <headersVue :titles="titles">
      <u-icon name="arrow-left" color="#fff" size="18"></u-icon>
    </headersVue>
    <view class="container">
      <view class="box_">
        <view class="d_s" style="margin-bottom: 10px;" v-if="userId">
          <view class="touxiang_">
            <image src="/static/imgs/yh.png" mode=""></image>
          </view>
          <view class="">
            <view class="name_">{{ staff.nickname }}</view>
            <view class="d_s">
              <view class="tel_">
                <image src="/static/imgs/tel.png" mode=""></image>
              </view>
              <view class="telnum">手机号：{{ staff.mobile }}</view>
            </view>
          </view>
        </view>
        <view class="d_b" v-if="!userId">
          <view class="">姓名</view>
          <input type="text" placeholder="请输入姓名" v-model="staff.nickname" style="text-align: right;"/>
        </view>
        <view class="d_b" v-if="!userId">
          <view class="">手机号</view>
          <input type="text" placeholder="请输入手机号" v-model="staff.mobile" style="text-align: right;"/>
        </view>
        <view class="d_b">
          <view class="">学历</view>
          <view class="" @click="showEducation = true">
            {{ staff.educational != null ? this.staff.educational : '请选择学历' }} >
          </view>
        </view>
        <view class="d_b">
          <view class="">身份证号</view>
          <input type="text" placeholder="请输入身份证号" v-model="staff.idCard" style="text-align: right;"/>
        </view>
        <view class="d_b">
          <view class="">入职时间</view>
          <view class="" @click="showJoinedDate = true">
            {{ staff.joinDate != null ? this.staff.joinDate : '请选择入职时间' }} >
          </view>
        </view>
        <view class="d_b">
          <view class="">转正时间</view>
          <view class="" @click="showFormalDate = true">
            {{ staff.probationPeriod != null ? this.staff.probationPeriod : '请选择转正时间' }} >
          </view>
        </view>
        <view class="d_b">
          <view class="">购买保险时间</view>
          <view class="" @click="showSafeDate = true">
            {{ staff.socialSecurityBuyDate != null ? this.staff.socialSecurityBuyDate : '请选择购买保险时间' }} >
          </view>
        </view>
        <view class="d_b">
          <view class="">驾照类型</view>
          <view class="" @click="showDriveType = true">
            {{ driverLicenseTypeArrStr != null ? this.driverLicenseTypeArrStr : '请选择驾照类型' }} >
          </view>
        </view>
        <view class="d_b" v-if="!userId">
          <view class="">岗位</view>
          <view class="" @click="showRole = true">
            {{ roleName != null ? this.roleName : '请选择岗位' }} >
          </view>
        </view>
        <view class="d_b" @click="handleUpload">
          <view class="">附件</view>
          <view class="lan_">上传附件
            <image src="/static/imgs/add.png" mode=""></image>
          </view>
        </view>
        <u-upload
            ref="uploadRef"
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="10"
            v-show="fileList1.length > 0"
        >
        </u-upload>
        <view class="hui_box" v-if="fileList1.length == 0">
          <image src="/static/imgs/wod.png" mode=""></image>
          <view class="">
            <view class="big_">附件格式 jpg/png</view>
            <view class="sm_">100KB</view>
          </view>
        </view>


        <view class="anniu" @click="submit">
          {{ buttonTile }}
        </view>
      </view>
    </view>

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

    <u-picker :show="showRole" ref="uPicker" :columns="[roles]"
              @confirm="chooseRole" @cancel="showRole = false"
              keyName="name"></u-picker>

    <qianziyu-select
        :show="showDriveType"
        type="checkbox"
        name="id"
        :dataLists="driverLicenseType"
        :showSearch=false
        @cancel="showDriveType = false"
        :checkboxData="driverLicenseTypeArr"
        @submit="onsubmit"
        @update:checkboxData="driverLicenseTypeArr = $event"
    >
    </qianziyu-select>

    <u-datetime-picker
        :show="showJoinedDate"
        v-model="selectJoinDate"
        @cancel="showJoinedDate = false"
        @confirm="chooseJoinDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
    <u-datetime-picker
        :show="showFormalDate"
        v-model="selectProbationPeriod"
        @cancel="showFormalDate = false"
        @confirm="chooseFormalDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
    <u-datetime-picker
        :show="showSafeDate"
        v-model="selectSocialSecurityBuyDate"
        @cancel="showSafeDate = false"
        @confirm="chooseSafeDate"
        mode="date"
        return-type='string'
    ></u-datetime-picker>
  </view>
</template>

<script>
import headersVue from '../../components/header/headers.vue';
import request from "@/utils/request";
import {formatDate, getDictDataByType} from "@/utils/utils";
import upload from "@/utils/upload";
import {baseImageUrl} from "@/config";

export default {
  data() {
    return {
      titles: "新增员工",
      staff: {
        joinDate: null,
        probationPeriod: null,
        socialSecurityBuyDate: null,
      },
      fileList1: [],
      selectJoinDate: new Date().toString(),
      selectProbationPeriod: new Date().toString(),
      selectSocialSecurityBuyDate: new Date().toString(),
      buttonTile: '保存',
      show: false,
      showRole: false,
      status: 'loading',
      userId: undefined,
      showEducation: false,
      showJoinedDate: false,
      showFormalDate: false,
      showSafeDate: false,
      showDriveType: false,
      educations: [],
      roles: [],
      driverLicenseType: [],
      driverLicenseTypeArr: [],
      driverLicenseTypeArrStr: null,
      roleName: null,
    }
  },
  components: {
    headersVue
  },
  onLoad(data) {
    if (data.id) {
      this.titles = '编辑员工'
      this.userId = data.id
      this.getInfoByUserId()
      this.buttonTile = '修改'
    }
    this.getEducation()
    this.getDriveType()
    this.getRoles()
  },
  methods: {
    cancelShow() {
      this.show = !this.cancelShow
    },
    async getRoles() {
      let res = await request({
        url: '/system/role/pageByQuery',
        method: 'get',
        params: {
          servicePackageId: 'jiance'
        }
      })
      this.roles = res.data
    },
    onsubmit(selectedData) {
      selectedData.map(item => item.id);
      this.driverLicenseTypeArr = selectedData;
      this.driverLicenseTypeArrStr = selectedData.map(item => item.id).join(',');
      this.showDriveType = false; // 提交后关闭弹窗
    },
    getDriveType() {
      return request({
        url: '/common/down/getDriverLicenseType',
        method: 'get'
      }).then(res => {
        //提取出数组中的id属性
        this.driverLicenseType = res.data
      })
    },
    submit() {
      //判断是否是修改
      console.log(this.staff.fileList)
      if (this.userId) {
        this.update()
      }else {
        this.add()
      }
    },
    update() {
      // 验证表单信息
      const flag = this.validData()
      if (!flag) {
        return
      }

      this.staff.userId = this.userId
      console.log(this.staff)
      const data = {
        ...this.staff,
        fileList: this.fileList1,
        driverLicenseType: this.driverLicenseTypeArrStr,
        driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id)
      }
      request({
        url: '/inspectionStaff/update',
        method: 'put',
        data: data
      }).then(res => {
        uni.showToast({
          title: "编辑成功"
        })
        this.getInfoByUserId()
      })
    },
    async add() {
      // 验证表单信息
      const flag = this.validData()
      if (!flag) {
        return
      }
      let data = {
        nickname: this.staff.nickname,
        mobile: this.staff.mobile,
        username: this.staff.nickname,
        status: 0,
        userType: '01',
        roleId: this.staff.roleId,
        name: this.nickname,
        joinDate: this.staff.joinDate,
        idCard: this.staff.idCard,
        educational: this.staff.educational,
        probationPeriod: this.staff.probationPeriod,
        socialSecurityBuyDate: this.staff.socialSecurityBuyDate,
        driverLicenseTypeArr: this.driverLicenseTypeArr.map(item => item.id),
        password: '123456'
      }
      let res = await request({
        url: '/inspectionStaff/save',
        method: 'post',
        data: data
      })
      if (res.code == 200) {
        let roleIds = []
        roleIds.push(this.staff.roleId)
        let resp = await request({
          url: '/system/permission/assign-user-role',
          method: 'post',
          data: {
            userId: res.data,
            roleIds: roleIds
          }
        })
        uni.showToast({
          title: "添加成功"
        })
        this.show = false
        this.getindex()
      }
    },
    validData() {
      if (!this.staff.nickname || !this.staff.mobile) {
        uni.showToast({
          title: '姓名和电话不能有空',
          icon: 'none'
        })
        return false
      }
      if (!this.staff.roleId && !this.userId) {
        uni.showToast({
          title: '请选择岗位',
          icon: 'none'
        })
        return false
      }
      return true
    },
    chooseJoinDate(e) {
      this.$nextTick(() => {
        this.staff.joinDate = formatDate(e.value)
        this.selectJoinDate = this.staff.joinDate
      })
      this.showJoinedDate = false
      console.log(this.staff)
    },
    chooseFormalDate(e) {
      this.$nextTick(() => {
        this.staff.probationPeriod = formatDate(e.value);
        this.selectProbationPeriod = this.staff.probationPeriod
      })
      this.showFormalDate = false;
      console.log(this.staff)
    },
    chooseSafeDate(e) {
      this.$nextTick(() => {
        this.staff.socialSecurityBuyDate = formatDate(e.value)
        this.selectSocialSecurityBuyDate = this.staff.socialSecurityBuyDate
      })
      this.showSafeDate = false
      console.log(this.staff)
    },
    async getInfoByUserId() {
      const res = await request({
        url: '/inspectionStaff/get',
        params: {
          id: this.userId
        },
        method: 'get'
      })
      this.staff = res.data
      this.topName = this.staff?.nickname
      if (res.data.driverLicenseType) {
        this.driverLicenseTypeArrStr = res.data.driverLicenseType
        res.data.driverLicenseTypeArr.forEach(item => {
          let temp = {
            id: item,
            name: item
          }
          this.driverLicenseTypeArr.push(temp)
        })
      }
      if (this?.staff?.fileList) {
        this.fileList1 = []
        this.staff.fileList.forEach((item) => {
          const temp = {
            name: item.name,
            url: item.url.startsWith("http") ? item.url : baseImageUrl + '/' + item.url
          }
          this.fileList1.push(temp)
        })
        console.log('tupian', this.fileList1)
      }
    },
    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 ''
    },
    async getEducations() {
      this.educations = await getDictDataByType("company_staff_edu")
    },
    chooseEducation(e) {
      this.$set(this.staff, 'education', e.value[0].label)
      this.staff.educational = e.value[0].label
      this.showEducation = false
    },
    chooseRole(e) {
      console.log(e)
      this.staff.roleId = e.value[0].id
      this.roleName = e.value[0].name
      this.showRole = false
    },

    // 上传相关方法
    handleUpload() {
      // 通过 ref 获取 u-upload 组件实例，并调用其上传方法
      this.$refs.uploadRef.chooseFile();
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        // let a = uni.uploadFile({
        //   url: "http://192.168.2.21:7001/upload", // 仅为示例，非真实的接口地址
        //   filePath: url,
        //   name: "file",
        //   formData: {
        //     user: "test",
        //   },
        //   success: (res) => {
        //     setTimeout(() => {
        //       resolve(res.data.data);
        //     }, 1000);
        //   },
        // });
        upload({
          url: '/common/upload',
          filePath: url,
        }).then((res) => {
          resolve(res.data.url);
          console.log(this.fileList1)
          this.forceRefreshFiles(); // 强制刷新文件列表
        })
      });
    },
  },
}
</script>

<style scoped lang="scss">
.content {
  background: #f4f5f6;
  height: 100vh;
}

.container {
  width: 100%;
  background: #f4f5f6;
  box-sizing: border-box;
  padding: 30rpx;
  padding-top: 200rpx;
  padding-bottom: 28px;
}

.box_ {
  background: #FFFFFF;
  width: 100%;
  box-sizing: border-box;
  padding: 30rpx;
  border-radius: 8rpx;
}

.d_s {
  display: flex;
  align-items: center;

}

.d_b {
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 30rpx 0rpx;
  border-top: 2rpx solid #F5F6F9;
  font-size: 28rpx;
  color: #8D90A6;

}

.touxiang_ {
  width: 90rpx;
  height: 90rpx;
  margin-right: 20rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.tel_ {
  width: 30rpx;
  height: 30rpx;
  margin-right: 20rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.name_ {
  font-size: 32rpx;
  color: #101A3E;
  margin-bottom: 5px;
}

.telnum {
  font-size: 24rpx;
  color: #366FFF;
}

.lan_ {
  font-size: 28rpx;
  color: #327DFB;
  display: flex;
  align-items: center;

  image {
    width: 36rpx;
    height: 36rpx;
    margin-left: 15rpx;
  }
}

.hui_box {
  width: 100%;
  background: #F5F6F9;
  border-radius: 16rpx;
  box-sizing: border-box;
  padding: 30rpx;
  display: flex;
  align-items: center;

  image {
    width: 90rpx;
    height: 90rpx;
    margin-right: 15rpx;
  }
}

.big_ {
  font-size: 28rpx;
  color: #101A3E;
}

.sm_ {
  font-size: 22rpx;
  color: #8D90A6;
}

.anniu {
  width: 622rpx;
  height: 78rpx;
  background: #427FFE;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  margin-top: 200rpx;
}
</style>
