<template>
  <ArtTableFullScreen>
    <div class="enterprise-customer-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="false"
        label-width="90"
        @reset="handleReset"
        @search="handleSearch"
      ></ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton @click="showDialog('add')" v-permission="'enterprise_customer:add'"
              >新增企业客户</ElButton
            >
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable
          ref="tableRef"
          row-key="id"
          :loading="loading"
          :data="enterpriseList"
          :currentPage="pagination.page"
          :pageSize="pagination.pageSize"
          :total="pagination.total"
          :marginTop="10"
          :actions="getActions"
          :actionsWidth="160"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>

        <!-- 新增/编辑对话框 -->
        <ElDialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '新增企业客户' : '编辑企业客户'"
          width="40%"
        >
          <ElForm ref="formRef" :model="form" :rules="rules" label-width="100px">
            <ElFormItem label="企业编号" prop="enterprise_code">
              <div style="display: flex; gap: 8px">
                <ElInput
                  v-model="form.enterprise_code"
                  placeholder="请输入企业编号或点击生成"
                  :disabled="dialogType === 'edit'"
                  clearable
                  style="flex: 1"
                />
                <CodeGeneratorButton
                  v-if="dialogType === 'add'"
                  code-type="enterprise"
                  @generated="handleCodeGenerated"
                />
              </div>
            </ElFormItem>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="企业名称" prop="enterprise_name">
                  <ElInput v-model="form.enterprise_name" placeholder="请输入企业名称" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="法人代表" prop="legal_person">
                  <ElInput v-model="form.legal_person" placeholder="请输入法人代表" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="营业执照号" prop="business_license">
                  <ElInput v-model="form.business_license" placeholder="请输入营业执照号" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="所在地区" prop="region">
                  <ElCascader
                    v-model="form.region"
                    :options="regionData"
                    placeholder="请选择省/市/区"
                    clearable
                    filterable
                    style="width: 100%"
                    @change="handleRegionChange"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="20">
              <!-- 只有非代理账号才显示归属店铺选择 -->
              <ElCol :span="12" v-if="!isAgentAccount">
                <ElFormItem label="归属店铺" prop="owner_shop_id">
                  <ElTreeSelect
                    v-model="form.owner_shop_id"
                    :data="shopTreeData"
                    placeholder="请选择归属店铺"
                    filterable
                    clearable
                    check-strictly
                    :render-after-expand="false"
                    :props="{
                      label: 'shop_name',
                      value: 'id',
                      children: 'children'
                    }"
                    style="width: 100%"
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElFormItem label="详细地址" prop="address">
              <ElInput
                v-model="form.address"
                type="textarea"
                :rows="2"
                placeholder="请输入详细地址"
              />
            </ElFormItem>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="联系人姓名" prop="contact_name">
                  <ElInput v-model="form.contact_name" placeholder="请输入联系人姓名" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="联系人电话" prop="contact_phone">
                  <ElInput v-model="form.contact_phone" placeholder="请输入联系人电话" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="登录手机号" prop="login_phone">
                  <ElInput
                    v-model="form.login_phone"
                    placeholder="请输入登录手机号"
                    :disabled="dialogType === 'edit'"
                  />
                </ElFormItem>
              </ElCol>
              <ElCol :span="12" v-if="dialogType === 'add'">
                <ElFormItem label="登录密码" prop="password">
                  <ElInput
                    v-model="form.password"
                    type="password"
                    placeholder="请输入登录密码"
                    show-password
                  />
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="handleCancel">取消</ElButton>
              <ElButton type="primary" @click="handleSubmit(formRef)" :loading="submitLoading">
                提交
              </ElButton>
            </div>
          </template>
        </ElDialog>

        <!-- 修改密码对话框 -->
        <ElDialog v-model="passwordDialogVisible" title="修改密码" width="400px">
          <ElForm ref="passwordFormRef" :model="passwordForm" :rules="passwordRules">
            <ElFormItem label="新密码" prop="password">
              <ElInput
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入新密码(6-20位)"
                show-password
              />
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="handlePasswordCancel">取消</ElButton>
              <ElButton
                type="primary"
                @click="handlePasswordSubmit(passwordFormRef)"
                :loading="passwordSubmitLoading"
              >
                提交
              </ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { useRouter } from 'vue-router'
  import { RoutesAlias } from '@/router/routesAlias'
  import { EnterpriseService, ShopService } from '@/api/modules'
  import { ElMessage, ElSwitch, ElCascader, ElTreeSelect } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type { EnterpriseItem, ShopResponse } from '@/types/api'
  import type { SearchFormItem } from '@/types'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { useAuth } from '@/composables/useAuth'
  import { useUserStore } from '@/store/modules/user'
  import CodeGeneratorButton from '@/components/business/CodeGeneratorButton.vue'
  import { formatDateTime } from '@/utils/business/format'
  import { regionData } from '@/utils/constants/regionData'

  defineOptions({ name: 'EnterpriseCustomer' })

  const { hasAuth } = useAuth()
  const userStore = useUserStore()

  const router = useRouter()

  // 判断是否是代理账号 (user_type === 3)
  const isAgentAccount = computed(() => userStore.info.user_type === 3)

  const dialogVisible = ref(false)
  const passwordDialogVisible = ref(false)
  const loading = ref(false)
  const submitLoading = ref(false)
  const passwordSubmitLoading = ref(false)
  const shopLoading = ref(false)
  const tableRef = ref()
  const currentEnterpriseId = ref<number>(0)
  const shopTreeData = ref<ShopResponse[]>([])

  // 搜索表单初始值
  const initialSearchState = {
    enterprise_name: '',
    login_phone: '',
    contact_phone: '',
    status: undefined as number | undefined
  }

  // 搜索表单
  const searchForm = reactive({ ...initialSearchState })

  // 状态选项
  const statusOptions = [
    { label: '启用', value: 1 },
    { label: '禁用', value: 0 }
  ]

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: '企业名称',
      prop: 'enterprise_name',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入企业名称'
      }
    },
    {
      label: '登录手机号',
      prop: 'login_phone',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入登录手机号'
      }
    },
    {
      label: '联系人电话',
      prop: 'contact_phone',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入联系人电话'
      }
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '请选择状态',
        options: statusOptions
      }
    }
  ]

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 列配置
  const columnOptions = [
    { label: '企业编号', prop: 'enterprise_code' },
    { label: '企业名称', prop: 'enterprise_name' },
    { label: '营业执照号', prop: 'business_license' },
    { label: '法人代表', prop: 'legal_person' },
    { label: '联系人姓名', prop: 'contact_name' },
    { label: '联系人电话', prop: 'contact_phone' },
    { label: '登录手机号', prop: 'login_phone' },
    { label: '所在地区', prop: 'address' },
    { label: '归属店铺', prop: 'owner_shop_name' },
    { label: '状态', prop: 'status' },
    { label: '创建时间', prop: 'created_at' },
    { label: '操作', prop: 'operation' }
  ]

  const formRef = ref<FormInstance>()
  const passwordFormRef = ref<FormInstance>()

  const rules = reactive<FormRules>({
    enterprise_code: [
      { required: true, message: '请输入企业编号', trigger: 'blur' },
      { max: 50, message: '企业编号不能超过50个字符', trigger: 'blur' }
    ],
    enterprise_name: [
      { required: true, message: '请输入企业名称', trigger: 'blur' },
      { max: 100, message: '企业名称不能超过100个字符', trigger: 'blur' }
    ],
    contact_name: [
      { required: true, message: '请输入联系人姓名', trigger: 'blur' },
      { max: 50, message: '联系人姓名不能超过50个字符', trigger: 'blur' }
    ],
    contact_phone: [
      { required: true, message: '请输入联系人电话', trigger: 'blur' },
      { max: 20, message: '联系人电话不能超过20个字符', trigger: 'blur' }
    ],
    login_phone: [{ required: true, message: '请输入登录手机号', trigger: 'blur' }],
    password: [
      { required: true, message: '请输入登录密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
    ]
  })

  const passwordRules = reactive<FormRules>({
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
    ]
  })

  const form = reactive<any>({
    id: 0,
    enterprise_code: '',
    enterprise_name: '',
    business_license: '',
    legal_person: '',
    region: [] as string[],
    province: '',
    city: '',
    district: '',
    address: '',
    contact_name: '',
    contact_phone: '',
    login_phone: '',
    password: '',
    owner_shop_id: null
  })

  const passwordForm = reactive({
    password: ''
  })

  const enterpriseList = ref<EnterpriseItem[]>([])

  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    {
      prop: 'enterprise_code',
      label: '企业编号',
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      prop: 'enterprise_name',
      label: '企业名称',
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      prop: 'contact_name',
      label: '联系人姓名',
      width: 120
    },
    {
      prop: 'contact_phone',
      label: '联系人电话',
      width: 130
    },
    {
      prop: 'login_phone',
      label: '登录手机号',
      width: 130
    },
    {
      prop: 'address',
      label: '所在地区',
      minWidth: 220,
      showOverflowTooltip: true,
      formatter: (row: EnterpriseItem) => {
        const parts: string[] = []
        if (row.province) parts.push(row.province)
        if (row.city) parts.push(row.city)
        if (row.district) parts.push(row.district)
        if (row.address) parts.push(row.address)
        return parts.length > 0 ? parts.join(' / ') : '-'
      }
    },
    {
      prop: 'owner_shop_name',
      label: '归属店铺',
      width: 150,
      showOverflowTooltip: true,
      formatter: (row: EnterpriseItem) => row.owner_shop_name || '平台'
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: EnterpriseItem) => {
        return h(ElSwitch, {
          modelValue: row.status,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用',
          inlinePrompt: true,
          disabled: !hasAuth('enterprise_customer:status'),
          'onUpdate:modelValue': (val: string | number | boolean) =>
            handleStatusChange(row, val as number)
        })
      }
    },
    {
      prop: 'created_at',
      label: '创建时间',
      width: 180,
      formatter: (row: EnterpriseItem) => formatDateTime(row.created_at)
    }
  ])

  // 操作列配置
  const getActions = (row: EnterpriseItem) => {
    const actions: any[] = []

    if (hasAuth('enterprise_customer:look_customer')) {
      actions.push({
        label: '账号列表',
        handler: () => viewCustomerAccounts(row),
        type: 'primary'
      })
    }

    if (hasAuth('enterprise_customer:card_authorization')) {
      actions.push({
        label: '卡授权',
        handler: () => manageCards(row),
        type: 'primary'
      })
    }

    if (hasAuth('enterprise_customer:device_authorization')) {
      actions.push({
        label: '设备授权',
        handler: () => manageDevices(row),
        type: 'primary'
      })
    }

    if (hasAuth('enterprise_customer:edit')) {
      actions.push({
        label: '编辑',
        handler: () => showDialog('edit', row),
        type: 'primary'
      })
    }

    if (hasAuth('enterprise_customer:update_pwd')) {
      actions.push({
        label: '修改密码',
        handler: () => showPasswordDialog(row),
        type: 'primary'
      })
    }

    return actions
  }

  onMounted(() => {
    getTableData()
    // 只有非代理账号才需要加载店铺列表
    if (!isAgentAccount.value) {
      loadShopList()
    }
  })

  // 加载店铺列表(获取所有店铺构建树形结构)
  const loadShopList = async () => {
    shopLoading.value = true
    try {
      const params: any = {
        page: 1,
        page_size: 9999 // 获取所有数据用于构建树形结构
      }
      const res = await ShopService.getShops(params)
      if (res.code === 0) {
        const items = res.data.items || []
        // 构建树形数据
        shopTreeData.value = buildTreeData(items)
      }
    } catch (error) {
      console.error('获取店铺列表失败:', error)
    } finally {
      shopLoading.value = false
    }
  }

  // 构建树形数据
  const buildTreeData = (items: ShopResponse[]) => {
    const map = new Map<number, ShopResponse & { children?: ShopResponse[] }>()
    const tree: ShopResponse[] = []

    // 先将所有项放入 map
    items.forEach((item) => {
      map.set(item.id, { ...item, children: [] })
    })

    // 构建树形结构
    items.forEach((item) => {
      const node = map.get(item.id)!
      if (item.parent_id && map.has(item.parent_id)) {
        // 有父节点，添加到父节点的 children 中
        const parent = map.get(item.parent_id)!
        if (!parent.children) parent.children = []
        parent.children.push(node)
      } else {
        // 没有父节点或父节点不存在，作为根节点
        tree.push(node)
      }
    })

    return tree
  }

  // 获取企业客户列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.page,
        page_size: pagination.pageSize,
        enterprise_name: searchForm.enterprise_name || undefined,
        login_phone: searchForm.login_phone || undefined,
        contact_phone: searchForm.contact_phone || undefined,
        status: searchForm.status
      }
      const res = await EnterpriseService.getEnterprises(params)
      if (res.code === 0) {
        enterpriseList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    getTableData()
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  // 刷新表格
  const handleRefresh = () => {
    getTableData()
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getTableData()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.page = newCurrentPage
    getTableData()
  }

  // 处理地区选择变化
  const handleRegionChange = (value: string[]) => {
    if (value && value.length === 3) {
      form.province = value[0]
      form.city = value[1]
      form.district = value[2]
    } else {
      form.province = ''
      form.city = ''
      form.district = ''
    }
  }

  const dialogType = ref('add')

  // 显示新增/编辑对话框
  const showDialog = (type: string, row?: EnterpriseItem) => {
    dialogType.value = type

    if (type === 'edit' && row) {
      form.id = row.id
      form.enterprise_code = row.enterprise_code
      form.enterprise_name = row.enterprise_name
      form.business_license = row.business_license
      form.legal_person = row.legal_person
      form.province = row.province
      form.city = row.city
      form.district = row.district
      // 设置地区级联选择器的值
      if (row.province && row.city && row.district) {
        form.region = [row.province, row.city, row.district]
      } else {
        form.region = []
      }
      form.address = row.address
      form.contact_name = row.contact_name
      form.contact_phone = row.contact_phone
      form.login_phone = row.login_phone
      form.owner_shop_id = row.owner_shop_id
    } else {
      form.id = 0
      form.enterprise_code = ''
      form.enterprise_name = ''
      form.business_license = ''
      form.legal_person = ''
      form.region = []
      form.province = ''
      form.city = ''
      form.district = ''
      form.address = ''
      form.contact_name = ''
      form.contact_phone = ''
      form.login_phone = ''
      form.password = ''
      // 如果是代理账号，自动设置归属店铺为当前登录用户的店铺
      form.owner_shop_id = isAgentAccount.value ? userStore.info.shop_id : null
    }

    // 重置表单验证状态
    nextTick(() => {
      formRef.value?.clearValidate()
    })

    dialogVisible.value = true
  }

  // 关闭对话框
  const handleCancel = () => {
    dialogVisible.value = false
    // 清除表单验证状态
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // 显示修改密码对话框
  const showPasswordDialog = (row: EnterpriseItem) => {
    currentEnterpriseId.value = row.id
    passwordForm.password = ''

    // 重置表单验证状态
    nextTick(() => {
      passwordFormRef.value?.clearValidate()
    })

    passwordDialogVisible.value = true
  }

  // 关闭修改密码对话框
  const handlePasswordCancel = () => {
    passwordDialogVisible.value = false
    // 清除表单验证状态
    nextTick(() => {
      passwordFormRef.value?.clearValidate()
    })
  }

  // 处理企业编码生成
  const handleCodeGenerated = (code: string) => {
    form.enterprise_code = code
  }

  // 提交表单
  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          const data: any = {
            enterprise_code: form.enterprise_code,
            enterprise_name: form.enterprise_name,
            business_license: form.business_license || undefined,
            legal_person: form.legal_person || undefined,
            province: form.province || undefined,
            city: form.city || undefined,
            district: form.district || undefined,
            address: form.address || undefined,
            contact_name: form.contact_name,
            contact_phone: form.contact_phone,
            owner_shop_id: form.owner_shop_id || undefined
          }

          if (dialogType.value === 'add') {
            data.login_phone = form.login_phone
            data.password = form.password
            await EnterpriseService.createEnterprise(data)
            ElMessage.success('新增成功')
          } else {
            await EnterpriseService.updateEnterprise(form.id, data)
            ElMessage.success('修改成功')
          }

          dialogVisible.value = false
          formEl.resetFields()
          getTableData()
        } catch (error) {
          console.error(error)
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 提交修改密码
  const handlePasswordSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
      if (valid) {
        passwordSubmitLoading.value = true
        try {
          await EnterpriseService.updateEnterprisePassword(currentEnterpriseId.value, {
            password: passwordForm.password
          })
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
          formEl.resetFields()
        } catch (error) {
          console.error(error)
        } finally {
          passwordSubmitLoading.value = false
        }
      }
    })
  }

  // 状态切换
  const handleStatusChange = async (row: EnterpriseItem, newStatus: number) => {
    const oldStatus = row.status
    // 先更新UI
    row.status = newStatus
    try {
      await EnterpriseService.updateEnterpriseStatus(row.id, { status: newStatus as 0 | 1 })
      ElMessage.success('状态切换成功')
    } catch (error) {
      // 切换失败，恢复原状态
      row.status = oldStatus
      console.error(error)
    }
  }

  // 查看客户账号
  const viewCustomerAccounts = (row: EnterpriseItem) => {
    router.push({
      path: `${RoutesAlias.EnterpriseCustomer}/customer-accounts/${row.id}`,
      query: { type: 'enterprise' }
    })
  }

  // 卡管理
  const manageCards = (row: EnterpriseItem) => {
    router.push({
      path: RoutesAlias.EnterpriseCards,
      query: { id: row.id }
    })
  }

  const manageDevices = (row: EnterpriseItem) => {
    router.push({
      path: RoutesAlias.EnterpriseDevices,
      query: { id: row.id }
    })
  }

  // 企业客户操作菜单项配置
</script>

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