<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 { FormInstance } from 'element-plus'
import moment from 'moment'
import TechCertificate from './TechCertificate.vue'
import avatarImg from '@/assets/imgs/avatar.jpg'
import DeptSelect from '@/components/DeptSelect/index.vue'
import UserOrgTree from '@/views/OaSystem/components/UserOrgTree/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
import WorkTable from './WorkTable.vue'
import FamilyTable from './familyTable.vue'
import SchoolTable from './SchoolTable.vue'
import PerformanceTable from './performanceTable.vue'

const formConfigList = getConfigDict()

const { query } = useRoute()
const { id, type } = query
const formRef = ref<FormInstance>()
const formData = ref({})
const tabNav = ref<string>('#gsxx')
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 treeNodeClick = (item, type) => {
  formData.value[type] = item['label']
  console.log(formData.value)
}
/**编辑员工档案详情 */
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) => {
  if (!formEl) return
  if (formData.value['schoolList'] && formData.value['schoolList'].length > 0) {
    formData.value.zgxl = formData.value['schoolList'][0]['xl']
  }

  formEl.validate((valid) => {
    if (valid) {
      formData.value['zzsj'] = formData.value['zzsj'] === null ? '' : formData.value['zzsj']
      addUserMutate(formData.value)
    } else {
      return false
    }
  })
}

/**点击预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 99999999,
    urlList: [imgUrl]
  })
}
//模拟锚点跳转
const goAnchor = (selector) => {
  tabNav.value = selector
  //参数selector是id选择器（#anchor14）
  document.querySelector(selector).scrollIntoView({
    behavior: 'smooth'
  })
}
/**是否是编辑页面 */
const isEdit = computed(() => {
  return type === 'edit'
})

// 上传路径
const updateUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + import.meta.env.VITE_UPLOAD_URL

