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

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

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" @refresh="refreshData">
        <template #left>
          <ElButton type="primary" @click="edit()" v-ripple v-auth="120101">新增校区</ElButton>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
          :loading="loading"
          :data="data"
          :columns="columns"
          :pagination="pagination"
          @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"-->
      <!--        :role-list="roleList"-->
      <!--        @submit="handleDialogSubmit"-->
      <!--      />-->
    </ElCard>

    <el-drawer
        v-model="drawer"
        direction="rtl"
        size="70%"
    >
      <template #header>
        <span style="font-size: 20px; font-weight: bold;">{{ currentRow.name }}</span>
      </template>
      <ElRow>
        <el-col :sm="10">
          <ElRow class="detail">

            <el-col :sm="12">
              <label>在校人数:</label> <span>{{ currentRow.person_num }}</span>
            </el-col>

            <el-col :sm="12">
              <label>地区:</label> <span>{{
                [currentRow.province, currentRow.city, currentRow.area].join(' / ')
              }}</span>
            </el-col>

            <el-col :span=24>
              <label>详细地址:</label> <span>{{ currentRow.address }}</span>
            </el-col>

            <el-col :sm="12">
              <label>负责人:</label> <span>{{ currentRow.bind_user_id }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否有饿了么校内站:</label> <span>{{ currentRow.is_eleme_in_school ? '有' : '无' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否有饿了么校外站:</label> <span>{{ currentRow.is_eleme_out_school ? '有' : '无' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否有美团校内站:</label> <span>{{ currentRow.is_meituan_in_school ? '有' : '无' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否有美团校外站:</label> <span>{{ currentRow.is_meituan_out_school ? '有' : '无' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否能上楼:</label> <span>{{ currentRow.can_go_upstairs ? '不能' : '能' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否合作:</label> <span>{{ currentRow.is_cooperate ? '已合作' : '未合作' }}</span>
            </el-col>

            <el-col :sm="12">
              <label>是否允许骑电动车:</label> <span>{{ currentRow.can_ride ? '不能' : '能' }}</span>
            </el-col>

            <el-col :span=24>
              <label>宿舍分布情况:</label> <span>{{ currentRow.dormitory_distribution }}</span>
            </el-col>

            <el-col :span=24>
              <label>校门口取餐点离宿舍情况:</label> <span>{{ currentRow.qucan_station_distribution }}</span>
            </el-col>

            <el-col :span=24>
              <label>校外商圈情况:</label> <span>{{ currentRow.out_business_description }}</span>
            </el-col>

            <el-col :span=24>
              <label>负责人:</label> <span>{{ currentRow.bind_user_name }}</span>
            </el-col>

            <el-col v-auth="120200">
              <label>校方关系人:</label>
              <el-table border :data="schoolInfo?.canteens || []" style="width: 100%; margin-top: 10px">
                <el-table-column prop="name" label="食堂" />
                <el-table-column prop="username" label="食堂经理"  />
                <el-table-column prop="phone" label="手机号" />
                <el-table-column prop="weixin" label="微信号" />
              </el-table>
            </el-col>

            <el-col v-auth="130100">
              <label>食堂信息:</label>
              <el-table border :data="schoolInfo?.relations || []" style="width: 100%; margin-top: 10px">
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="position" label="职位"  />
                <el-table-column prop="phone" label="手机号" />
                <el-table-column prop="weixin" label="微信号" />
              </el-table>
            </el-col>

          </ElRow>
        </el-col>
        <el-col :sm="14">
          <FollowDrawer :first_id="currentRow.id" :second_id="0" type="school" :uid="drawerUid"/>
        </el-col>
      </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, ElInput} from 'element-plus'
import {useTable} from '@/composables/useTable'
import {schoolApi} from '@/api/schoolApi'
import UserSearch from './user-search.vue'
import {useUserStore} from '@/store/modules/user'
import EmojiText from '@utils/ui/emojo'
import {router} from '@/router'
import {RoutesAlias} from '@/router/routesAlias'
import {followApi} from "@/api/followApi";
import {schoolRelationApi} from "@/api/schoolRelationApi";
import {commonApi} from "@/api/commonApi";
import { detectDeviceType } from '@/utils'
import FollowProver from "@/components/custom/FollowProver.vue";

defineOptions({name: 'User'})

const {list} = schoolApi
const drawer = ref(false)
const followDialogVisible = ref(false)

// 搜索表单
const searchForm = ref({
  name: '',
  is_cooperate: -1,
  address: []
})

const defaultValue = <Api.School.SchoolListItem>{
  id: 0,
  name: '',
  province: '',
  city: '',
  area: '',
  address: '',
  person_num: '',
  bind_user_id: 0,
  is_eleme_in_school: 0,
  is_eleme_out_school: 0,
  is_meituan_in_school: 0,
  is_meituan_out_school: 0,
  can_go_upstairs: 0,
  is_cooperate: 0,
  can_ride: 0,
  dormitory_distribution: '',
  qucan_station_distribution: '',
  out_business_description: '',
  memo: ''
}

const currentRow = ref<Api.School.SchoolListItem>({...defaultValue})

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

const drawerUid = ref(0)

/**
 * 处理弹窗提交事件
 */
const handleDialogSubmit = async () => {
  followDialogVisible.value = false
  drawerUid.value++
  getData()
}

const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  resetSearchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable<Api.School.SchoolListItem>({
  // 核心配置
  core: {
    apiFn: list,
    apiParams: {
      current: 1,
      size: 20,
      ...searchForm.value
    },
    // 排除 apiParams 中的属性
    excludeParams: [],
    columnsFactory: () => [
      {
        prop: 'name', label: '学校（校区）', showOverflowTooltip: true, formatter: (row) => {
          return h(ElButton, {
            type: 'primary',
            link: true,
            onClick: () => showDrawer(row),
            style: {"text-decoration": 'underline'}
          }, () => row.name)
        }
      },
      {prop: 'area', label: '地区', formatter: (row) => row.province + row.city + row.area},
      {prop: 'address', label: '详细地址'},
      {
        prop: 'canteen',
        label: '关联食堂',
        // sortable: true,
        // checked: false, // 隐藏列
        formatter: (row) => {
          return h(ElButton, {type: 'primary', size: 'small', onClick: () => showCanteen(row)}, () => '查看')
        }
      },
      {
        prop: 'concat',
        label: '关系人',
        formatter: (row) => {
          return h(ElButton, {type: 'primary', size: 'small', onClick: () => showContact(row)}, () => '查看')
        }
      },
      {
        prop: 'is_cooperate',
        label: '合作状态',
        formatter: (row) => {
          return h(ElTag, {type: row.is_cooperate ? 'success' : 'danger'}, () =>
              row.is_cooperate ? '已合作' : '未合作'
          )
        }
      },
      {prop: 'person_num', label: '在校人数'},
      // {prop: 'is_eleme_in_school', label: '是否有饿了么校内站', useSlot: true},
      {prop: 'is_eleme_in_school', label: '是否有饿了么校内站', formatter: (row) => {
          return h(ElTag, {type: row.is_eleme_out_school ? 'success' : 'danger'}, () =>
              row.is_eleme_out_school ? '有' : '无'
          )
        }},
      {
        prop: 'is_eleme_out_school',
        label: '是否有饿了么校外站',
        formatter: (row) => {
          return h(ElTag, {type: row.is_eleme_out_school ? 'success' : 'danger'}, () =>
              row.is_eleme_out_school ? '有' : '无'
          )
        }
      },
      {
        prop: 'is_meituan_in_school',
        label: '是否有美团校内站',
        formatter: (row) => {
          return h(ElTag, {type: row.is_meituan_in_school ? 'success' : 'danger'}, () =>
              row.is_meituan_in_school ? '有' : '无'
          )
        }
      },
      {
        prop: 'is_meituan_out_school',
        label: '是否有美团校外站',
        formatter: (row) => {
          return h(ElTag, {type: row.is_meituan_out_school ? 'success' : 'danger'}, () =>
              row.is_meituan_out_school ? '有' : '无'
          )
        }
      },
      {
        prop: 'can_go_upstairs',
        label: '是否能上楼',
        formatter: (row) => {
          return h(ElTag, {type: row.can_go_upstairs ? 'success' : 'danger'}, () =>
              row.can_go_upstairs ? '能' : '不能'
          )
        }
      },
      {
        prop: 'can_ride',
        label: '是否允许骑电动车',
        formatter: (row) => {
          return h(ElTag, {type: row.can_ride ? 'success' : 'danger'}, () =>
              row.can_ride ? '能' : '不能'
          )
        }
      },
      {prop: 'follow_list', label: '跟进记录', useSlot: true, width: 400},
      { prop: 'dormitory_distribution', label: '宿舍分布情况', showOverflowTooltip: true },
      { prop: 'qucan_station_distribution', label: '校门口取餐点离宿舍情况', showOverflowTooltip: true },
      {prop: 'out_business_description', label: '校外商圈情况', showOverflowTooltip: true},
      {prop: 'memo', label: '备注', showOverflowTooltip: true},
      {
        prop: 'operation',
        label: '操作',
        width: detectDeviceType() == 'Mobile' ? 60 : 120,
        fixed: 'right', // 固定列
        formatter: (row) =>
            h('div', [
              h(ArtButtonTable, {
                type: 'view',
                onClick: () => view(row.id)
              }),
              useUserStore().checkAuth(110202) && h(ArtButtonTable, {
                type: 'edit',
                onClick: () => edit(row.id)
              }),
            ])
      }
    ]
  }
})


const doUpdateAttr = (scope: any) => {
  if (!scope.row.id) {
    return
  }
  schoolApi
      .updateAttr({id: scope.row.id, attr: scope.prop, value: scope.row[scope.prop]})
      .then(() => {
        ElMessage.success(`${EmojiText[200]} 修改成功`)
      })
}

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

/**
 * 编辑
 */
const edit = (id?: number): void => {
  router.push({
    path: RoutesAlias.SchoolEdit,
    query: {
      id: id
    }
  })
}

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

/**
 * 查看
 */
const view = (id: number): void => {
  router.push({
    path: RoutesAlias.SchoolInfo,
    query: {
      id: id
    }
  })
}

const schoolInfo = ref<Api.School.SchoolInfo>()

const showDrawer = (row: Api.School.SchoolListItem): void => {
  drawer.value = true;
  currentRow.value = row
  schoolApi.info(row.id).then((res) => {
    schoolInfo.value = res
  })
}

const showContact = (row: Api.School.SchoolListItem):void => {
  router.push({
    path: RoutesAlias.SchoolRelation,
    query: {
      school_id: row.id
    }
  })
}

const showCanteen = (row: Api.School.SchoolListItem):void => {
  router.push({
    path: RoutesAlias.CanteenList,
    query: {
      school_id: row.id
    }
  })
}

/**
 * 删除
 */
const deleteUser = (id: number): void => {
  ElMessageBox.confirm(`确定要删除该学校吗？`, '删除学校', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    schoolApi.delete({id: id}).then(() => {
      ElMessage.success(`${EmojiText[200]} 删除成功`)
      setTimeout(() => {
        getData()
      }, 1000)
    })
  })
}
</script>

<style lang="scss" scoped>
.el-button::after {
  content: none !important;
}
.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;
  padding-right: 5px;
  .el-col {
    margin-bottom: 30px;
    label {
      font-weight: bold;
      margin-right: 5px;
    }
  }
}
</style>
