<script setup>
import { Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  base_list,
  family_add,
  family_del,
  family_edit,
  family_list,
  grade_class,
  honor_add,
  honor_del,
  honor_list,
  user_detail,
  user_edit,
} from './api'
import { dealFigureToChinese } from '~/utils/common-util'
const props = defineProps({
  data: {
    type: Array,
    default: [],
  },
  userId: {
    type: String,
    default: '',
  },

  schoolData: [],
})

const emit = defineEmits(['close'])
const ruleForm = ref({
  // ue_jgbh: '',
  // ue_user_cardno: '',
  // ue_zym: '',
  // ue_user_birthday: '',
  // ue_mzmc: '',
  // ue_user_gender: '',
  // ue_zzmmmc: '',
  // ue_whcdbh: '',
  // ue_szzbbh: '',
  // ue_rdsj: '',
  // ue_szdxzbh: '',
  // ue_yynlbh: '',
  // jtzz: '',
  // xxdz: '',
  // ue_xlbj: '',
  // ue_tc: '是',
})
const ruleFormRef = ref(null)
const formData = ref(props.data)
const rules = reactive({})

const validateTel = (rule, value, callback) => {
  const reg_ph = /^(((\d{3,4}-)?[0-9]{7,8})|(1(3|4|5|6|7|8|9)\d{9}))$/
  if (value && !reg_ph.test(value))
    callback(new Error('请输入正确的电话号码'))
  else callback()
}

initRules()
function initRules() {
  formData.value.map((item) => {
    if (item.key == 'jtzycy') {
      const data = JSON.parse(JSON.stringify(item.children))
      data.map((val) => {
        val.value = ''
      })
      console.log(data, 123)
      item.childrenData = [
        {
          uf_id: '',
          data: [...data],
        },
      ]
      console.log(data, 345)
    }

    if (!item.children)
      return

    item.children.map((val) => {
      if (val.required) {
        const obj = {
          required: true,
          message:
            val.type && val.type != 'textarea'
              ? `请选择${val.name}`
              : `请输入${val.name}`,
          trigger: val.type && val.type != 'textarea' ? 'change' : 'blur',
        }
        rules[val.key] = [obj]
      }

      if (val.type == 'email') {
        const obj = {
          type: 'email',
          message: '请输入正确的电子邮箱',
          trigger: ['blur', 'change'],
        }
        rules[val.key] = [obj]
      }
      else if (val.type == 'tel') {
        const obj = {
          validator: validateTel,
          message: '请输入正确的电话号码',
          trigger: ['blur', 'change'],
        }
        rules[val.key] = [obj]
      }
    })
  })
}

const selectObj = ref({
  ue_user_gender: [
    {
      name: '男',
      value: '1',
    },
    {
      name: '女',
      value: '2',
    },
  ],
  sfhj: [
    {
      name: '是',
      value: '1',
    },
    {
      name: '否',
      value: '2',
    },
  ],
  sm_id: props.schoolData,
  grade: [],
  cm_id: [],
})

const handleAddCy = (value) => {
  console.log(value, 22)
  const data = JSON.parse(JSON.stringify(value.children))
  data.map((val) => {
    val.value = ''
  })
  value.childrenData.push({
    uf_id: '',
    data,
  })
}

const handleRemoveCy = async (data, i) => {
  await family_del({ uf_id: data[i].uf_id })

  data.splice(i, 1)
}
const rymcData = ref([])
const rymcValue = ref('')
const handleAddRymc = async () => {
  const obj = {
    user_honor: {
      uh_rymc: rymcValue.value,
      uh_user_id: props.userId,
    },
  }
  await honor_add(obj)

  rymcData.value.unshift({ uh_rymc: rymcValue.value })

  rymcValue.value = ''
}

const handleRemoveRymc = async (i) => {
  await honor_del({ uh_id: rymcData.value[i].uh_id })
  rymcData.value.splice(i, 1)
}
const detailInfo = ref({})
const userInfo = ref({})

