<template>
  <ArtTableFullScreen>
    <div class="enterprise-customer-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="searchForm"
        :items="searchFormItems"
        :show-expand="true"
        @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="50%"
        >
          <ElForm ref="formRef" :model="form" :rules="rules" label-width="100px">
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="企业编号" prop="enterprise_code">
                  <ElInput
                    v-model="form.enterprise_code"
                    placeholder="请输入企业编号或点击生成"
                    :disabled="dialogType === 'edit'"
                    clearable
                  >
                    <template #append>
                      <ElButton v-if="dialogType === 'add'" @click="handleGenerateEnterpriseCode"
                        >生成编码</ElButton
                      >
                    </template>
                  </ElInput>
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="企业名称" prop="enterprise_name">
                  <ElInput v-model="form.enterprise_name" placeholder="请输入企业名称" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="法人代表" prop="legal_person">
                  <ElInput v-model="form.legal_person" placeholder="请输入法人代表" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="12">
                <ElFormItem label="营业执照号" prop="business_license">
                  <ElInput v-model="form.business_license" placeholder="请输入营业执照号" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow :gutter="20">
              <ElCol :span="12">
                <ElFormItem label="所在地区" prop="region">
                  <ElCascader
                    v-model="form.region"
                    :options="regionData as CascaderOption[]"
                    placeholder="请选择省/市/区"
                    clearable
                    filterable
                    style="width: 100%"
                    @change="handleRegionChange"
                  />
                </ElFormItem>
              </ElCol>
              <!-- 只有非代理账号才显示归属店铺选择 -->
              <ElCol :span="12" v-if="!isAgentAccount">
                <ElFormItem label="归属店铺" prop="owner_shop_id">
                  <ElCascader
                    v-model="form.owner_shop_id"
                    :options="shopCascadeOptions"
                    :props="shopCascadeProps"
                    placeholder="请选择归属店铺"
                    filterable
                    clearable
                    style="width: 100%"
                    @focus="handleOwnerShopFocus"
                    @visible-change="handleOwnerShopVisibleChange"
                    @change="handleShopChange"
                  />
                </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, onActivated } from 'vue'
  import { useRouter } from 'vue-router'
  import { RoutesAlias } from '@/router/routesAlias'
  import { EnterpriseService, ShopService } from '@/api/modules'
  import { ElMessage, ElSwitch, ElCascader } from 'element-plus'
  import type { CascaderOption, CascaderValue, FormInstance, FormRules } from 'element-plus'
  import type { EnterpriseItem } 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 { generateEnterpriseCode } from '@/utils/codeGenerator'
  import { formatDateTime } from '@/utils/business/format'
  import { regionData } from '@/utils/constants/regionData'
  import { STATUS_SELECT_OPTIONS } from '@/config/constants'

  defineOptions({ name: 'EnterpriseCustomer' })

  const { hasAuth } = useAuth()
  const canUpdateEnterpriseCustomerStatus = hasAuth('enterprise_customer:status')
  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 shopList = ref<any[]>([])
  // 店铺级联选择相关
  const shopCascadeOptions = ref<any[]>([])
  const shopCascadeProps = {
    lazy: true,
    checkStrictly: true,
    lazyLoad: async (node: any, resolve: any) => {
      const { level, value } = node
      const parentId = level === 0 ? undefined : value

      try {
        const res = await ShopService.getShopsCascade({ parent_id: parentId })
        if (res.code === 0) {
          const nodes = (res.data || []).map((item: any) => ({
            value: item.id,
            label: item.shop_name,
            leaf: !item.has_children
          }))
          resolve(nodes)
        } else {
          resolve([])
        }
      } catch (error) {
        console.error('加载店铺级联数据失败:', error)
        resolve([])
      }
    },
    value: 'value',
    label: 'label',
    children: 'children'
  }

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

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

  // 搜索表单配置
  const searchFormItems = computed<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: 'owner_shop_id',
      type: 'select',
      options: shopList.value.map((shop) => ({
        label: shop.shop_name,
        value: shop.id
      })),
      config: {
        clearable: true,
        filterable: true,
        remote: true,
        remoteMethod: handleSearchOwnerShop,
        placeholder: '请输入店铺名称搜索',
        reserveKeyword: true
      }
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      options: STATUS_SELECT_OPTIONS,
      config: {
        clearable: true,
        placeholder: '请选择状态'
      }
    }
  ])

  // 分页
  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' },
    ...(canUpdateEnterpriseCustomerStatus ? [{ 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 || '平台'
    },
    ...(canUpdateEnterpriseCustomerStatus
      ? [
          {
            prop: 'status',
            label: '状态',
            width: 100,
            formatter: (row: EnterpriseItem) => {
              return h(ElSwitch, {
                modelValue: row.status,
                activeValue: 1,
                inactiveValue: 0,
                activeText: '启用',
                inactiveText: '禁用',
                inlinePrompt: true,
                '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: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(() => {
    handleSearchOwnerShop('')
    getTableData()
  })

  onActivated(() => {
    getTableData()
  })

  // 加载店铺列表 - 改用级联查询
  const loadShopList = async () => {
    if (shopLoading.value) return

    shopLoading.value = true
    try {
      const res = await ShopService.getShopsCascade({ parent_id: undefined })
      if (res.code === 0) {
        shopCascadeOptions.value = (res.data || []).map((item: any) => ({
          value: item.id,
          label: item.shop_name,
          leaf: !item.has_children
        }))
      }
    } catch (error) {
      console.error('获取店铺列表失败:', error)
    } finally {
      shopLoading.value = false
    }
  }

  const handleOwnerShopFocus = async () => {
    if (isAgentAccount.value) return
    await loadShopList()
  }

  const handleOwnerShopVisibleChange = async (visible: boolean) => {
    if (!visible) return
    await handleOwnerShopFocus()
  }

  const handleSearchOwnerShop = async (query: string = '') => {
    try {
      const res = await ShopService.getShops({
        page: 1,
        page_size: 20,
        shop_name: query || undefined,
        status: 1
      })
      if (res.code === 0) {
        shopList.value = res.data.items || []
      }
    } catch (error) {
      console.error('搜索归属店铺失败:', error)
    }
  }

  // 处理店铺选择变化
  const handleShopChange = (value: any) => {
    if (Array.isArray(value) && value.length > 0) {
      form.owner_shop_id = value[value.length - 1]
    } else {
      form.owner_shop_id = null
    }
  }

  // 获取企业客户列表
  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,
        owner_shop_id: searchForm.owner_shop_id ?? 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: CascaderValue | null | undefined) => {
    const region = Array.isArray(value) ? value.map(String) : []
    if (region.length === 3) {
      form.province = region[0]
      form.city = region[1]
      form.district = region[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 handleGenerateEnterpriseCode = () => {
    form.enterprise_code = generateEnterpriseCode()
    ElMessage.success('编码生成成功')
  }

  // 提交表单
  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' }
    })
  }

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

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