<template>
  <div
    id="TradingDetailedInfoAdd"
    v-loading="loading"
    element-loading-background="rgba(122, 122, 122, 0.8)"
    element-loading-text="Loading..."
    class="InfoBox"
    :class="{ active: dialogInfoTradingAdd }"
  >
    <div class="header">
      <span v-if="editor" class="title">{{ $t('Label.EditorRole') }}</span>
      <span v-else class="title">{{ $t('Label.AddRole') }}</span>
      <span class="close crm-cursor" @click="close">
        <el-icon><Close /></el-icon>
      </span>
    </div>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="100PX">
      <el-form-item prop="name" :label="$t('Label.RoleName') + '：'">
        <el-input
          v-model="form.name"
          :placeholder="$t('Placeholder.Input')"
          @input="selectChange"
        ></el-input>
      </el-form-item>
      <el-form-item prop="departmentId" :label="$t('Label.RoleGroup') + '：'">
        <el-select
          v-model="form.departmentId"
          class="crm_search_down"
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChange"
        >
          <el-option
            v-for="(item, index) in group"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="authorityBox" :label="$t('Label.permissions') + '：'">
        <div
          style="
            border: 1px solid #dcdfe6;
            padding: 5px 2px;
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-end;
            width: 100%;
          "
        >
          <el-button
            v-if="role_system"
            style="padding-right: 4px"
            type="text"
            @click="() => append('one')"
          >
            {{ $t('R-OneNodeAdd') }}
          </el-button>
          <el-tree
            ref="treeRef"
            style="width: 100%"
            :data="roleTreeDate"
            show-checkbox
            :props="defaultProps"
            node-key="tId"
            :default-checked-keys="defaultSelect"
            @check="handleCheck"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span v-if="role_system">
                  <el-icon @click="() => append(data)"><CirclePlus /></el-icon>
                  <el-icon @click="() => update(data)"><Edit /></el-icon>
                  <el-icon @click="() => remove(data)"><Delete /></el-icon>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-form-item>
    </el-form>
    <el-button :loading="addLoading" class="btn crm-cursor" @click="confirm">{{
      $t('Btn.Confirm')
    }}</el-button>
    <el-dialog
      v-model="dialogCheck"
      :title="dialogCheck_form.title"
      center
      append-to-body
      width="600"
      custom-class="dialog_header_w"
      @close="cancel"
    >
      <div class="dia-content">
        <el-form
          ref="dialogCheckFormRef"
          :model="dialogCheck_form"
          :rules="rules"
          label-width="135px"
          class="dialogCheck_form"
        >
          <el-form-item
            v-if="dialogCheck_form.typeIndex1 != 3"
            prop="name"
            :label="$t('Label.AuthorityName') + '：'"
          >
            <el-input
              v-model="dialogCheck_form.name"
              style="width: 400px"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="dialogCheck_form.typeIndex != 3 && dialogCheck_form.typeIndex1 != 3"
            prop="link"
            :label="$t('Label.Url') + '：'"
          >
            <el-input
              v-model.trim="dialogCheck_form.link"
              style="width: 400px"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="dialogCheck_form.typeIndex != 3 && dialogCheck_form.typeIndex1 != 3"
            prop="icon"
            :label="$t('Label.Icon') + '：'"
          >
            <el-input
              v-model.trim="dialogCheck_form.icon"
              style="width: 400px"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="dialogCheck_form.typeIndex != 3 && dialogCheck_form.typeIndex1 != 3"
            prop="subIndex"
            :label="$t('Label.SubIndex') + '：'"
          >
            <el-input
              v-model.number.trim="dialogCheck_form.subIndex"
              style="width: 400px"
              :placeholder="$t('Placeholder.Input')"
              @input="selectChange"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="dialogCheck_form.typeIndex == 3 && dialogCheck_form.typeIndex1 != 3"
            prop="action"
            :label="$t('Label.Url') + '：'"
          >
            <el-input
              v-model.trim="dialogCheck_form.action"
              style="width: 400px"
              :placeholder="$t('Placeholder.Input')"
            ></el-input>
          </el-form-item>
          <div
            v-if="dialogCheck_form.typeIndex1 == 3"
            style="text-align: center; font-size: 20px; padding: 25px 0"
          >
            {{ $t('Msg.Delete') }}
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogCheck_form.typeIndex1 == 1" type="primary" @click="toAppend()">
            {{ $t('Btn.Confirm') }}
          </el-button>
          <el-button v-if="dialogCheck_form.typeIndex1 == 2" type="primary" @click="toUpdate()">
            {{ $t('Btn.Confirm') }}
          </el-button>
          <el-button v-if="dialogCheck_form.typeIndex1 == 3" type="primary" @click="toRemove()">
            {{ $t('Btn.Confirm') }}
          </el-button>
          <el-button @click="cancel">{{ $t('Btn.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, watch, inject } from 'vue'
  import { CirclePlus, Edit, Delete, Close } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import ServiceUser from '@/service/user'
  import Config from '@/config/index'
  import { useI18n } from 'vue-i18n'

  const { Code } = Config
  const { t } = useI18n()
  const Session = inject('session')

  // props
  const props = defineProps({
    dialogInfoTradingAdd: {
      type: Boolean,
      default: false,
    },
    editor: {
      default: '',
    },
    myInfo: {
      default: '',
    },
    formList: {
      default: '',
    },
  })

  // emits
  const emit = defineEmits(['confirmToReload', 'closeAdd'])

  // refs
  const formRef = ref(null)
  const treeRef = ref(null)
  const dialogCheckFormRef = ref(null)
  // 新增loading
  const addLoading = ref(false)
  const loading = ref(false)

  // reactive data
  const form = reactive({})
  const group = ref([])
  const roleTreeDate = ref([])
  const defaultSelect = ref([])
  const data_check = ref([])

  const dialogCheck = ref(false)
  const dialogCheck_form = reactive({
    title: '',
    typeIndex: null,
    typeIndex1: null,
    pid: null,
    valid: null,
    id: null,
    subIndex: null,
    name: '',
    link: '',
    icon: '',
    action: '',
    ids: [],
    nodeId: null,
    code: '',
  })

  // constants
  const defaultProps = {
    children: 'children',
    label: 'name',
  }

  // computed
  const role_system = computed(() => {
    const user = JSON.parse(Session.Get('user', true) || '{}')
    return user.departmentId == null && user.roleName == 'ROLE_SYSTEM'
  })

  // rules
  const rules = reactive({
    name: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
    link: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
    icon: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
    subIndex: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
    action: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
  })

  // methods
  const selectChange = () => {
    // 这里可能需要强制更新
  }

  const append = (data) => {
    console.log(data, 'append')
    if (data == 'one') {
      dialogCheck_form.title = t('R-OneNodeAdd')
      dialogCheck_form.typeIndex = 1
      dialogCheck_form.typeIndex1 = 1
      dialogCheck_form.pid = null
      dialogCheck_form.valid = 1
    } else {
      if (data.type == 0 && !data.pid) {
        dialogCheck_form.title = t('R-TwoNodeAdd')
        dialogCheck_form.typeIndex = 2
        dialogCheck_form.typeIndex1 = 1
        dialogCheck_form.pid = data.id
        dialogCheck_form.valid = 1
      } else {
        dialogCheck_form.title = t('R-BtnAdd')
        dialogCheck_form.typeIndex = 3
        dialogCheck_form.typeIndex1 = 1
        dialogCheck_form.nodeId = data.id
        dialogCheck_form.valid = 1
      }
    }
    dialogCheck.value = true
  }

  const update = (data) => {
    if (data.type == 0 && !data.pid) {
      dialogCheck_form.title = t('R-OneNodeAdd')
      dialogCheck_form.typeIndex = 1
      dialogCheck_form.typeIndex1 = 2
      dialogCheck_form.pid = null
      dialogCheck_form.valid = 1
      dialogCheck_form.id = data.id
      dialogCheck_form.subIndex = data.subIndex
    } else {
      if (data.type == 0 && data.pid) {
        dialogCheck_form.title = t('R-TwoNodeAdd')
        dialogCheck_form.typeIndex = 2
        dialogCheck_form.typeIndex1 = 2
        dialogCheck_form.pid = data.pid
        dialogCheck_form.valid = 1
        dialogCheck_form.id = data.id
        dialogCheck_form.subIndex = data.subIndex
      } else if (data.type == 1 && data.pid) {
        dialogCheck_form.title = t('R-BtnAdd')
        dialogCheck_form.typeIndex = 3
        dialogCheck_form.typeIndex1 = 2
        dialogCheck_form.nodeId = data.pid
        dialogCheck_form.valid = 1
        dialogCheck_form.id = data.id
      }
    }

    dialogCheck_form.name = data.name || ''
    dialogCheck_form.link = data.link || ''
    dialogCheck_form.icon = data.icon || ''
    dialogCheck_form.action = data.action || ''

    dialogCheck.value = true
  }

  const remove = (data) => {
    if (data.type == 0 && !data.pid) {
      dialogCheck_form.title = t('R-OneNodeAdd')
      dialogCheck_form.typeIndex = 1
      dialogCheck_form.typeIndex1 = 3
      dialogCheck_form.ids = [data.id]
    } else {
      if (data.type == 0 && data.pid) {
        dialogCheck_form.title = t('R-TwoNodeAdd')
        dialogCheck_form.typeIndex = 2
        dialogCheck_form.typeIndex1 = 3
        dialogCheck_form.ids = [data.id]
      } else if (data.type == 1 && data.pid) {
        dialogCheck_form.title = t('R-BtnAdd')
        dialogCheck_form.typeIndex = 3
        dialogCheck_form.typeIndex1 = 3
        dialogCheck_form.ids = [data.id]
      }
    }
    dialogCheck.value = true
  }

  const getDepartmentList = async () => {
    try {
      const res = await ServiceUser.departmentList({})
      if (res.code == Code.StatusOK) {
        group.value = res.data
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      ElMessage.error(t('Msg.RequestError'))
    }
  }

  const handleCheck = (data, checked) => {
    data_check.value = []
    const checkedNodes = [...checked.checkedNodes, ...checked.halfCheckedNodes]

    checkedNodes.forEach((item) => {
      const dataItem = {
        name: item.code,
        id: item.id,
        pid: item.pid,
        type: item.type,
      }
      data_check.value.push(dataItem)
    })
  }

  const getDataCheck = () => {
    const data_c = []
    roleTreeDate.value.forEach((item) => {
      if (item.show) {
        data_c.push({
          name: item.code,
          id: item.id,
          pid: item.pid,
          type: item.type,
        })
      }
      if (item.children?.length) {
        item.children.forEach((item1) => {
          if (item1.show) {
            data_c.push({
              name: item1.code,
              id: item1.id,
              pid: item1.pid,
              type: item1.type,
            })
          }
          const btnsArray = item1.btns ? Object.values(item1.btns) : []
          btnsArray.forEach((item2) => {
            if (item2.show) {
              data_c.push({
                name: item2.code,
                id: item2.id,
                pid: item2.pid,
                type: item2.type,
              })
            }
          })
        })
      }
    })
    data_check.value = data_c
  }

  const cancel = () => {
    dialogCheck.value = false
    dialogCheckFormRef.value?.resetFields()
  }

  const toAppend = async () => {
    try {
      const valid = await dialogCheckFormRef?.value.validate()
      console.log(valid)
      console.log(dialogCheck_form)
      const { typeIndex } = dialogCheck_form
      if (valid) {
        if (typeIndex == 1 || typeIndex == 2) {
          dialogCheck_form.subIndex = Number(dialogCheck_form.subIndex)
          dialogCheck_form.code = dialogCheck_form.name

          const res = await ServiceUser.authorityNodeAdd({
            ...dialogCheck_form,
          })

          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        } else if (typeIndex == 3) {
          dialogCheck_form.code = dialogCheck_form.name
          let res = await ServiceUser.authorityActionAdd({
            ...dialogCheck_form,
          })
          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        }
        cancel()
        getRoleDetailAdd()
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }
  const getRoleDetailUpdate = async () => {
    // 复制表单数据
    Object.assign(form, props.formList)

    try {
      const res = await ServiceUser.groupSingleUpdate({
        id: props.formList?.id || form.id,
      })

      if (res.code === Code.StatusOK) {
        // 处理角色树数据
        const processedData = processRoleTreeData(res.data)
        roleTreeDate.value = processedData.data
        defaultSelect.value = processedData.select
      } else {
        ElMessage.error(res.msg || t('Msg.RequestError'))
      }
      loading.value = false
    } catch (error) {
      console.error('获取角色详情失败:', error)
      ElMessage.error(t('Msg.RequestError'))
    }
  }
  // 处理角色树数据的函数（可以独立出来复用）
  const processRoleTreeData = (treeData) => {
    const select = []

    const processedData = treeData.map((item) => {
      // 处理一级节点
      const processedItem = {
        ...item,
        name: t(item.name),
        children: item.children ? processChildrenNodes(item.children, select) : [],
      }

      return processedItem
    })

    return {
      data: processedData,
      select,
    }
  }
  // 处理子节点
  const processChildrenNodes = (children, select) => {
    return children.map((child) => {
      // 处理二级节点
      const btnsArray = child.btns ? Object.values(child.btns) : []

      // 处理三级节点（按钮节点）
      const buttonNodes = btnsArray.map((btn) => {
        const buttonNode = {
          ...btn,
          name: t(btn.name),
        }

        // 如果按钮节点显示，添加到选中列表中
        if (buttonNode.show) {
          select.push(buttonNode.tId)
        }

        return buttonNode
      })

      const processedChild = {
        ...child,
        name: t(child.name),
        children: buttonNodes,
      }

      // 如果没有子节点且当前节点显示，添加到选中列表中
      if (!buttonNodes.length && processedChild.show) {
        select.push(processedChild.tId)
      }

      return processedChild
    })
  }

  const toUpdate = async () => {
    try {
      const valid = await dialogCheckFormRef.value.validate()
      if (valid) {
        const { typeIndex } = dialogCheck_form
        if (typeIndex == 1 || typeIndex == 2) {
          dialogCheck_form.subIndex = Number(dialogCheck_form.subIndex)
          dialogCheck_form.code = dialogCheck_form.name

          const res = await ServiceUser.authorityNodeUpdate({
            ...dialogCheck_form,
          })

          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        } else if (typeIndex == 3) {
          dialogCheck_form.code = dialogCheck_form.name
          let res = await ServiceUser.authorityActionUpdate({
            ...dialogCheck_form,
          })
          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        }
        cancel()
        getRoleDetailAdd()
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  const toRemove = async () => {
    try {
      const valid = await dialogCheckFormRef.value.validate()
      if (valid) {
        const { typeIndex } = dialogCheck_form
        if (typeIndex == 1 || typeIndex == 2) {
          const res = await ServiceUser.authorityNodeDelete({
            ...dialogCheck_form,
          })

          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        } else if (typeIndex == 3) {
          let res = await ServiceUser.authorityActionDelete({
            ...dialogCheck_form,
          })
          if (res.code == Code.StatusOK) {
            ElMessage.success(res.msg)
          } else {
            ElMessage.error(res.msg)
          }
        }
        cancel()
        getRoleDetailAdd()
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }

  const getRoleDetailAdd = async () => {
    try {
      const res = await ServiceUser.groupSingleAdd({})
      if (res.code == Code.StatusOK) {
        const data = res.data.map((item) => {
          return {
            ...item,
            name: t(item.name),
            children:
              item.children?.map((child) => ({
                ...child,
                name: t(child.name),
                children: child.btns
                  ? Object.values(child.btns).map((btn) => ({
                      ...btn,
                      name: t(btn.name),
                    }))
                  : [],
              })) || [],
          }
        })
        roleTreeDate.value = data
        loading.value = false
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      ElMessage.error(t('Msg.RequestError'))
    }
  }

  const confirm = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        toConfirm()
      } else {
        return false
      }
    })
  }
  const toConfirm = () => {
    addLoading.value = true
    if (props.editor) {
      roleUpdate()
    } else {
      roleAdd()
    }
  }
  const roleAdd = async () => {
    let res = await ServiceUser.roleListAdd({
      data: data_check.value,
      code: 'ROLE_USER',
      ...form,
    })
    addLoading.value = false
    if (res.code == Code.StatusOK) {
      formRef.value.resetFields()
      roleTreeDate.value = []
      emit('confirmToReload')
      emit('closeAdd', false)
      ElMessage.success(t('Msg.Success'))
    } else {
      ElMessage.error(res.msg)
    }
  }
  const roleUpdate = async () => {
    if (!data_check.value.length) {
      getDataCheck()
    }

    let res = await ServiceUser.roleListUpdate({
      data: data_check.value,
      code: 'ROLE_USER',
      ...form,
    })
    addLoading.value = false
    if (res.code == Code.StatusOK) {
      roleTreeDate.value = []
      defaultSelect.value = []
      formRef.value.resetFields()
      emit('confirmToReload')
      emit('closeAdd', false)
      ElMessage.success(t('Msg.Success'))
    } else {
      ElMessage.error(res.msg)
    }
  }
  //提交成功后回调
  const confirmToReload = () => {
    emit('confirmToReload', true)
  }

  // watch for props changes
  watch(
    () => props.formList,
    (newVal) => {
      if (newVal) {
        Object.assign(form, newVal)
      }
    },
    { immediate: true }
  )
  watch(
    () => props.dialogInfoTradingAdd,
    async (newVal) => {
      loading.value = true
      if (newVal) {
        if (props.editor) {
          await getRoleDetailUpdate()
        } else {
          await getRoleDetailAdd()
        }
      }
    }
  )

  // lifecycle
  onMounted(async () => {
    // await Promise.all([getDepartmentList(), getRoleDetailAdd()])
    getDepartmentList()
    console.log(props, 'props')

    // 设置默认选中
    if (props.editor && props.formList?.id) {
      // 如果有编辑数据，设置默认选中项
      // 这里需要根据实际逻辑设置 defaultSelect.value
    }
  })
</script>

<style scoped></style>
