<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="搜索" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="搜索客户编码/名称..."
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态" class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['cus:management:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['cus:management:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['cus:management:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="客户编码" align="center" prop="customerCode" min-width="160px" />
      <el-table-column label="客户名称" align="center" prop="customerName" min-width="160px" />
      <el-table-column label="区域" align="center" min-width="160px">
        <template #default="scope">
          {{
            [scope.row.provinceName, scope.row.cityName].filter((v) => !!v).join(' ') ||
            scope.row.countryName ||
            '-'
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="售后负责人"
        align="center"
        prop="afterSalesManager"
        min-width="140px"
      />
      <el-table-column label="状态" align="center" prop="status" min-width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openConfig(scope.row)"
            v-hasPermi="['cus:management:update']"
          >
            配置
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleSyncData(scope.row)"
            v-hasPermi="['cus:management:update']"
          >
            同步数据
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['cus:management:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cus:management:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ManagementForm ref="formRef" @success="getList" />

  <Dialog v-model="configDialogVisible" title="数据库配置" width="40%">
    <el-form
      ref="configFormRef"
      v-loading="configLoading"
      :model="configFormData"
      :rules="configRules"
      label-width="100px"
    >
      <el-form-item label="数据库IP" prop="dbIp">
        <el-input v-model="configFormData.dbIp" placeholder="请输入数据库IP" />
      </el-form-item>
      <el-form-item label="数据库端口" prop="dbPort">
        <el-input-number
          v-model="configFormData.dbPort"
          :min="1"
          :max="65535"
          controls-position="right"
          class="w-full"
          placeholder="请输入数据库端口"
        />
      </el-form-item>
      <el-form-item label="数据库账号" prop="dbUsername">
        <el-input v-model="configFormData.dbUsername" placeholder="请输入数据库账号" />
      </el-form-item>
      <el-form-item label="数据库密码" prop="dbPassword">
        <el-input
          v-model="configFormData.dbPassword"
          placeholder="请输入数据库密码"
          show-password
          type="password"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleTestConnection" :disabled="configLoading">测试连接</el-button>
      <el-button type="primary" @click="submitConfig" :disabled="configLoading">确 定</el-button>
      <el-button @click="configDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ManagementApi, Management } from '@/api/cus/management'
import ManagementForm from './ManagementForm.vue'

/** 客户管理 列表 */
defineOptions({ name: 'Management' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Management[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const keyword = queryParams.keyword?.trim()
    const baseParams = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      status: queryParams.status
    }
    let data = await ManagementApi.getManagementPage({
      ...baseParams,
      customerCode: keyword || undefined
    })
    if (keyword && (!data?.list?.length || data.total === 0)) {
      data = await ManagementApi.getManagementPage({
        ...baseParams,
        customerName: keyword
      })
    }
    list.value = data?.list || []
    total.value = data?.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ManagementApi.deleteManagement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除客户管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ManagementApi.deleteManagementList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Management[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

const configDialogVisible = ref(false)
const configLoading = ref(false)
const configFormRef = ref()
const configOriginRow = ref<Management | undefined>(undefined)
const configFormData = reactive({
  dbIp: undefined,
  dbPort: undefined,
  dbUsername: undefined,
  dbPassword: undefined
})
const configRules = reactive({
  dbIp: [{ required: true, message: '数据库IP不能为空', trigger: 'blur' }],
  dbPort: [{ required: true, message: '数据库端口不能为空', trigger: 'blur' }],
  dbUsername: [{ required: true, message: '数据库账号不能为空', trigger: 'blur' }]
})

const openConfig = (row: Management) => {
  configOriginRow.value = row
  configFormData.dbIp = row.dbIp
  configFormData.dbPort = row.dbPort
  configFormData.dbUsername = row.dbUsername
  configFormData.dbPassword = row.dbPassword
  configDialogVisible.value = true
  nextTick(() => configFormRef.value?.clearValidate())
}

const handleTestConnection = async () => {
  try {
    await configFormRef.value.validate()
    configLoading.value = true
    await ManagementApi.testDbConnection({
      id: configOriginRow.value?.id,
      ...configFormData
    })
    message.success('连接成功')
  } catch (e: any) {
    const tip = e?.msg || e?.message
    if (tip) {
      message.error(tip)
    }
  } finally {
    configLoading.value = false
  }
}

const submitConfig = async () => {
  await configFormRef.value.validate()
  if (!configOriginRow.value?.id) return
  configLoading.value = true
  try {
    await ManagementApi.updateManagement({
      ...(configOriginRow.value as any),
      ...configFormData,
      id: configOriginRow.value.id
    })
    message.success(t('common.updateSuccess'))
    configDialogVisible.value = false
    await getList()
  } finally {
    configLoading.value = false
  }
}

const handleSyncData = async (row: Management) => {
  try {
    await message.confirm('确认同步该客户的数据？')
    await ManagementApi.syncData(row.id)
    message.success('同步成功')
  } catch (e: any) {
    const tip = e?.msg || e?.message
    if (tip) {
      message.error(tip)
    }
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ManagementApi.exportManagement(queryParams as any)
    download.excel(data, '客户管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
