<script setup lang="ts">
/**
 * @description 档案详情
 */

defineOptions({ name: 'StaffDetail' })

import { useQuery, useMutation } from '@tanstack/vue-query'
import { getRecordsDetail, editRecordsDetail, generateStaffNum } from '@/api/oa/staffRecords'
import { getConfigDict } from './index'
import { ElRow, FormInstance } from 'element-plus'
// import TechCertificate from './TechCertificate.vue'
import avatarImg from '@/assets/imgs/avatar.jpg'
import DeptSelect from '@/components/DeptSelect/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import WorkTable from './WorkTable.vue'
import FamilyTable from './familyTable.vue'
import SchoolTable from './SchoolTable.vue'
import moment from 'moment'

const formConfigList = getConfigDict()

const { query } = useRoute()
const { id, type } = query
const formRef = ref<FormInstance>()
const formData = ref({})
let avatar = avatarImg

/**获取员工档案详情 */
useQuery(
  ['fetch-staff-detail', id],
  async () => {
    return await getRecordsDetail({ userId: id })
  },
  {
    onSuccess: (res) => {
      formData.value = handleTimeData(res)
      // formData.value = res
      // if (Array.isArray(formData.value['bysj'])) {
      //   formData.value['bysj'] = res.bysj.join('-')
      // }
      avatar = res.avatar ? res.avatar : avatar
    }
  }
)

// 处理 [2001, 1, 1] 格式的时间数据
const handleTimeData = (dataSource) => {
  const keyList = ['birthday', 'bysj', 'cjgzsj', 'yshtqssj', 'htdqs', 'htqdsj', 'rgssj', 'zzsj']
  Object.keys(dataSource).forEach((key) => {
    if (keyList.includes(key) && Array.isArray(dataSource[key])) {
      const dateString = dataSource[key].join('-')
      const dateValue = moment(dateString).valueOf()
      dataSource[key] = dateValue
    }
  })
  return dataSource
}

/**编辑员工档案详情 */
const { mutate: addUserMutate } = useMutation({
  mutationFn: async (values: any) => {
    return await editRecordsDetail(values)
  },
  onSuccess() {
    ElMessage({
      message: '员工档案修改成功！',
      type: 'success'
    })
  },
  onError() {
    ElMessage({
      message: '员工档案修改失败，请稍后再试！',
      type: 'error'
    })
  }
})

/**生成工号 */
const { mutate: generateStaffNumber } = useMutation({
  mutationFn: async () => {
    return await generateStaffNum()
  },
  onSuccess(res) {
    formData.value['loginName'] = res
  },
  onError() {
    ElMessage({
      message: '工号生成失败！',
      type: 'error'
    })
  }
})

/**表单保存 */
const submitForm = (formEl: FormInstance | undefined) => {
  // console.log('formData.value', formData.value)
  // return
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      addUserMutate(formData.value)
    } else {
      return false
    }
  })
}

/**部门切换时 */
const deptOnChange = (id) => {
  formData.value['deptId'] = id
}

/**点击预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 99999999,
    urlList: [imgUrl]
  })
}

/**是否是编辑页面 */
const isEdit = computed(() => {
  return type === 'edit'
})