detailData()
async function detailData() {
  const data = { user_id: props.userId }
  const res = await user_detail({ user_id: props.userId })
  if (res.code == 1) {
    detailInfo.value = res.data
    console.log()
    ruleForm.value = {
      ue_user_realname: detailInfo.value.user_realname, // 姓名
      ue_xh: detailInfo.value.user_ext.ue_xh, // 职工编号
      ue_jgmc: detailInfo.value.user_ext.ue_jgmc, // 籍贯
      ue_user_cardno: detailInfo.value.user_ext.ue_user_cardno, // 身份证号码
      ue_cym: detailInfo.value.user_ext.ue_cym, // 曾用名
      ue_user_birthday: detailInfo.value.user_ext.ue_user_birthday, // 出生日期
      ue_mzmc: detailInfo.value.user_ext.ue_mzmc, // 民族
      ue_user_gender: detailInfo.value.user_ext.ue_user_gender, // 性别
      // ue_user_gender: detailInfo.value.user_ext.ue_user_gender == 1 ? '男' : (detailInfo.value.user_ext.ue_user_gender == 2 ? '女' : '保密'), // 性别
      ue_zzmmmc: detailInfo.value.user_ext.ue_zzmmmc, // 政治面貌
      ue_whcdmc: detailInfo.value.user_ext.ue_whcdmc, // 文化程度
      ue_szzbmc: detailInfo.value.user_ext.ue_szzbmc, // 所在支部
      ue_rdsj: detailInfo.value.user_ext.ue_rdsj, // 入党时间
      ue_bzlxmc: detailInfo.value.user_ext.ue_bzlxmc, // 编制类型
      ue_szdxzmc: detailInfo.value.user_ext.ue_szdxzmc, // 所在党小组
      ue_yynlmc: detailInfo.value.user_ext.ue_yynlmc, // 语言能力
      sm_id: detailInfo.value.user_ext.ue_sm_id, // 学校
      grade: detailInfo.value.user_ext.grade_id, // 年级
      cm_id: detailInfo.value.user_ext.jc_id, // 班级
      sm_name: detailInfo.value.user_ext.ue_xxmc,
      gradename: detailInfo.value.user_ext.grade_name, // 年级
      cm_name: detailInfo.value.user_ext.jc_name, // 班级
      ue_jtzz: detailInfo.value.user_ext.ue_jtzz, // 训练背景
      ue_xxdz: detailInfo.value.user_ext.ue_xxdz, // 特长
      ue_xlbj: detailInfo.value.user_ext.ue_xlbj, // 训练背景
      ue_tc: detailInfo.value.user_ext.ue_tc, // 特长
      // ue_xlbj: detailInfo.value.user_ext.ue_xlbj != '' ? detailInfo.value.user_ext.ue_xlbj : '无', // 训练背景
      // ue_tc: detailInfo.value.user_ext.ue_tc ? detailInfo.value.user_ext.ue_tc : '无', // 特长
      ue_user_phone: detailInfo.value.user_ext.ue_user_phone, // 联系方式
      ue_user_email: detailInfo.value.user_ext.ue_user_email, // 电子邮件
    }
    // props.schoolData.value.map(item => {
    //   if (item.sm_name == ruleForm.value.sm_id) {
    //     ruleForm.value.sm_name = item.sm_name
    //   }
    // })
    await handleChange({ key: 'sm_id' }, ruleForm.value.sm_id, 1)
    handleChange({ key: 'grade' }, ruleForm.value.grade, 1)
  }

  const res1 = await family_list({ uf_user_id: props.userId })
  if (res1.code == 1) {
    const data = res1.data.page_data
    if (data.length != 0) {
      formData.value.map((item) => {
        if (item.key == 'jtzycy') {
          item.childrenData = []
          data.map((value) => {
            const children = JSON.parse(JSON.stringify(item.children))
            children.map((val) => {
              val.value = value[val.key]
            })
            item.childrenData.push({
              uf_id: value.uf_id,
              data: children,
            })
          })
        }
      })
    }
  }

  const res2 = await honor_list({ uh_user_id: props.userId })
  if (res2.code == 1) {
    rymcData.value = res2.data.page_data
    ruleForm.value.sfhj = rymcData.value.length != 0 ? '1' : '2'
  }
}

