<script setup>
import { org_list, org_member_add, org_member_delete, org_member_list } from '../api.js'
import { dealFigureToChinese } from '~/utils/common-util'

const props = defineProps({
  userId: '',
  areaData: [],
  sydwData: [],
})

const emit = defineEmits(['close'])

const ruleFormRef = ref(null)
const ruleForm = reactive({
  qy: '',
  sydw: '',
  bm: '',
})
const manageData = ref([])
const jdRzxxSelectData = ref([])
const formData = ref([
  {
    name: '选择区域',
    key: 'uom_area_id4',
    keyName: 'uom_area_id4_name',
    type: 'select',
    selectKey: 'areaData',
    field: 'id',
    fieldName: 'name',
  },
  {
    name: '事业单位',
    key: 'uo_id_0',
    keyName: 'uo_name_0',
    type: 'select',
    selectKey: 'sydwData',
    field: 'uo_id',
    fieldName: 'uo_name',
  },
  {
    name: '部门',
    key: 'uo_id_1',
    keyName: 'uo_name_1',
    type: 'select',
    selectKey: 'deptData',
    field: 'uo_id',
    fieldName: 'uo_name',
  },
  {
    name: '职位',
    key: 'uom_zw',
  },
])

function handleAddGlbm() {
  const data = JSON.parse(JSON.stringify(formData.value))
  data.map((val) => {
    val.value = ''
  })
  manageData.value.push({
    uom_id: '',
    uom_default: false,
    data,
  })
  jdRzxxSelectData.value.push({
    areaData: props.areaData,
    sydwData: props.sydwData,
    deptData: [],
  })
}

const handleRemoveGlbm = (i) => {
  const data = manageData.value
  if (data[i].uom_id == '') {
    data.splice(i, 1)
    jdRzxxSelectData.value.splice(i, 1)
    const arr = data.filter(item => item.uom_default == true)
    if (arr.length == 0)
      data[0].uom_default = true
  }
  else {
    ElMessageBox.confirm('确定要删除该任职信息吗？', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      center: true,
      buttonSize: 'large',
      customClass: '_',
    })
      .then(async () => {
        const res = await org_member_delete({ uom_id: data[i].uom_id })
        if (res.code == 1) {
          ElMessage.success('删除成功！')
          initJdRzxxData()
        }
      })
      .catch(() => { })
  }
}

// 局端任职信息
initJdRzxxData()
async function initJdRzxxData() {
  const res = await org_member_list({ uom_user_id: props.userId })
  if (res.code == 1) {
    const data = res.data.page_data
    if (data.length != 0) {
      manageData.value = []
      jdRzxxSelectData.value = []
      data.map((value, index) => {
        jdRzxxSelectData.value.push({
          areaData: props.areaData,
          sydwData: props.sydwData,
          deptData: [],
        })

        const children = JSON.parse(JSON.stringify(formData.value))
        const nameObj = {}
        children.map((val) => {
          if (val.keyName)
            nameObj[val.keyName] = value[val.keyName]

          val.value = value[val.key]
          if (val.key == 'uo_id_0')
            handleJdRzxxChange(val, index, val.value)
        })

        let obj = {
          uom_id: value.uom_id,
          uom_default: value.uom_default_option_k == 1,
          data: children,
        }
        obj = Object.assign(obj, nameObj)
        manageData.value.push(obj)
      })
    }
    else {
      const children = JSON.parse(JSON.stringify(formData.value))
      children.map((val) => {
        val.value = ''
      })
      manageData.value = [{
        uom_id: '',
        uom_default: true,
        data: [...children],
      }]
      jdRzxxSelectData.value = [{
        areaData: props.areaData,
        sydwData: props.sydwData,
        deptData: [],
      }]
    }
  }
}

const handleJdRzxxChange = async (item, index, val, data) => {
  if (item.key == 'uo_id_0') {
    if (data) {
      data.map((v) => {
        (v.key == 'uo_id_1') && (v.value = '')
      })
    }
    const res = await org_list({ uo_pid: val, limit: '100' })
    if (res.code == 1)
      jdRzxxSelectData.value[index].deptData = res.data.page_data
  }
  else if (item.key == 'uom_default') {
    manageData.value.map((v, i) => {
      v[item.key] = i == index
    })
  }

  if (item.keyName && manageData.value[index]) {
    jdRzxxSelectData.value[index][item.selectKey].map((v) => {
      if (val == v[item.field]) {
        manageData.value[index][item.keyName] = v[item.fieldName]
        if (item.key == 'uo_id_1')
          manageData.value[index].uom_uo_path = v.uo_path
      }
    })
  }
}

const handleCancel = (type) => {
  emit('close', type)
}

const handleSubmit = async () => {
  const arr = []
  manageData.value.map((item) => {
    const jdRzObj = {}
    item.data.map((value) => {
      jdRzObj[value.key] = value.value
    })
    const obj = {
      uom_user_id: props.userId,
      uom_id: item.uom_id,
      uo_id_0: jdRzObj.uo_id_0,
      uo_name_0: item.uo_name_0 || '',
      uo_id_1: jdRzObj.uo_id_1,
      uo_name_1: item.uo_name_1 || '',
      uom_uo_path: item.uom_uo_path || '',
      uom_zw: jdRzObj.uom_zw,
      uom_default: item.uom_default ? '1' : '2',
      uom_area_id1: '15',
      uom_area_id2: '235',
      uom_area_id3: '2615',
      uom_area_id4: jdRzObj.uom_area_id4,
      uom_area_id4_name: item.uom_area_id4_name || '',
    }
    arr.push(obj)
  })
  await org_member_add({ user_org_member: arr })

  ElMessage.success('保存成功！')
  handleCancel()
}
</script>

<template>
  <div class="manageDepartment px-50px">
    <el-form ref="ruleFormRef" class="mb-10" label-position="top" :model="ruleForm" :rules="rules">
      <div v-for="(children, ci) in manageData" :key="ci">
        <div class="flex justify-between items-center mb-20px">
          <div class="title">
            <span>管理部门</span>
            <span v-if="manageData.length > 1">{{ dealFigureToChinese(ci + 1) }}</span>
          </div>
          <div class="flex items-center space-x-6">
            <el-checkbox v-model="children.uom_default" label="登录默认部门" @change="(val) => handleJdRzxxChange({ key: 'uom_default' }, ci)" />
            <el-button v-if="manageData.length > 1" type="primary" size="small" plain @click="handleRemoveGlbm(ci)">
              删除
            </el-button>
          </div>
        </div>
        <div class="grid grid-cols-2 gap-x-6">
          <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-select v-if="item.type == 'select'" v-model="item.value" class="w-full" filterable clearable @change="(val) => handleJdRzxxChange(item, ci, val, children.data)">
              <el-option v-for="(val, vi) in jdRzxxSelectData[ci][item.selectKey]" :key="vi" :label="val[item.fieldName]" :value="val[item.field]" />
            </el-select>
          </el-form-item>
        </div>
      </div>
      <el-button type="primary" size="small" plain @click="handleAddGlbm(value)">
        添加管理部门
      </el-button>
    </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">
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.manageDepartment {
  :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 {
        width: 100%;
        box-shadow: none;
        border-radius: 8px;
        background: #f7f7f7;
      }
    }
  }
}
</style>
