<!--
 * @Author: xiejiang
 * @Date: 2024-11-28 15:01:02
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 23:13:39
 * @Description: 机构管理
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="h-full">
    <PageContainer
      :filter-conditions="filterConditions"
      :table-data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @search-change="handleSearch"
      @clear="handleClear(true)"
      @on-search="onSearch"
      @page-change="handlePage"
    >
      <template #header-left>
        <SearchWithButton
          :loading="loading"
          placeholder="机构名称"
          v-model="companyName"
          @clear="handleClear(null)"
          @on-search="handleSearch(searchParams)"
      /></template>

      <template #header-right>
        <div class="flex items-center justify-end gap-2">
          <t-button theme="primary" @click="handelEdit(null)">
            <template #icon><AddIcon /></template>
            添加机构</t-button
          >
        </div>
      </template>

      <template #operation="{ row }">
        <operate-btn v-if="row.companyStatus != 2" content="启用" @click="handelStatus(row, 2)"> </operate-btn>
        <operate-btn v-if="row.companyStatus != 1" content="详情" @click="handelDetail(row)"> </operate-btn>
        <operate-btn content="编辑" @click="handelEdit(row)"> </operate-btn>
        <operate-btn v-if="row.companyStatus == 2" content="停用" @click="handelStatus(row, 1)"> </operate-btn>
        <operate-btn v-if="row.companyStatus != 2" content="删除" @click="handelDel(row)"></operate-btn>
      </template>
    </PageContainer>
  </div>
</template>

<script setup lang="tsx" name="institution">
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from '@/components/PageFilters/interface/index'
import type { Pagination } from '@/components/PageContainer/interface/index'
import { statusTxt } from '@/utils/status'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import { ResCompany } from '@/api/interface/institution/index'
import {
  getCompanyList,
  postCompanyDelete,
  postCompanyDisable,
  postCompanyEnable
} from '@/api/modules/institution/index'
import { ResDictionary } from '@/api/interface/dectionory/index'
import { getGetDictDataByName } from '@/api/modules/dectionory/index'

defineOptions({
  name: 'institution'
})

const { setBreadcrumb } = useBasic()
const router = useRouter()

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '客户中心'
    },
    {
      title: '机构管理'
    }
  ])
})

onActivated(() => {
  getDictData()
  getData()
})

// 加载状态
const loading = ref(false)
// 分页配置
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

const companyName = ref('')

// 筛选项配置，type类型参考pageFilters组件下的ts定义
const filterConditions = ref<filterItemProp[]>([
  {
    label: '机构类型',
    prop: 'companyType',
    type: 'select',
    selectData: []
  },
  {
    label: '机构状态',
    prop: 'companyStatus',
    type: 'select',
    selectData: [
      { label: '编辑中', value: 1 },
      { label: '启用', value: 2 },
      { label: '停用', value: 3 }
    ]
  }
])

// 获取机构类型
const dictDatas = ref<ResDictionary[]>([])
const getDictData = () => {
  getGetDictDataByName({ dictName: '机构类型' }).then(res => {
    dictDatas.value = res.data
    filterConditions.value[0].selectData = dictDatas.value.map(v => {
      return { label: v.valueName || '', value: v.dictDataId || '' }
    })
  })
}

// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '机构名称', colKey: 'companyName' },
  {
    title: '机构类型',
    colKey: 'companyTypeName'
  },
  {
    title: '机构管理员',
    colKey: 'adminUserName',
    ellipsis: true,
    cell: (h, { row }) => {
      return (
        <t-tooltip content={`${row.adminUserName}(${row.adminUserMobile})`}>
          <div class='ellipsis'>
            <span>
              {row.adminUserName}({row.adminUserMobile})
            </span>
          </div>
        </t-tooltip>
      )
    }
  },
  {
    title: '服务到期时间',
    colKey: 'serviceTerminationTime',
    cell: (h, { row }) => {
      return (
        <t-tooltip content={row.serviceTerminationTime}>
          <div
            class={
              dayjs(row.serviceTerminationTime).isBefore(dayjs())
                ? 'ellipsis text-[var(--td-error-color-11)]'
                : 'ellipsis'
            }
          >
            {row.serviceTerminationTime}
          </div>
        </t-tooltip>
      )
    }
  },
  {
    title: '机构状态',
    colKey: 'companyStatus',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <div class={'dot ' + statusTxt(row.companyStatus)?.class}></div>
          <span class={statusTxt(row.companyStatus)?.class}>{statusTxt(row.companyStatus)?.title}</span>
        </div>
      )
    }
  },
  {
    title: '服务状态',
    colKey: 'serviceStatus',
    cell: (h, { row }) => {
      const html =
        row.serviceStatus == '0' ? (
          <span>-</span>
        ) : (
          <>
            <div class={'dot ' + statusTxt(row.serviceStatus + 1)?.class}></div>
            <span class={statusTxt(row.serviceStatus + 1)?.class}>{row.serviceStatus == 1 ? '服务中' : '已结束'}</span>
          </>
        )
      return <div class='flex items-center'>{html}</div>
    }
  },
  { title: '机构备注', colKey: 'remark' },
  { title: '添加时间', colKey: 'inputTime' },
  {
    title: '添加人',
    colKey: 'inputUserName',
    width: 120,
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <t-tooltip content={row.inputUserName}>
            <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis' : ''}>
              <span>{row.inputUserName || '-'}</span>
            </div>
          </t-tooltip>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 200 }
]

// 表格数据，自行规范ts
const tableData = ref<ResCompany[]>([])

// 获取表格数据接口
const getData = () => {
  loading.value = true
  const postData = {
    ...pagination.value,
    ...searchParams.value,
    companyName: companyName.value
  }
  getCompanyList(postData)
    .then(res => {
      tableData.value = res.data
      pagination.value.total = res?.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}
const searchParams = ref<Record<string, any>>({}) //   搜索筛选

// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

// 搜索
const onSearch = (params: Record<string, any>) => {
  searchParams.value = params
}

const handleClear = (flge: boolean | null) => {
  if (flge) {
    searchParams.value = {}
  }
  companyName.value = ''
  pagination.value.page = 1
  getData()
}

// 处理分页
const handlePage = (pageInfo: Pagination) => {
  pagination.value = { ...pagination.value, ...pageInfo }
  getData()
}

// 查看详情
const handelDetail = (row: ResCompany) => {
  router.push({
    name: 'institution-detail',
    query: {
      companyId: row.companyId
    }
  })
}
// 编辑新增
const handelEdit = (row: ResCompany | null) => {
  router.push({
    name: 'institution-edit',
    query: {
      companyId: row?.companyId
    }
  })
}

// 状态
const handelStatus = (row: ResCompany, status: number) => {
  const postCompanyStatus = status == 2 ? postCompanyEnable : postCompanyDisable
  const dialog = MessageBox(status, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postCompanyStatus({
        companyId: row?.companyId
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 删除
const handelDel = (row: ResCompany) => {
  const dialog = MessageBox(3, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postCompanyDelete({
        companyId: row?.companyId
      })
        .then(() => {
          MessagePlugin.success('操作成功')
          getData()
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}
</script>