const gradeData = ref([])
const classData = ref([])
async function handleChange({ key, keyName, field, fieldName }, data, type) {
  if (!type) {
    selectObj.value[key].map((item) => {
      if (data == item.value || data == item[field])
        ruleForm.value[keyName] = item.name || item[fieldName]
    })
  }

  if (key == 'sm_id') {
    // 年级班级
    if (ruleForm.value.sm_id != '') {
      const res3 = await grade_class({ sm_id: ruleForm.value.sm_id })
      if (res3.code == 1)
        gradeData.value = [...res3.data]
      selectObj.value.grade = gradeData.value
    }
    else {
      selectObj.value.grade = []
      selectObj.value.cm_id = []
    }

    if (!type) {
      ruleForm.value.grade = ''
      ruleForm.value.cm_id = ''
    }
    // console.log(gradeData.value, 111111111111)
  }
  else if (key == 'grade') {
    classData.value = []
    gradeData.value.map((item) => {
      if (ruleForm.value.grade == item.grade)
        classData.value = item.classes
    })
    selectObj.value.cm_id = classData.value
    if (!type)
      ruleForm.value.cm_id = ''
  }
  // if (!keyName) {
  //   return
  // }
}
const handleCancel = (type) => {
  emit('close', type)
}
// 提交
const handleSubmit = (formEl) => {
  if (!formEl)
    return

  formEl.validate(async (valid, fields) => {
    if (valid) {
      const filterKeys = ['ue_user_realname', 'sfhj']
      const obj = {}
      for (const key in ruleForm.value) {
        if (!filterKeys.includes(key))
          obj[key] = ruleForm.value[key]
      }

      const obj1 = {
        // user_id: props.userId,
        ue_user_realname: ruleForm.value.ue_user_realname, // 姓名
        ue_xh: ruleForm.value.ue_xh, // 职工编号
        ue_jgmc: ruleForm.value.ue_jgmc, // 籍贯
        ue_user_cardno: ruleForm.value.ue_user_cardno, // 身份证号码
        ue_cym: ruleForm.value.ue_cym, // 曾用名
        ue_user_birthday: ruleForm.value.ue_user_birthday, // 出生日期
        ue_mzmc: ruleForm.value.ue_mzmc, // 民族
        ue_user_gender: ruleForm.value.ue_user_gender, // 性别
        // ue_user_gender: detailInfo.value.user_ext.ue_user_gender == 1 ? '男' : (detailInfo.value.user_ext.ue_user_gender == 2 ? '女' : '保密'), // 性别
        ue_zzmmmc: ruleForm.value.ue_zzmmmc, // 政治面貌
        ue_whcdmc: ruleForm.value.ue_whcdmc, // 文化程度
        ue_szzbmc: ruleForm.value.ue_szzbmc, // 所在支部
        ue_rdsj: ruleForm.value.ue_rdsj, // 入党时间
        ue_bzlxmc: ruleForm.value.ue_bzlxmc, // 编制类型
        ue_szdxzmc: ruleForm.value.ue_szdxzmc, // 所在党小组
        ue_yynlmc: ruleForm.value.ue_yynlmc, // 语言能力
        ue_sm_id: ruleForm.value.sm_id, // 学校
        grade_id: ruleForm.value.grade, // 年级
        jc_id: ruleForm.value.cm_id, // 班级
        ue_xxmc: ruleForm.value.sm_name,
        grade_name: ruleForm.value.gradename, // 年级
        jc_name: ruleForm.value.cm_name, // 班级
        ue_jtzz: ruleForm.value.ue_jtzz, // 训练背景
        ue_xxdz: ruleForm.value.ue_xxdz, // 特长
        ue_xlbj: ruleForm.value.ue_xlbj, // 训练背景
        ue_tc: ruleForm.value.ue_tc, // 特长
        ue_user_phone: ruleForm.value.ue_user_phone, // 联系方式
        ue_user_email: ruleForm.value.ue_user_email, // 电子邮件
      }
      const data = {
        user_ext: obj1,
        user_profile: {
          user_realname: ruleForm.value.ue_user_realname,
        },
        user_main: { sm_id: obj1.ue_sm_id },
        user_id: props.userId,
        cm_id: obj1.jc_id,
      }
      const res = await user_edit(data)
      if (res.code != 1)
        return

      const child = formData.value.filter(item => item.key == 'jtzycy')[0]
        .childrenData
      if (child) {
        child.map(async (item) => {
          const obj = {
            uf_user_id: props.userId,
          }
          item.data.map((val) => {
            obj[val.key] = val.value
          })
          let data1 = {
            user_family: obj,
          }
          if (item.uf_id == '') {
            await family_add(data1)
          }
          else {
            data1 = Object.assign({ uf_id: item.uf_id }, data1)
            await family_edit(data1)
          }
        })
      }

      ElMessage.success('保存成功！')
      handleCancel(1)
    }
    else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<template>
  <!-- <el-scrollbar height="80vh"> -->
  <div class="addAndEdit px-50px">
    <el-form
      ref="ruleFormRef"
      label-position="top"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
    >
      <div v-for="(value, i) in formData" :key="i" class="mb-10">
        <template v-if="value.key != 'jtzycy'">
          <div class="title mb-20px">
            {{ value.name }}
          </div>
          <div class="grid grid-cols-2 gap-x-10">
            <template v-for="(item, index) in value.children" :key="index">
              <el-form-item
                :class="item.class"
                :label="item.name"
                :prop="item.key"
              >
                <el-input
                  v-if="
                    !item.type || item.type == 'email' || item.type == 'tel'
                  "
                  v-model="ruleForm[item.key]"
                />
                <el-input
                  v-if="item.type == 'textarea'"
                  v-model="ruleForm[item.key]"
                  type="textarea"
                  :rows="3"
                />
                <el-date-picker
                  v-if="item.type == 'date'"
                  v-model="ruleForm[item.key]"
                  class="w-full"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
                <el-select
                  v-if="item.type == 'select'"
                  v-model="ruleForm[item.key]"
                  class="w-full"
                  filterable
                  clearable
                  :multiple="item.multiple"
                  @change="(val) => handleChange(item, val)"
                >
                  <el-option
                    v-for="(val, vi) in selectObj[item.key]"
                    :key="vi"
                    :label="val.name || val[item.fieldName]"
                    :value="val.value || val[item.field]"
                  />
                </el-select>
                <el-radio-group
                  v-if="item.type == 'radio'"
                  v-model="ruleForm[item.key]"
                >
                  <el-radio
                    v-for="(val, vi) in selectObj[item.key]"
                    :key="vi"
                    :label="val.value"
                  >
                    {{ val.name }}
                  </el-radio>
                </el-radio-group>
                <div v-if="item.type == 'rymc'">
                  <div class="flex items-center space-x-4">
                    <el-input v-model="rymcValue" />
                    <el-button
                      type="primary"
                      size="small"
                      @click="handleAddRymc"
                    >
                      添加
                    </el-button>
                  </div>
                  <div>
                    <div
                      v-for="(val, vi) in rymcData"
                      :key="vi"
                      class="flex items-center space-x-4"
                    >
                      <span class="rymcName">{{ val.uh_rymc }}</span>
                      <el-icon
                        color="#3F8CFF"
                        class="cursor-pointer"
                        @click="handleRemoveRymc(vi)"
                      >
                        <Close />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </template>
          </div>
        </template>
        <template v-else>
          <div v-for="(children, ci) in value.childrenData" :key="ci">
            <div class="flex justify-between">
              <div class="title mb-20px">
                <span>{{ value.name }}</span>
                <span v-if="value.childrenData.length > 1">{{
                  dealFigureToChinese(ci + 1)
                }}</span>
              </div>
              <el-button
                v-if="value.childrenData.length > 1"
                type="primary"
                size="small"
                plain
                @click="handleRemoveCy(value.childrenData, ci)"
              >
                删除
              </el-button>
            </div>
            <div class="grid grid-cols-2 gap-x-10">
              <el-form-item
                v-for="(item, index) in children.data"
                :key="index"
                :class="item.class"
                :label="item.name"
                :prop="item.key"
              >
                <el-input v-if="!item.type" v-model="item.value" />
              </el-form-item>
            </div>
          </div>
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleAddCy(value)"
          >
            添加成员
          </el-button>
        </template>
      </div>
    </el-form>

    <div class="flex_center space-x-12">
      <el-button size="large" @click="handleCancel(2)">
        取消
      </el-button>
      <el-button size="large" type="primary" @click="handleSubmit(ruleFormRef)">
        确定
      </el-button>
    </div>
  </div>
  <!-- </el-scrollbar> -->
</template>

<style lang="scss" scoped>
.addAndEdit {
  :deep(.el-form) {
    .title {
      color: #3f8cff;
      font-size: 16px;
      font-weight: 600;
      line-height: 22px;
    }
    .el-form-item__label {
      font-size: 14px;
      color: #3f3f44;
      font-weight: 600;
      margin-bottom: 5px;
    }
    .el-form-item__content {
      .el-input,
      .el-input__wrapper,
      .el-textarea__inner {
        width: 100%;
        box-shadow: none;
        border-radius: 8px;
        background: #f7f7f7;
      }
      .rymcName {
        color: #000;
        font-weight: 600;
        line-height: 30px;
      }
    }
  }
}
</style>