// 回填正确路径
const imageUrl = (url) => {
  if (!url) return []
  return url.split(',').map((item, index) => ({
    url: item,
    uid: index
  }))
}
const getImgUrlList = (url) => {
  if (!url) return []
  return url.split(',')
}
// 附件上传成功
const onUploadSuccess = (file: any, type: string) => {
  const fileList = file.map((item) => item.url)
  formData.value[type] = fileList.join(',')
}
// 修改并保存工作经历
const saveWorkList = (data: any[]) => {
  // console.log('data', data)
  formData.value['workList'] = data.map((item) => ({ ...item, userId: id }))
}
// 修改并保存家庭成员
const saveFamilyList = (data: any[]) => {
  // console.log('data', data)
  formData.value['familyList'] = data.map((item) => ({ ...item, userId: id }))
}
// 修改并保存学习经历
const saveSchoolList = (data: any[]) => {
  // console.log('data', data)
  formData.value['schoolList'] = data.map((item) => ({ ...item, userId: id }))
}
// 修改并保存绩效考核记录
const savePerformanceList = (data: any[]) => {
  // console.log('data', data)
  formData.value['performanceList'] = data.map((item) => ({ ...item, userId: id }))
}
//修改病保存职称证书
const saveTechCertificateList = (data: any[]) => {
  formData.value['certList'] = data.map((item) => ({ ...item, userId: id }))
}
</script>
<template>
  <div class="staff-files-wrap">
    <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-header">
          <div class="user-card">
            <el-image
              class="staff-avator"
              :src="avatar"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              @click="imagePreview(avatar)"
              :initial-index="0"
            />
          </div>
          <div class="my-portrait-card">
            <div class="btn_box">
              <el-form-item v-if="isEdit">
                <el-button color="#1B80EB" type="primary" @click="submitForm(formRef)"
                  >保存</el-button
                >
              </el-form-item>
            </div>
            <div class="user-base-info">
              <h4>{{ formData?.['nickname'] }}</h4>
              <span>{{ formData?.['deptName'] }}</span>
            </div>
            <ul>
              <li v-for="(child, c) in formConfigList[0].children" :key="c">
                <el-form-item :label="`${child.title}:`" :prop="child.name" label-width="110px">
                  <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]"
                    :title="child?.tip ? 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>
            </ul>
          </div>
        </div>
        <div class="my-portrait-wrap">
          <ul class="my-portrait-nav">
            <li @click="goAnchor('#gsxx')" :class="{ active: tabNav === '#gsxx' }">公司信息</li>
            <li @click="goAnchor('#gzkxx')" :class="{ active: tabNav === '#gzkxx' }">工资卡信息</li>
            <li @click="goAnchor('#sfzxx')" :class="{ active: tabNav === '#sfzxx' }">
              身份证信息
            </li>
            <li @click="goAnchor('#jjlxrxx')" :class="{ active: tabNav === '#jjlxrxx' }">
              紧急联系人信息
            </li>
            <li @click="goAnchor('#gzjl')" :class="{ active: tabNav === '#gzjl' }">工作经历</li>
            <li @click="goAnchor('#jtcy')" :class="{ active: tabNav === '#jtcy' }">家庭成员</li>
            <li @click="goAnchor('#xxjl')" :class="{ active: tabNav === '#xxjl' }">学习经历</li>
            <li @click="goAnchor('#jxkh')" :class="{ active: tabNav === '#jxkh' }">绩效考核</li>
            <li @click="goAnchor('#zczs')" :class="{ active: tabNav === '#zczs' }">职称证书</li>
          </ul>
          <div class="my-portrait-container">
            <div class="my-portrait-item" id="gsxx">
              <div class="title">
                <i></i>
                <span>公司信息</span>
              </div>
              <div class="my-portrait-card">
                <ul>
                  <li v-for="(child, c) in formConfigList[1].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"
                      />

                      <UserOrgTree
                        v-if="child.type === 'user-select'"
                        v-model="formData[child?.name]"
                        @node-click="(item) => treeNodeClick(item, child?.sname)"
                      />
                      <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=""
                      >
                        <template v-if="child?.append" #append>{{ child?.append }}</template>
                      </el-input>
                      <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" id="gzkxx">
              <div class="title">
                <i></i>
                <span>工资卡信息</span>
              </div>
              <div class="my-portrait-card">
                <ul>
                  <li v-for="(child, c) in formConfigList[2].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" id="sfzxx">
              <div class="title">
                <i></i>
                <span>身份证信息</span>
              </div>
              <div class="my-portrait-card">
                <ul>
                  <li v-for="(child, c) in formConfigList[3].children" :key="c">
                    <el-form-item :label="`${child.title}:`" :prop="child.name">
                      <template v-if="child.type === 'time'">
                        <el-date-picker
                          v-model="formData[child?.name]"
                          style="width: 100%"
                          :placeholder="isEdit ? child.title : ''"
                          type="date"
                          format="YYYY-MM-DD"
                          value-format="x"
                        />
                      </template>
                      <template v-else-if="child?.type === 'upload'">
                        <UploadImgs
                          v-if="isEdit"
                          :modelValue="imageUrl(formData[child?.name])"
                          :updateUrl="updateUrl"
                          height="55px"
                          :callback="(file) => onUploadSuccess(file, child?.name)"
                        />
                        <div v-else>
                          <span
                            style="margin-left: 3px"
                            v-for="(item, index) in getImgUrlList(formData[child?.name])"
                            :key="index"
                          >
                            <el-image
                              style="width: 100px; height: 100px"
                              :src="item"
                              fit="scale-down"
                              :preview-src-list="[item]"
                            />
                          </span>
                        </div>
                      </template>
                      <el-input
                        v-if="child?.type === undefined"
                        v-model="formData[child?.name]"
                        placeholder=""
                      />
                    </el-form-item>
                  </li>
                  <li></li>
                </ul>
              </div>
            </div>
            <div class="my-portrait-item" id="jjlxrxx">
              <div class="title">
                <i></i>
                <span>紧急联系人信息</span>
              </div>
              <div class="my-portrait-card">
                <ul>
                  <li v-for="(child, c) in formConfigList[4].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=""
                      />
                    </el-form-item>
                  </li>
                  <li></li>
                </ul>
              </div>
            </div>

            <div class="my-portrait-item" id="gzjl">
              <WorkTable
                :defaultData="formData['workList']"
                @onSave="saveWorkList"
                :onlyRead="type == 'view'"
              />
            </div>
            <div class="my-portrait-item" id="jtcy">
              <FamilyTable
                :defaultData="formData['familyList']"
                @onSave="saveFamilyList"
                :onlyRead="type == 'view'"
              />
            </div>
            <div class="my-portrait-item" id="xxjl">
              <SchoolTable
                :defaultData="formData['schoolList']"
                @onSave="saveSchoolList"
                :onlyRead="type == 'view'"
              />
            </div>
            <div class="my-portrait-item" id="jxkh">
              <PerformanceTable
                :defaultData="formData['performanceList']"
                @onSave="savePerformanceList"
                :onlyRead="type == 'view'"
              />
            </div>
            <div class="my-portrait-item" id="zczs">
              <TechCertificate
                :defaultData="formData['certList']"
                @onSave="saveTechCertificateList"
                :onlyRead="type == 'view'"
              />
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.staff-files-wrap {
  height: 100%;

  .my-portrait {
    width: 100%;
    height: 100%;
    padding: 0 0 10px;
    overflow: hidden;
    :deep(.el-form) {
      display: flex;
      flex-direction: column;
      height: 100% !important;
    }
    .my-portrait-header {
      background: #fff;
      padding: 26px 30px;
      padding-bottom: 0px;
      overflow: hidden;
      border-radius: 20px;
      display: flex;
      align-content: center;
      margin-bottom: 15px;
      > .user-card {
        width: 160px;
        margin-right: 10px;
      }
      > .my-portrait-card {
        flex: 1;
        position: relative;
        > .btn_box {
          position: absolute;
          right: 0px;
        }
        > .user-base-info {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          margin-left: 20px;
          > h4 {
            font-size: 22px;
            color: #111518;
            margin-right: 10px;
          }
          > span {
            color: #777c80;
          }
        }
        > ul {
          > li {
            display: inline-block;
            width: calc(20% - 30px);
            text-align: left;
            &:not(:nth-child(5n + 5)) {
              margin-right: 30px;
            }
          }
        }
      }
    }
    .my-portrait-wrap {
      background: #fff;
      padding: 26px 30px;
      padding-top: 0px;
      border-radius: 20px;
      overflow-y: auto;
      flex: 1;
      flex-grow: 1;
      display: flex;
      flex-direction: column;
      > .my-portrait-nav {
        display: flex;
        border-bottom: 1px solid #e5eff7;
        margin: 0px -30px;
        margin-bottom: 15px;
        padding: 0px 20px;
        > li {
          padding: 15px;
          cursor: pointer;
          font-size: 17px;
          position: relative;
          &.active {
            color: #2e77e6;
            &::after {
              display: block;
              content: '';
              width: 20px;
              height: 3px;
              background: #2e77e6;
              position: absolute;
              bottom: 0px;
              left: 0px;
              right: 0px;
              margin: auto;
            }
          }
        }
      }
      > .my-portrait-container {
        overflow-y: auto;
        flex: 1;
        flex-grow: 1;
        > .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-group__append {
        border: 0px;
        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%;
}
.staff-avator {
  width: 100%;
  max-height: 180px;
}
</style>
