<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="user" :labelWidth="'80px'" style="margin-bottom: 80px;">

        <!-- 基本身份信息 -->
        <uni-collapse class="collapse" :accordion="false" :value="['basicInfo']">
          <uni-collapse-item class="collapse-item" title="基本身份信息" name="basicInfo" :show-animation="true">
            <uni-forms-item label="用户昵称" name="nickName" required>
              <uni-easyinput v-model="user.nickName" placeholder="请输入昵称" />
            </uni-forms-item>
            <uni-forms-item label="归属部门" name="deptId" required>
              <uni-data-picker v-model="user.deptId" :localdata="deptOptions" popup-title="请选择归属部门" />
            </uni-forms-item>
            <uni-forms-item label="手机号码" name="phonenumber">
              <uni-easyinput v-model="user.phonenumber" placeholder="请输入手机号码" />
            </uni-forms-item>
            <uni-forms-item label="邮箱" name="email">
              <uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
            </uni-forms-item>
            <uni-forms-item label="身份证号" name="cardNumber">
              <uni-easyinput v-model="user.cardNumber" placeholder="请输入身份证号" />
            </uni-forms-item>
            <uni-forms-item label="用户性别" name="sex" required>
              <uni-data-picker v-model="user.sex" :localdata="sys_user_sex" popup-title="请选择性别" />
            </uni-forms-item>
            <uni-forms-item label="生肖" name="zodiac">
              <uni-data-picker v-model="user.zodiac" :localdata="sys_user_zodiac" popup-title="请选择生肖" />
            </uni-forms-item>
            <uni-forms-item label="星座" name="constellation">
              <uni-data-picker v-model="user.constellation" :localdata="sys_user_constellation" popup-title="请选择星座" />
            </uni-forms-item>
            <uni-forms-item label="血型" name="blooGroup">
              <uni-data-picker v-model="user.blooGroup" :localdata="sys_user_blood_group" popup-title="请选择血型" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 状态管理信息 -->
        <uni-collapse class="collapse" :accordion="false" :value="['status']">
          <uni-collapse-item class="collapse-item" title="状态管理信息" name="status" :show-animation="true">

            <uni-forms-item label="培训合规状态" name="trainingComplianceStatus">
              <uni-data-checkbox v-model="user.trainingComplianceStatus" :localdata="yesNoOptions" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 资质能力信息 -->
        <uni-collapse class="collapse" :accordion="false" :value="['qualification']">
          <uni-collapse-item class="collapse-item" title="资质能力信息" name="qualification" :show-animation="true">
            <uni-forms-item label="资质等级" name="qualificationLevel" :required="isSecurityRole">
              <uni-data-picker v-model="user.qualificationLevel" :localdata="sys_user_qualification_level"
                popup-title="请选择资质等级" @change="handleQualificationLevelChange" />
            </uni-forms-item>
            <uni-forms-item label="岗位类型" name="postIds" :required="isSecurityRole">
              <zxz-uni-data-select v-model="user.postIds" :localdata="postTreeData" multiple placeholder="请选择岗位类型" />
            </uni-forms-item>
            <uni-forms-item label="是否通过政审" name="politicalReviewSituation">
              <uni-data-checkbox v-model="user.politicalReviewSituation" :localdata="yesNoOptions" />
            </uni-forms-item>
            <uni-forms-item label="政治面貌" name="politicalStatus">
              <uni-data-picker v-model="user.politicalStatus" :localdata="sys_user_political_status"
                popup-title="请选择政治面貌" />
            </uni-forms-item>
            <uni-forms-item label="学历" name="schooling">
              <uni-data-picker v-model="user.schooling" :localdata="sys_user_schooling" popup-title="请选择学历" />
            </uni-forms-item>
            <uni-forms-item label="行政处罚情况" name="administrativeStatus">
              <uni-easyinput v-model="user.administrativeStatus" type="textarea" placeholder="请输入行政处罚情况" />
            </uni-forms-item>
            <uni-forms-item label="健康异常情况" name="physicalHealthStatus">
              <uni-easyinput v-model="user.physicalHealthStatus" type="textarea" placeholder="请输入健康异常情况" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 工作履历/经验 -->
        <uni-collapse class="collapse" :accordion="false" :value="['experience']">
          <uni-collapse-item class="collapse-item" title="工作履历/经验" name="experience" :show-animation="true">
            <uni-forms-item label="开始工作时间" name="startWorkingDate">
              <uni-datetime-picker v-model="user.startWorkingDate" type="date" placeholder="请选择开始工作时间" />
            </uni-forms-item>
            <uni-forms-item label="开始安检工作时间" name="securityCheckStartDate">
              <uni-datetime-picker v-model="user.securityCheckStartDate" type="date" placeholder="请选择开始安检工作时间" />
            </uni-forms-item>
            <uni-forms-item label="曾在安检工作中担任的最高职务" name="securityInspectionPosition">
              <uni-data-picker v-model="user.securityInspectionPosition" :localdata="securityPositionOptions"
                popup-title="请选择最高职务" />
            </uni-forms-item>
            <uni-forms-item label="接受奖励次数" name="workRewardsNumber">
              <uni-easyinput v-model="user.workRewardsNumber" type="number" placeholder="请输入接受奖励次数" />
            </uni-forms-item>
            <uni-forms-item label="接受处罚次数" name="workPenaltiesNumber">
              <uni-easyinput v-model="user.workPenaltiesNumber" type="number" placeholder="请输入接受处罚次数" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 评价类指标 -->
        <uni-collapse class="collapse" :accordion="false" :value="['evaluation']">
          <uni-collapse-item class="collapse-item" title="评价类指标" name="evaluation" :show-animation="true">
            <uni-forms-item label="性格特征" name="characterCharacteristics">
              <uni-data-picker v-model="user.characterCharacteristics" :localdata="sys_user_character_characteristics"
                popup-title="请选择性格特征" />
            </uni-forms-item>
            <uni-forms-item label="工作风格" name="workingStyle">
              <uni-data-picker v-model="user.workingStyle" :localdata="sys_user_working_style" popup-title="请选择工作风格" />
            </uni-forms-item>
            <uni-forms-item label="团队配合人员" name="teamCooperation">
              <zxz-uni-data-select v-model="user.teamCooperation" :localdata="teamCooperationOptions" multiple
                placeholder="请选择团队配合人员" />
            </uni-forms-item>
            <uni-forms-item label="自我关键词评价" name="selfKeywords">
              <view class="evaluation-column">
                <uni-data-picker v-model="user.selfAssessmentPersonalityTrait" :localdata="sys_user_personality_trait"
                  popup-title="请选择性格特质" style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.selfAssessmentCapabilityPerformance"
                  :localdata="sys_user_capability_performance" popup-title="请选择能力表现"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.selfAssessmentInterpersonalInteraction"
                  :localdata="sys_user_interpersonal_interaction" popup-title="请选择人际互动"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.selfAssessmentGrowthPotential" :localdata="sys_user_growth_potential"
                  popup-title="请选择成长潜力" style="width: 100%;" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="同事关键词评价" name="colleagueKeywords">
              <view class="evaluation-column">
                <uni-data-picker v-model="user.colleagueCommentsPersonalityTrait"
                  :localdata="sys_user_personality_trait" popup-title="请选择性格特质"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.colleagueCommentsCapabilityPerformance"
                  :localdata="sys_user_capability_performance" popup-title="请选择能力表现"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.colleagueCommentsInterpersonalInteraction"
                  :localdata="sys_user_interpersonal_interaction" popup-title="请选择人际互动"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.colleagueCommentsGrowthPotential" :localdata="sys_user_growth_potential"
                  popup-title="请选择成长潜力" style="width: 100%;" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="上级关键词评价" name="superiorKeywords">
              <view class="evaluation-column">
                <uni-data-picker v-model="user.superiorEvaluationPersonalityTrait"
                  :localdata="sys_user_personality_trait" popup-title="请选择性格特质"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.superiorEvaluationCapabilityPerformance"
                  :localdata="sys_user_capability_performance" popup-title="请选择能力表现"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.superiorEvaluationInterpersonalInteraction"
                  :localdata="sys_user_interpersonal_interaction" popup-title="请选择人际互动"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.superiorEvaluationGrowthPotential" :localdata="sys_user_growth_potential"
                  popup-title="请选择成长潜力" style="width: 100%;" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="下级关键词评价" name="subordinateKeywords">
              <view class="evaluation-column">
                <uni-data-picker v-model="user.subordinateEvaluationPersonalityTrait"
                  :localdata="sys_user_personality_trait" popup-title="请选择性格特质"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.subordinateEvaluationCapabilityPerformance"
                  :localdata="sys_user_capability_performance" popup-title="请选择能力表现"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.subordinateEvaluationInterpersonalInteraction"
                  :localdata="sys_user_interpersonal_interaction" popup-title="请选择人际互动"
                  style="width: 100%; margin-bottom: 10px;" />
                <uni-data-picker v-model="user.subordinateEvaluationGrowthPotential"
                  :localdata="sys_user_growth_potential" popup-title="请选择成长潜力" style="width: 100%;" />
              </view>
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 应急联络信息 -->
        <uni-collapse class="collapse" :accordion="false" :value="['emergency']">
          <uni-collapse-item class="collapse-item" title="应急联络信息" name="emergency" :show-animation="true">
            <uni-forms-item label="紧急联系人姓名" name="emergencyContactName">
              <uni-easyinput v-model="user.emergencyContactName" placeholder="请输入紧急联系人姓名" />
            </uni-forms-item>
            <uni-forms-item label="紧急联系人电话" name="emergencyContactPhone">
              <uni-easyinput v-model="user.emergencyContactPhone" placeholder="请输入紧急联系人电话" />
            </uni-forms-item>
            <uni-forms-item label="紧急联系人关系" name="emergencyContactRelationship">
              <uni-data-picker v-model="user.emergencyContactRelationship"
                :localdata="sys_user_emergency_contact_relationship" popup-title="请选择紧急联系人关系" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

        <!-- 其他信息 -->
        <uni-collapse class="collapse" :accordion="false" :value="['other']">
          <uni-collapse-item class="collapse-item" title="其他信息" name="other" :show-animation="true">
            <uni-forms-item label="备注" name="remark">
              <uni-easyinput v-model="user.remark" type="textarea" placeholder="请输入备注" />
            </uni-forms-item>
          </uni-collapse-item>
        </uni-collapse>

      </uni-forms>
    </view>

    <!-- 固定在底部的提交按钮 -->
    <view class="submit-button">
      <button type="primary" @click="submit" style="margin-top: 0;width: 100%;">提交</button>
    </view>
  </view>
