<template>
  <div
    id="google"
    v-loading="loading"
    class="view"
    :element-loading-background="'rgba(43, 48, 67, 0.65)'"
    :element-loading-spinner="'el-icon-loading'"
  >
    <!-- 搜索表单 -->
    <div class="crm_search">
      <el-form ref="searchRef" :model="search">
        <el-row>
          <el-col :span="24" :md="24" :lg="24">
            <el-form-item style="margin-right: 10px">
              <el-input
                v-model="search.groupEmail"
                style="width: 330px !important"
                :placeholder="t('Placeholder.Input')"
                clearable
              >
                <template #prepend>
                  <span class="crm-cursor crm-border-radius-no">
                    {{ t('Enter_info.GroupEmail') }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="search.groupName"
                style="width: 300px !important"
                :placeholder="t('Placeholder.Input')"
                clearable
                class="crm-border-radius-no"
              >
                <template #prepend>
                  <span class="crm-cursor crm-border-radius-no">
                    {{ t('Enter_info.GroupName') }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                class="crm-border-radius-no crm-border-left-no"
                :icon="Search"
                @click="handleSearch"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button v-if="display['R-GoogleGroup-Add']?.show" @click="handleAdd">
            {{ t('Btn.Add') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" stripe style="width: 100%">
      <el-table-column :label="t('Enter_info.GroupEmail')">
        <template #default="{ row }">
          {{ row.groupEmail || '--' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('Enter_info.GroupName')">
        <template #default="{ row }">
          {{ row.groupName || '--' }}
        </template>
      </el-table-column>
      <el-table-column :label="t('Label.Action')" width="120" align="center">
        <template #default="{ row }">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link crm-cursor">
              <i style="font-weight: bold; font-size: 20px" class="iconfont iconcaidan"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="display['R-GoogleGroup-Update']?.show"
                  :command="{ type: 'editor', row: row }"
                >
                  <el-icon><Edit /></el-icon>
                  <span>{{ t('Btn.Editor') }}</span>
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="display['R-GoogleGroup-Delete']?.show"
                  :command="{ type: 'delete', id: row.id }"
                >
                  <el-icon><Delete /></el-icon>
                  <span>{{ t('Btn.Delete') }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="pagerInfo.rowTotal" class="crm_pagination">
      <div class="crm_page_total">
        <span>{{ t('Page.total.item1') }}</span>
        <span>{{ pagerInfo.rowTotal }}</span>
        <span>{{ t('Page.total.item2') }}</span>
      </div>
      <el-pagination
        v-model:current-page="pagerInfo.current"
        class="page"
        background
        layout="sizes, prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagerInfo.row"
        :total="pagerInfo.rowTotal"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item :label="t('Enter_info.GroupName') + '：'" prop="groupName">
          <el-input v-model.trim="form.groupName" :placeholder="t('Placeholder.Input')"></el-input>
        </el-form-item>
        <el-form-item :label="t('Enter_info.GroupEmail') + '：'" prop="groupEmail">
          <el-input
            v-model.trim="form.groupEmail"
            type="textarea"
            :placeholder="t('Placeholder.Input')"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">{{ t('Btn.Cancel') }}</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            {{ t('Btn.Confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, nextTick, inject } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
  import { Delete, Edit, Search } from '@element-plus/icons-vue'
  import Service from '@/service/google'
  import Config from '@/config'

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

  // 响应式数据
  const loading = ref(false)
  const searchRef = ref(null)
  const formRef = ref(null)
  const submitLoading = ref(false)
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  const search = reactive({
    groupEmail: '',
    groupName: '',
  })

  const tableData = ref([])

  const pagerInfo = reactive({
    current: 1,
    row: 10,
    rowTotal: 0,
  })

  const form = reactive({
    id: '',
    groupEmail: '',
    groupName: '',
  })

  // 计算属性
  const display = computed(() => {
    return JSON.parse(Session.Get('display', true))
  })
  // 自定义邮箱验证规则
  const validateEmails = (rule, value, callback) => {
    if (!value) {
      callback(new Error(t('Placeholder.Input')))
      return
    }

    // 检查是否包含中文逗号
    if (value.includes('，')) {
      callback(new Error('请使用英文逗号分隔多个邮箱地址'))
      return
    }

    // 分割邮箱地址，只支持英文逗号，去除空格
    const emails = value
      .split(',')
      .map((email) => email.trim())
      .filter((email) => email)

    // 邮箱格式正则表达式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

    // 验证每个邮箱格式
    for (const email of emails) {
      if (!emailRegex.test(email)) {
        callback(new Error(t('vaildate.email.format')))
        return
      }
    }

    callback()
  }
  // 验证规则
  const rules = reactive({
    groupEmail: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
      {
        validator: validateEmails,
        trigger: 'blur',
      },
    ],
    groupName: [
      {
        required: true,
        message: t('Placeholder.Input'),
        trigger: 'blur',
      },
    ],
  })

  // 生命周期
  onMounted(() => {
    fetchData()
  })

  // 方法
  // 获取数据
  const fetchData = async () => {
    loading.value = true
    if (!display.value['R-GoogleGroup-Search']?.show) {
      ElMessage.warning(t('Msg.NotDisplay'))
      loading.value = false
      return
    }

    try {
      const params = {
        ...search,
        page: {
          current: pagerInfo.current,
          row: pagerInfo.row,
        },
      }
      const res = await Service.googleGroupList(params)
      if (res.code === Code.StatusOK) {
        tableData.value = res.data || []
        pagerInfo.rowTotal = res.data.total || 0
      } else {
        ElMessage.error(res.msg || t('Msg.SearchFail'))
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      ElMessage.error(t('Msg.SystemError'))
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagerInfo.current = 1
    fetchData()
  }

  // 新增
  const handleAdd = () => {
    isEdit.value = false
    dialogTitle.value = t('Btn.Add')
    form.id = ''
    form.groupEmail = ''
    form.groupName = ''
    dialogVisible.value = true
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
  }

  // 编辑
  const handleEdit = (row) => {
    isEdit.value = true
    dialogTitle.value = t('Btn.Editor')
    form.id = row.id
    form.groupEmail = row.groupEmail
    form.groupName = row.groupName
    dialogVisible.value = true
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
  }

  // 删除
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm(t('Msg.DeleteConfirm'), t('Msg.SystemPrompt'), {
        confirmButtonText: t('Btn.Confirm'),
        cancelButtonText: t('Btn.Cancel'),
        type: 'warning',
      })

      const res = await Service.googleGroupDelete({ ids: [id] })
      if (res.code === Code.StatusOK) {
        ElMessage.success(t('Msg.DeleteSuccess'))
        fetchData()
      } else {
        ElMessage.error(res.msg || t('Msg.DeleteFail'))
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error(t('Msg.SystemError'))
      }
    }
  }

  // 下拉菜单命令处理
  const handleCommand = (command) => {
    if (command.type === 'editor') {
      handleEdit(command.row)
    } else if (command.type === 'delete') {
      handleDelete(command.id)
    }
  }

  // 分页处理
  const handleCurrentChange = (val) => {
    pagerInfo.current = val
    fetchData()
  }

  const handleSizeChange = (val) => {
    pagerInfo.row = val
    pagerInfo.current = 1
    fetchData()
  }

  // 弹窗关闭
  const handleDialogClose = () => {
    dialogVisible.value = false
    form.id = ''
    form.groupEmail = ''
    form.groupName = ''
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true
    try {
      let res
      if (isEdit.value) {
        // 编辑
        res = await Service.googleGroupUpdate(form)
        if (res.code === Code.StatusOK) {
          ElMessage.success(t('Msg.ModifySuccess'))
          handleDialogClose()
          fetchData()
        } else {
          ElMessage.error(res.msg || t('Msg.ModifyFail'))
        }
      } else {
        // 新增
        res = await Service.googleGroupAdd(form)
        if (res.code === Code.StatusOK) {
          ElMessage.success(t('Msg.SaveSuccess'))
          handleDialogClose()
          fetchData()
        } else {
          ElMessage.error(res.msg || t('Msg.SaveFail'))
        }
      }
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error(t('Msg.SystemError'))
    } finally {
      submitLoading.value = false
    }
  }
</script>
<style lang="scss" scoped>
  #google {
    .crm_search {
      background: #fff;
      border-radius: 4px;
    }

    .el-table {
      margin-bottom: 20px;
    }

    .crm_pagination {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #fff;
      padding: 20px;
      border-radius: 4px;

      .crm_page_total {
        span {
          margin-right: 5px;
        }
      }
    }

    .el-dropdown-link {
      cursor: pointer;
    }
  }
</style>
