<!-- 餐饮公司关系管理 -->
<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
  <div class="user-page art-full-height">
    <!-- 搜索栏 -->
    <UserSearch
      v-model="searchForm"
      @search="handleSearch"
      @reset="resetSearchParams"
      :selectList="selectList"
      :user-list="userList"
      labelPosition="left"
    ></UserSearch>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" @refresh="refreshData">
        <template #left>
          <ElButton type="primary" @click="showDialog('add')" v-ripple v-auth="120201">新增餐饮公司关系</ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >

        <template #follow_list="scope">
          <el-row>
            <el-col :sm="20">
              <FollowProver :follow_list="scope.row.follow_list" />
            </el-col>
            <el-col :sm="4">
              <ElButton size="small" @click="follow(scope.row)" v-ripple v-auth="120301" type="primary">跟进</ElButton>
            </el-col>
          </el-row>
        </template>

      </ArtTable>

      <!-- 餐饮公司关系弹窗 -->
      <UserDialog
        v-model:visible="dialogVisible"
        :type="dialogType"
        :user-data="currentUserData"
        :selectList="selectList"
        @submit="handleDialogSubmit"
      />

      <!--   跟进弹窗   -->
      <FollowDialog
        v-model:visible="followDialogVisible"
        :user-data="currentUserData"
        :type="'company'"
        :first_id="currentUserData.company_id || 0"
        :second_id="currentUserData.id || 0"
        :selectList="selectList"
        @submit="handleDialogSubmit"
      />
    </ElCard>

    <!--   跟进详情显示   -->
    <el-drawer
        v-model="drawer"
        direction="rtl"
        size="60%"
    >
      <template #header>
        <span style="font-size: 20px; font-weight: bold;">校方联系人</span>
      </template>
      <ElRow>
        <ElCol :sm="8">
          <ElRow class="detail">

            <el-col>
              <label>关系人:</label> <span>{{ currentRow.name }}</span>
            </el-col>

            <el-col>
              <label>手机:</label> <span>{{ currentRow.phone }}</span>
            </el-col>

            <el-col>
              <label>微信:</label> <span>{{ currentRow.weixin }}</span>
            </el-col>

            <el-col>
              <label>职位:</label> <span>{{ currentRow.position }}</span>
            </el-col>

            <el-col>
              <label>餐饮公司:</label> <span>{{ currentRow.company_name }}</span>
            </el-col>

            <el-col>
              <label>备注:</label> <span>{{ currentRow.memo }}</span>
            </el-col>

          </ElRow>
        </ElCol>
        <ElCol :sm="16">
          <FollowDrawer :first_id="currentRow.company_id" :second_id="currentRow.id" type="company" :uid="drawerUid"/>
        </ElCol>
      </ElRow>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import {ElMessageBox, ElMessage, ElTag, ElImage, ElButton} from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import UserSearch from './modules/user-search.vue'
  import UserDialog from './modules/user-dialog.vue'
  import { companyRelationApi } from '@/api/companyRelationApi'
  import { useUserStore } from '@/store/modules/user'
  import {followApi} from "@/api/followApi";
  import {commonApi} from "@/api/commonApi";
  import { detectDeviceType } from '@/utils'
  import FollowProver from "@/components/custom/FollowProver.vue";

  defineOptions({ name: 'companyRelation' })

  type CompanyContactItem = Api.Company.contactItem
  const { list } = companyRelationApi

  // 弹窗相关
  const dialogType = ref<Form.DialogType>('add')
  const dialogVisible = ref(false)
  const followDialogVisible = ref(false)
  const currentUserData = ref<Partial<CompanyContactItem>>({})

  // 选中行
  const selectedRows = ref<CompanyContactItem[]>([])

  // 搜索表单
  const searchForm = ref({
    name: '',
    phone: '',
    company_id: parseInt(<string>useRoute().query.company_id)  || '',
    date: useRoute().query.date || '',
    last_user_id:0,
    last_date:[],
    bind_user_id:0,
  })

  const userList = ref<Api.Common.SelectInfo[]>([])
  const selectList = ref<Api.Common.SelectRelationInfo[]>([])
  const getSelectList = async () => {
    await commonApi.selectList(['company_relation', 'user']).then(res => {
      selectList.value = res.company_relation || []
      userList.value = res.user || []
    })
  }
  getSelectList()

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable<CompanyContactItem>({
    // 核心配置
    core: {
      apiFn: list,
      apiParams: {
        current: 1,
        size: 20,
        ...searchForm.value
      },
      // 排除 apiParams 中的属性
      excludeParams: ['daterange'],
      columnsFactory: () => [
        {
          prop: 'name', label: '关系人', formatter: (row) => {
            return h(ElButton, {
              type: 'primary',
              link: true,
              onClick: () => showDrawer(row),
              style: {"text-decoration": 'underline'}
            }, () => row.name)
          }
        },
        { prop: 'company_name', label: '餐饮公司' },
        { prop: 'phone', label: '手机号' },
        { prop: 'weixin', label: '微信号' },
        { prop: 'position', label: '职位' },
        {prop: 'follow_list', label: '跟进记录', useSlot: true, width: 400},
        { prop:'last_user_name', label:'最后一次跟进人' },
        { prop:'last_date', label:'最后一次跟进时间' },
        { prop: 'memo', label: '备注', showOverflowTooltip: true },
        {
          prop: 'operation',
          label: '操作',
          width: detectDeviceType() == 'Mobile' ? 60 : 120,
          fixed: 'right', // 固定列
          formatter: (row) =>
            useUserStore().checkAuth(120202) &&
            h('div', [
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => showDialog('edit', row)
              }),
              useUserStore().checkAuth(120203) &&
                h(ArtButtonTable, {
                  type: 'delete',
                  onClick: () => deleteUser(row)
                })
            ])
        }
      ]
    }
  })

  /**
   * 搜索处理
   * @param params 参数
   */
  const handleSearch = (params: Record<string, any>) => {
    Object.assign(searchParams, { ...params })
    getData()
  }

  const detaltValue = <Api.Company.contactItem>{
    id: 0,
    name: '',
    company_id: 0, // 餐饮公司ID,
    company_name: '',
    phone: '',
    weixin: '',
    position: '',
    memo: '',
    last_user_id: 0,
    last_user_name: '',
    last_date: '',
  }

  const currentRow = ref<Api.Company.contactItem>({...detaltValue})
  const drawer = ref(false)

  const showDrawer = (row: Api.Company.contactItem): void => {
    drawer.value = true;
    currentRow.value = row
  }

  /**
   * 显示餐饮公司关系弹窗
   */
  const showDialog = (type: Form.DialogType, row?: CompanyContactItem): void => {
    dialogType.value = type
    currentUserData.value = row || {}
    nextTick(() => {
      dialogVisible.value = true
    })
  }

    /**
   * 显示跟进弹窗
   */
  const follow = (row: CompanyContactItem): void => {
    currentUserData.value = row || {}
    nextTick(() => {
      followDialogVisible.value = true
    })
  }

  /**
   * 删除餐饮公司关系
   */
  const deleteUser = (row: CompanyContactItem): void => {
    ElMessageBox.confirm(`确定要注销该餐饮公司关系吗？`, '注销餐饮公司关系', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      companyRelationApi.delete({ id: row.id })
      // 延迟更新 不然数据可能没更新
      setTimeout(() => {
        refreshData()
      }, 1000)
    })
  }

  const drawerUid = ref(0)

  /**
   * 处理弹窗提交事件
   */
  const handleDialogSubmit = async () => {
    try {
      dialogVisible.value = false
      followDialogVisible.value = false
      drawerUid.value++
      await getSelectList()
      // 延迟更新 不然数据可能没更新
      setTimeout(() => {
        refreshData()
      }, 1000)
    } catch (error) {
      console.error('提交失败:', error)
    }
  }

  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: CompanyContactItem[]): void => {
    selectedRows.value = selection
  }
</script>

<style lang="scss" scoped>
  .user-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        margin-left: 0;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
  .detail {
    //padding-top: 20px;
    font-size: 14px;
    .el-col {
      margin-bottom: 30px;
      label {
        font-weight: bold;
        margin-right: 5px;
      }
    }
  }
</style>