</template>

<script>

import { updateUser, listAllUser, getPostAllList, getUserInfoById } from "@/api/system/user"
import { getDeptList } from "@/api/system/dept/dept"
import storage from "@/utils/storage"
import constant from "@/utils/constant"
import useDictMixin from "@/utils/dict"

export default {
  mixins: [useDictMixin],
  data() {
    return {
      user: {
        // 基本身份信息
        nickName: "",
        deptId: "",
        phonenumber: "",
        email: "",
        cardNumber: "",
        sex: "",
        zodiac: "",
        constellation: "",
        blooGroup: "",

        // 状态管理信息
        trainingComplianceStatus: "",

        // 资质能力信息
        qualificationLevel: "",
        postIds: [],
        politicalReviewSituation: "",
        politicalStatus: "",
        schooling: "",
        administrativeStatus: "",
        physicalHealthStatus: "",

        // 工作履历/经验
        startWorkingDate: "",
        securityCheckStartDate: "",
        securityInspectionPosition: "",
        workRewardsNumber: "",
        workPenaltiesNumber: "",

        // 评价类指标
        characterCharacteristics: "",
        workingStyle: "",
        teamCooperation: [],
        selfAssessmentPersonalityTrait: "",
        selfAssessmentCapabilityPerformance: "",
        selfAssessmentInterpersonalInteraction: "",
        selfAssessmentGrowthPotential: "",
        colleagueCommentsPersonalityTrait: "",
        colleagueCommentsCapabilityPerformance: "",
        colleagueCommentsInterpersonalInteraction: "",
        colleagueCommentsGrowthPotential: "",
        superiorEvaluationPersonalityTrait: "",
        superiorEvaluationCapabilityPerformance: "",
        superiorEvaluationInterpersonalInteraction: "",
        superiorEvaluationGrowthPotential: "",
        subordinateEvaluationPersonalityTrait: "",
        subordinateEvaluationCapabilityPerformance: "",
        subordinateEvaluationInterpersonalInteraction: "",
        subordinateEvaluationGrowthPotential: "",

        // 应急联络信息
        emergencyContactName: "",
        emergencyContactPhone: "",
        emergencyContactRelationship: "",

        // 其他信息
        remark: ""
      },

      // 性别选项
      sys_user_sex: [],

      // 生肖选项
      sys_user_zodiac: [],

      // 星座选项
      sys_user_constellation: [],

      // 血型选项
      sys_user_blood_group: [],

      // 资质等级选项
      sys_user_qualification_level: [],

      // 岗位类型选项
      sys_user_post_type: [],

      // 是否通过政审选项
      yesNoOptions: [
        { text: '是', value: '1' },
        { text: '否', value: '0' }
      ],

      // 政治面貌选项
      sys_user_political_status: [],

      // 学历选项
      sys_user_schooling: [],

      // 安检最高职务选项
      sys_user_security_position: [],

      // 安检最高职务选项（写死）
      securityPositionOptions: [
        { text: '安检员', value: '安检员' },
        { text: '班组长', value: '班组长' }
      ],

      // 性格特征选项
      sys_user_character_characteristics: [],

      // 工作风格选项
      sys_user_working_style: [],

      // 团队配合人员选项
      sys_user_team_cooperation: [],

      // 性格特质选项
      sys_user_personality_trait: [],

      // 能力表现选项
      sys_user_capability_performance: [],

      // 人际互动选项
      sys_user_interpersonal_interaction: [],

      // 成长潜力选项
      sys_user_growth_potential: [],

      // 紧急联系人关系选项
      sys_user_emergency_contact_relationship: [],

      // 团队配合人员选项
      teamCooperationOptions: [],

      // 岗位类型树状数据
      postTreeData: [],

      // 部门选项数据
      deptOptions: [],

    }
  },
  onLoad() {
    this.loadDictData()
    this.getUser()
    this.loadTeamCooperationData()
    this.loadPostTreeData()
    this.loadDeptData()
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  computed: {
    rules() {
      return {
        nickName: {
          rules: [{
            required: true,
            errorMessage: '用户昵称不能为空'
          }]
        },
        deptId: {
          rules: [{
            required: true,
            errorMessage: '归属部门不能为空'
          }]
        },
        qualificationLevel: {
          rules: [{
            required: this.isSecurityRole,
            errorMessage: '资质等级不能为空'
          }]
        },
        postIds: {
          rules: [{
            required: this.isSecurityRole,
            errorMessage: '岗位类型不能为空'
          }]
        },
        phonenumber: {
          rules: [{
            required: true,
            errorMessage: '手机号码不能为空'
          }, {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            errorMessage: '请输入正确的手机号码'
          }]
        },
        email: {
          rules: [{
            required: true,
            errorMessage: '邮箱地址不能为空'
          }, {
            format: 'email',
            errorMessage: '请输入正确的邮箱地址'
          }]
        }
      }
    },
    // 判断当前用户是否是安检员或班组长角色
    isSecurityRole() {
      // 安检员和班组长的角色ID通常是固定的，这里假设安检员角色ID为101，班组长角色ID为102
      // 您可以根据实际情况调整这些ID
      const securityRoleIds = ['banzuzhang', 'SecurityCheck'] // 安检员和班组长的角色ID

      // 检查当前用户的角色ID是否包含安检员或班组长的角色ID
      console.log((this.user?.roles && this.user?.roles.length > 0) && this.user.roles.some(role => securityRoleIds.includes(role.roleKey)), "this.user.roleIds.some(role => securityRoleIds.includes(role.roleKey))")
      return (this.user?.roles && this.user?.roles.length > 0) && this.user?.roles.some(role => securityRoleIds.includes(role.roleKey))

    }
  },
  methods: {
    async loadDictData() {
      try {
        const dicts = await this.useDict(
          'sys_user_sex',
          'sys_user_zodiac',
          'sys_user_constellation',
          'sys_user_blood_group',
          'sys_user_qualification_level',
          'sys_user_post_type',
          'sys_user_political_status',
          'sys_user_schooling',
          'sys_user_security_position',
          'sys_user_character_characteristics',
          'sys_user_working_style',
          'sys_user_team_cooperation',
          'sys_user_personality_trait',
          'sys_user_capability_performance',
          'sys_user_interpersonal_interaction',
          'sys_user_growth_potential',
          'sys_user_emergency_contact_relationship'
        )

        // 将获取到的字典数据转换为uni-data-picker需要的格式
        Object.keys(dicts).forEach(key => {
          // console.log(dicts[key])
          // 将dictLabel/dictValue格式转换为label/value格式
          this[key] = dicts[key].map(item => ({
            text: item.label,
            value: item.value
          }))
        })
      } catch (error) {
        console.error('加载字典数据失败:', error)
      }
    },

    // 加载团队配合人员数据
    async loadTeamCooperationData() {
      try {
        const res = await listAllUser()
        if (res && res.data) {
          this.teamCooperationOptions = res.data.map(item => ({
            text: `${item.nickName}(${item.userName})`,
            value: item.userId
          }))
        }
      } catch (error) {
        console.error('加载团队配合人员数据失败:', error)
      }
    },

    // 加载岗位类型树状数据
    async loadPostTreeData() {
      try {
        const res = await getPostAllList()

        if (res && res.data) {
          // 保存原始树状数据
          this.postTreeDataAll = JSON.parse(JSON.stringify(res.data))

          // 将树状数据扁平化，显示为"父级岗位名称 - 子级岗位名称"格式
          const flattenTreeWithParent = (nodes, parentName = '') => {
            let result = []
            nodes.forEach(node => {
              // 如果有子节点，只处理子节点
              if (node.children && node.children.length > 0) {
                result = result.concat(flattenTreeWithParent(node.children, node.postName))
              } else {
                // 如果没有子节点，显示当前节点（带父级名称）
                const displayText = parentName ? `${parentName}/${node.postName}` : node.postName
                result.push({
                  text: displayText,
                  value: node.postId
                })
              }
            })
            return result
          }

          this.postTreeData = flattenTreeWithParent(res.data)
        }
      } catch (error) {
        console.error('加载岗位类型树状数据失败:', error)
      }
    },

    // 资质等级变化处理
    handleQualificationLevelChange(e) {
      console.log('资质等级变化', e)
      // 清空岗位类型选择
      this.user.postIds = []

      // 如果资质等级为五级，需要重新生成过滤后的扁平化数据
      const flattenTreeWithParent = (nodes, parentName = '') => {
        let result = []
        nodes.forEach(node => {
          if (node.children && node.children.length > 0) {
            result = result.concat(flattenTreeWithParent(node.children, node.postName))
          } else {
            const displayText = parentName ? `${parentName}/${node.postName}` : node.postName
            result.push({
              text: displayText,
              value: node.postId
            })
          }
        })
        return result
      }

      if (e?.detail?.value[0]?.value === 'LEVEL_FIVE') {
        this.postTreeData = flattenTreeWithParent(this.postTreeDataAll).filter(item => item.value !== 9 && item.value !== 10)
      } else {
        this.postTreeData = flattenTreeWithParent(this.postTreeDataAll)
      }


    },

    // 递归过滤树形数据
    filterPostTree(data) {
      return data.filter(item => {
        // 过滤掉postId为9或10的选项
        if (item.postId == 9 || item.postId == 10) {
          return false
        }

        // 如果有子节点，递归过滤
        if (item.children && item.children.length > 0) {
          item.children = this.filterPostTree(item.children)
        }

        return true
      })
    },

    // 加载部门数据
    async loadDeptData() {
      try {
        const res = await getDeptList()
        if (res && res.data) {
          // 直接使用树状数据，转换为uni-data-picker需要的格式
          const transformDeptTree = (nodes) => {
            return nodes.map(node => ({
              text: node.label,
              value: node.id,
              children: node.children ? transformDeptTree(node.children) : []
            }))
          }
          this.deptOptions = transformDeptTree(res.data)
        }
      } catch (error) {
        console.error('加载部门数据失败:', error)
      }
    },
    getUser() {
      // 获取当前登录用户的ID
      const currentUserId = storage.get(constant.id)
      if (currentUserId) {
        getUserInfoById(currentUserId).then(response => {
          let res = { ...response.data }
          res.teamCooperation = res.teamCooperation ? res.teamCooperation.split(",") : []
          res.postIds = response.postIds || []
          res.roleIds = response.roleIds || []
          this.user = res
        })
      } else {
        console.error('未找到当前登录用户ID')
      }
    },
    submit(ref) {
      // 重新设置验证规则，确保角色变化后规则能更新
      this.$refs.form.setRules(this.rules)
      
      this.$refs.form.validate().then(res => {
        // 准备提交数据，将数组字段转换为字符串
        const submitData = {
          ...this.user,
          teamCooperation: this.user.teamCooperation ? this.user.teamCooperation.join(',') : ''
        }

        updateUser(submitData).then(response => {
          this.$modal.msgSuccess("修改成功")
          // 提交成功后返回上一个页面
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        })
      }).catch(err => {
        // 验证失败时显示错误提示
        console.error('表单验证失败:', err)
        this.$modal.msgError('请检查表单填写是否正确')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
  padding-bottom: 80px;
  /* 为底部按钮预留空间 */
}

.example {
  padding: 15px;

  background-color: #fff;
}

.submit-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #fff;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.collapse {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.collapse-item {
  background-color: #fff;
  padding: 10px;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}

button[type="primary"] {
  margin-top: 20px;
  background-color: #409EFF;
}

.evaluation-row {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
}

.evaluation-column {
  display: flex;
  flex-direction: column;
  width: 100%;
}
</style>
