<template>
  <el-drawer
    v-model="visible"
    :title="editor ? t('Label.EditorUser') : t('Label.AddUser')"
    size="650"
    @close="close"
  >
    <el-form ref="formRef" :rules="rules" :model="form" label-width="150PX">
      <el-form-item :label="$t('Label.UserNames') + '：'">
        <el-input v-model.trim="form.username" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('Label.Name') + '：'">
        <el-input v-model="form.name" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('Label.Email') + '：'">
        <el-input v-model.trim="form.email" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <!--      <el-form-item :label="$t('Label.Phone') + '：'">-->
      <!--        <el-input v-model.trim="form.phone" :placeholder="$t('Placeholder.Input')"></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item :label="$t('Label.Pwd') + '：'">
        <el-input v-model.trim="form.password"></el-input>
      </el-form-item>
      <el-form-item :label="$t('Label.RoleName') + '：'">
        <el-select
          v-model="form.roleId"
          class="crm_search_down"
          :placeholder="$t('Placeholder.Choose')"
        >
          <el-option
            v-for="(item, index) in roleName"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.departmentId == '1'" :label="$t('Label.SalesSupervisor') + '：'">
        <el-select
          v-model="form.pid"
          class="crm_search_down"
          filterable
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChange"
        >
          <el-option
            v-for="(item, index) in userSales"
            :key="index"
            :label="item.name + '(' + item.ibNo + ')'"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.departmentId == '1'"
        :label="$t('salaryPerformance.salary.item1') + '：'"
      >
        <el-select
          v-model="form.salesType"
          class="crm_search_down"
          filterable
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChangesalesType"
        >
          <el-option :label="$t('salaryPerformance.salary.item2')" :value="1"></el-option>
          <el-option :label="$t('salaryPerformance.salary.item3')" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.departmentId == '1'"
        :label="$t('salaryPerformance.salary.item3') + '：'"
      >
        <el-select
          v-model="form.leaderId"
          class="crm_search_down"
          filterable
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChange"
        >
          <el-option
            v-for="(item, index) in userSales"
            :key="index"
            :label="item.name + '(' + item.ibNo + ')'"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.departmentId == '1'"
        :label="$t('salaryPerformance.salary.item4') + '：'"
      >
        <el-select
          v-model="form.salesCommissionRuleId"
          class="crm_search_down"
          filterable
          clearable
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChange"
        >
          <el-option
            v-for="(item, index) in GetRuleDropdownList"
            :key="index"
            :label="item.ruleName + '(' + item.kpiStandardName + ')'"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.departmentId == '1'"
        :label="$t('salaryPerformance.salary.item5') + '：'"
      >
        <el-input v-model.trim="form.salaryLogin" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
      <el-form-item
        v-if="form.departmentId == '1'"
        prop="salaryPlatform"
        :label="$t('salaryPerformance.salary.item6') + '：'"
      >
        <el-select
          v-model="form.salaryPlatform"
          class="crm_search_down"
          filterable
          :placeholder="$t('Placeholder.Choose')"
          @change="selectChange"
        >
          <el-option label="MT4" value="MT4"></el-option>
          <el-option label="MT5" value="MT5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('Label.Region') + '：'">
        <el-select
          v-model="form.groupId"
          class="crm_search_down"
          :placeholder="$t('Placeholder.Choose')"
        >
          <el-option
            v-for="(item, index) in GetState"
            :key="index"
            :label="Session.Get('lang') == 'cn' ? item.name : item.enName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('Label.Nationality') + '：'">
        <el-select
          v-model="form.country"
          class="crm_search_down"
          filterable
          remote
          :placeholder="$t('Placeholder.Choose')"
        >
          <el-option
            v-for="(item, index) in mock_options"
            :key="index"
            :label="item.enName"
            :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="areaId" :label="$t('Area.item1') + '：'">
        <el-select
          v-model="form.areaId"
          class="crm_search_down"
          :placeholder="$t('Placeholder.Choose')"
        >
          <el-option
            v-for="(item, index) in GetArea"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item :label="$t('Label.Code') + '：'">-->
      <!--        <el-input v-model.trim="form.ibNo" :placeholder="$t('Placeholder.Input')"></el-input>-->
      <!--      </el-form-item>-->
      <!-- <el-form-item :label="$t('Label.ibNoTemp') + '：'">
        <el-input

          v-model.trim="form.ibNoTemp"
          :placeholder="$t('Placeholder.Input')"
        ></el-input>
      </el-form-item> -->
      <!--      <el-form-item v-if="!editor" :label="$t('Enter_info.GroupEmail') + '：'">-->
      <!--        <el-select-->
      <!--          v-model="form.groupEmail"-->
      <!--          class="crm_search_down"-->
      <!--          :placeholder="$t('Placeholder.Choose')"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="(item, index) in groupEmailList"-->
      <!--            :key="index"-->
      <!--            :label="item.groupName"-->
      <!--            :value="item.groupEmail"-->
      <!--          ></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item prop="entryDate" :label="$t('Label.entryDate') + '：'">-->
      <!--        <el-date-picker-->
      <!--          v-model="form.entryDate"-->
      <!--          type="date"-->
      <!--          class="crm_search_down"-->
      <!--          value-format="YYYY-MM-DD"-->
      <!--          :placeholder="$t('Placeholder.Input')"-->
      <!--        >-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item prop="pid" :label="$t('Label.SalesSupervisor1') + '：'">-->
      <!--        <el-select-->
      <!--          v-model="form.attachId"-->
      <!--          class="crm_search_down"-->
      <!--          filterable-->
      <!--          :placeholder="$t('Placeholder.Choose')"-->
      <!--        >-->
      <!--          <el-option-->
      <!--            v-for="(item, index) in userSales"-->
      <!--            :key="index"-->
      <!--            :label="item.name + '(' + item.ibNo + ')'"-->
      <!--            :value="item.id"-->
      <!--          ></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item prop="entryStatus" :label="$t('Label.EmploymentStatus') + '：'">-->
      <!--        <el-select-->
      <!--          v-model="form.entryStatus"-->
      <!--          class="crm_search_down"-->
      <!--          :placeholder="$t('Placeholder.Choose')"-->
      <!--        >-->
      <!--          <el-option :label="$t('State.employmentStatus1')" :value="1"></el-option>-->
      <!--          <el-option :label="$t('State.employmentStatus2')" :value="2"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item v-if="!user.merchantId" :label="$t('Label.Merchant') + '：'">
        <el-switch
          v-model="form.isMerchantAdmin"
          class="crm_switch"
          :active-value="1"
          :inactive-value="0"
          :active-text="$t('Btn.Yes')"
          :inactive-text="$t('Btn.No')"
          active-color="#368FEC"
          inactive-color="#EB3F57"
        >
        </el-switch>
      </el-form-item>
      <el-form-item :label="$t('Label.LoginState') + '：'">
        <el-switch
          v-model="form.valid"
          class="crm_switch"
          :active-value="1"
          :inactive-value="0"
          :active-text="$t('Btn.Yes')"
          :inactive-text="$t('Btn.No')"
          active-color="#368FEC"
          inactive-color="#EB3F57"
        >
        </el-switch>
      </el-form-item>
      <el-form-item :label="$t('Label.IpLimit') + '：'">
        <el-switch
          v-model="form.ipLimit"
          class="crm_switch"
          :active-value="1"
          :inactive-value="0"
          :active-text="$t('Btn.Yes')"
          :inactive-text="$t('Btn.No')"
          active-color="#368FEC"
          inactive-color="#EB3F57"
        >
        </el-switch>
      </el-form-item>

      <el-form-item v-show="form.ipLimit" :label="$t('Label.limitIp') + '：'">
        <el-input v-model.trim="form.limitIp" :placeholder="$t('Placeholder.Input')"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="confirm">{{ $t('Btn.Confirm') }}</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, onMounted, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { FormInstance, FormRules } from 'element-plus'
  import ServiceSalary from '@/service/salaryPerformance'
  import ServiceMarket from '@/service/marketing'
  import ServiceUser from '@/service/user'
  import Config from '@/config/index'
  import { safeGetUser } from '@/utils/safeJson'

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

  interface Props {
    dialogInfoTradingAdd: boolean
    editor?: string
    myInfo?: any
    formList?: any
  }

  const props = withDefaults(defineProps<Props>(), {
    dialogInfoTradingAdd: false,
    editor: '',
    myInfo: null,
    formList: null,
  })

  const emit = defineEmits<{
    (e: 'update:dialogInfoTradingAdd', value: boolean): void
    (e: 'confirmToReload'): void
    (e: 'close'): void
  }>()

  // Refs
  const formRef = ref<FormInstance>()
  const visible = ref(props.dialogInfoTradingAdd)

  // Reactive data
  const form = reactive({})
  const roleName = ref([])
  const userSales = ref([])
  const GetRuleDropdownList = ref([])
  const GetRuleDropdown = ref([])
  const GetState = ref([])
  const GetArea = ref([])
  const mock_options = ref([])
  const groupEmailList = ref([])
  const rules = ref<FormRules>({
    areaId: [
      {
        required: true,
        message: t('Placeholder.Choose'),
        trigger: 'change',
      },
    ],
  })

  // Computed
  const GetRuleDropdownListComputed = computed(() => {
    return GetRuleDropdown.value.filter((item: any) => item.salesType == form.salesType)
  })
  const user = computed(() => {
    return safeGetUser(Session)
  })
  const role_system = computed(() => {
    const user = JSON.parse(Session.Get('user', true) || '{}')
    return user.departmentId == null && user.roleName == 'ROLE_SYSTEM'
  })

  // Methods
  const selectChangesalesType = (val: number) => {
    form.salesCommissionRuleId = null
    GetRuleDropdownList.value = GetRuleDropdown.value.filter((item: any) => item.salesType == val)
  }
  const getRoleList = async () => {
    let res = await ServiceUser.roleNameList({})
    if (res.code == Code.StatusOK) {
      roleName.value = res.data
    } else {
      pigeon.MessageError(res.msg)
    }
  }
  // 获取邮箱组别列表
  const getGroupEmailList = async () => {
    try {
      let res = await ServiceUser.getGroupEmailList({})
      if (res.code == Code.StatusOK) {
        groupEmailList.value = res.data
      } else {
        // 使用 Element Plus 的消息提示或其他消息组件
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取邮箱组别列表失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }
  // 获取销售主管列表
  const getRoleSuperiorList = async () => {
    try {
      let res = await ServiceUser.userSales({})
      if (res.code == Code.StatusOK) {
        userSales.value = res.data
      } else {
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取销售主管列表失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }

  // 获取薪资绩效规则下拉
  const getsalesCommissionRuleDropdown = async () => {
    let res = await ServiceSalary.salesCommissionRuleDropdown({})
    if (res.code == Code.StatusOK) {
      GetRuleDropdown.value = res.data
      form.salesType = Number(form.salesType) || null
      GetRuleDropdownList.value = GetRuleDropdown.value.filter(
        (item: any) => item.salesType == form.salesType
      )
    } else {
      pigeon.MessageError(res.msg)
    }
  }

  // 获取角色地区信息
  const getDepartmentState = async () => {
    try {
      let res = await ServiceUser.userGroupGet({})
      if (res.code == Code.StatusOK) {
        GetState.value = res.data
      } else {
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取角色地区信息失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }

  // 获取角色区域信息
  const getArealListUP = async () => {
    try {
      let res = await ServiceUser.arealListUP({})
      if (res.code == Code.StatusOK) {
        GetArea.value = res.data
      } else {
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取角色区域信息失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }

  // 获取国家列表
  const getCountry = async () => {
    try {
      let res = await ServiceMarket.Country({})
      if (res.code == Code.StatusOK) {
        mock_options.value = res.data
      } else {
        pigeon.MessageError(res.msg || t('Msg.Error'))
      }
    } catch (error) {
      console.error('获取国家列表失败:', error)
      pigeon.MessageError(t('Msg.NetworkError'))
    }
  }

  // 提交
  const confirm = () => {
    if (!formRef.value) return

    formRef.value.validate((valid) => {
      if (valid) {
        toConfirm()
      } else {
        return false
      }
    })
  }

  const toConfirm = () => {
    if (props.editor) {
      userUpdate()
    } else {
      userAdd()
    }
  }

  // 用户update
  const userUpdate = async () => {
    if (form.departmentId != 1) {
      form.pid = null
      form.salesType = null
      form.salesCommissionRuleId = null
      form.leaderId = null
      form.salaryLogin = null
      form.salaryPlatform = null
    }

    if (!form.ipLimit) {
      form.limitIp = null
    }

    let res = await ServiceUser.userListUpdate({
      ...form,
    })

    if (res.code == Code.StatusOK) {
      emit('confirmToReload')
      close()
      formRef.value?.resetFields()
      // 使用 $pigeon 的替代方式
      console.log(t('Msg.Success'))
    } else {
      console.error(res.msg)
    }
  }

  // 用户add
  const userAdd = async () => {
    if (form.departmentId != 1) {
      form.pid = null
      form.salesType = null
      form.salesCommissionRuleId = null
      form.leaderId = null
      form.salaryLogin = null
      form.salaryPlatform = null
    }

    if (!form.ipLimit) {
      form.limitIp = null
    }

    let res = await ServiceUser.userListAdd({
      ...form,
    })

    if (res.code == Code.StatusOK) {
      emit('confirmToReload')
      formRef.value?.resetFields()
      console.log(t('Msg.Success'))
    } else {
      console.error(res.msg)
    }
  }

  const close = () => {
    emit('update:dialogInfoTradingAdd', false)
    emit('close')
  }

  const selectChange = () => {
    // 选择变更处理
  }

  // Lifecycle
  onMounted(() => {
    // 初始化数据
    // getsalesCommissionRuleDropdown()
  })

  // Watch
  watch(
    () => props.formList,
    (newVal) => {
      if (newVal) {
        Object.assign(form, newVal)
      }
    },
    { immediate: true }
  )
  // Watch
  watch(
    () => props.dialogInfoTradingAdd,
    (newVal) => {
      visible.value = newVal
      if (!newVal && formRef.value) {
        formRef.value?.resetFields()
        Object.keys(form).forEach((key) => (form[key] = ''))
      }
      if (newVal) {
        getDepartmentState()
        getArealListUP()
        getCountry()
        getRoleList()
        getRoleSuperiorList()
        getsalesCommissionRuleDropdown()
        getGroupEmailList()
        if (!form.entryStatus) {
          Object.assign(form, { entryStatus: 1 })
        }
      }
    },
    { immediate: true }
  )
</script>

<style scoped lang="scss"></style>