// 修改并保存工作经历
const saveWorkList = (data: any[]) => {
  // console.log('data', data)
  formData.value['workList'] = data
}
// 修改并保存家庭成员
const saveFamilyList = (data: any[]) => {
  // console.log('data', data)
  formData.value['familyList'] = data
}
// 修改并保存学习经历
const saveSchoolList = (data: any[]) => {
  // console.log('data', data)
  formData.value['schoolList'] = data
}
</script>
<template>
  <div class="staff-files-wrap">
    <div class="staff-name">
      <el-image
        class="staff-avator"
        :src="avatar"
        :zoom-rate="1.2"
        :max-scale="7"
        :min-scale="0.2"
        @click="imagePreview(avatar)"
        :initial-index="0"
      />
      <span>{{ formData?.['nickname'] }}员工档案</span>
    </div>

    <div
      v-if="formData && Object.keys(formData)?.length > 0"
      :class="isEdit ? 'my-portrait' : 'my-portrait form-unable-edit'"
    >
      <el-form ref="formRef" :model="formData" label-width="150px" :disabled="!isEdit">
        <div class="my-portrait-item" v-for="(item, index) in formConfigList" :key="index">
          <div class="title">
            <i></i>
            <span>{{ item.title }}</span>
          </div>
          <div class="my-portrait-card">
            <ul>
              <li v-for="(child, c) in item.children" :key="c">
                <el-form-item :label="`${child.title}:`" :prop="child.name">
                  <el-date-picker
                    v-if="child.type === 'time'"
                    v-model="formData[child?.name]"
                    style="width: 100%"
                    :placeholder="isEdit ? child.title : ''"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="x"
                  />

                  <DeptSelect
                    v-if="child.type === 'dept-select'"
                    v-model="formData['deptId']"
                    :defaultValue="formData['deptId'] ?? ''"
                  />

                  <el-select
                    v-if="child.type === 'select'"
                    v-model="formData[child?.name]"
                    style="width: 100%"
                    :placeholder="isEdit ? child.title : '-'"
                  >
                    <el-option
                      v-for="opt in child.options"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </el-select>

                  <el-input
                    v-if="child?.type === undefined"
                    v-model="formData[child?.name]"
                    placeholder=""
                  />
                  <div v-if="child?.type === 'button'" class="generate-num">
                    <el-input v-model="formData[child?.name]" placeholder="" :disabled="true" />
                    <ElButton
                      v-if="isEdit"
                      type="primary"
                      style="width: 70px; height: 30px; margin-left: 10px"
                      @click="generateStaffNumber()"
                      >生成工号</ElButton
                    >
                  </div>
                </el-form-item>
              </li>
              <li></li>
            </ul>
          </div>
        </div>

        <div class="my-portrait-item">
          <WorkTable :defaultData="formData['workList']" @onSave="saveWorkList" />
        </div>
        <div class="my-portrait-item">
          <FamilyTable :defaultData="formData['familyList']" @onSave="saveFamilyList" />
        </div>
        <div class="my-portrait-item">
          <SchoolTable :defaultData="formData['schoolList']" @onSave="saveSchoolList" />
        </div>
        <el-row justify="end">
          <el-form-item v-if="isEdit">
            <el-button color="#1B80EB" type="primary" @click="submitForm(formRef)">保存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.staff-files-wrap {
  height: calc(100% - 10px);
  padding: 26px 30px;
  margin: 40px 0 25px;
  overflow: hidden;
  background: #fff;
  border-radius: 20px;

  .staff-name {
    display: flex;
    justify-content: center;
    align-items: center;

    span {
      display: block;
      font-family: 'Microsoft YaHei';
      font-size: 32px;
      font-weight: bold;
      color: #000000;
      text-align: center;
    }

    .staff-avator {
      width: 36px;
      height: 36px;
      margin-right: 12px;
      cursor: pointer;
      border-radius: 50%;
    }
  }

  .my-portrait {
    width: 100%;
    height: calc(100% - 40px);
    padding: 0 0 10px;
    overflow: auto;

    .my-portrait-item {
      margin-bottom: 20px;
      width: 100%;
      .title {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        i {
          display: block;
          width: 16px;
          height: 16px;
          margin-right: 9px;
          background: url('../../../../assets/imgs/OA/mine/star.png') center no-repeat;
          background-size: 100%;
        }

        span {
          font-size: 18px;
          font-weight: bold;
          color: #000000;
        }
      }

      ul {
        display: flex;
        padding: 20px 40px 0;
        background: #f7f8fa;
        border-radius: 4px;
        flex-wrap: wrap;
        justify-content: space-between;

        li {
          width: calc(33.3% - 40px);
        }
      }
    }
  }

  .form-unable-edit {
    .my-portrait-item {
      ul {
        background: linear-gradient(90deg, #f2f7ff 0%, rgb(245 249 255 / 0%) 100%);
        border: 1px solid #e4e9f1;
      }
    }

    :deep(.el-form) {
      .el-input.is-disabled .el-input__wrapper {
        background-color: unset;
        box-shadow: none;
      }

      .el-input.is-disabled .el-input__inner {
        color: #000000;
        -webkit-text-fill-color: #000000;
      }

      .el-form-item__label {
        font-size: 16px;
        color: #455773;
      }

      .el-form-item--default {
        margin-bottom: 10px;
      }

      .el-input__inner {
        font-family: 'Microsoft YaHei';
        font-size: 16px;
        font-weight: 500;
        color: #000000;
      }

      .el-input__suffix {
        display: none;
      }
    }
  }
}

.generate-num {
  display: flex;
  width: 100%;
}
</style>
