<template>
  <div>
    <el-form :model="searchForm" ref="searchRef" inline label-width="0">
      <el-form-item>
        <el-cascader
          :options="schoolOption"
          v-model="searchForm.schPlace"
          clearable
          filterable
          show-all-levels
          style="width: 300px"
          placeholder="选择驾校/场地"
          :props="{ expandTrigger: 'hover', multiple: false, checkStrictly: true }"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="searchForm.className"
          placeholder="请输入班型名称"
          clearable
          style="width: 180px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="searchForm.licenseType"
          placeholder="请选择驾照类型"
          clearable
          filterable
          @change="handleQuery"
        >
          <el-option
            v-for="item in getDictOptions(DICT_TYPE.LINCENSE_TYPE)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button plain @click="handleQuery" v-hasPermi="['school:class:search']">查询</el-button>
        <el-button plain @click="handleReset" v-hasPermi="['school:class:reset']">重置</el-button>
        <el-button
          type="primary"
          plain
          @click="handleOpenDialog('create', null)"
          v-hasPermi="['school:class:add']"
        >
          新增
        </el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete([])"
          v-hasPermi="['school:class:batch-delete']"
        >
          批量删除
        </el-button>
        <el-button
          type="warning"
          @click="handleBatchStatus"
          v-hasPermi="['school:class:batch-status']"
        >
          批量启/停用
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="tableList"
      v-loading="loading"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column
        v-for="col in columns"
        :prop="col.props"
        :key="col.props"
        :label="col.label"
        :width="col.width"
        show-overflow-tooltip
      />
      <el-table-column label="备注" width="260">
        <template #default="{ row }">
          <!-- <div v-dompurify-html="row.remark"></div> -->
          <el-popover placement="top" width="500px" trigger="click">
            <template #reference>
              <el-button type="primary" style="padding: 0" text>点击查看</el-button>
            </template>
            <div v-dompurify-html="row.remark"></div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="0"
            :inactive-value="1"
            :disabled="!checkPermi(['school:class:update'])"
            @change="handleChangeStatus(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120px">
        <template #default="{ row }">
          <el-button
            type="primary"
            style="padding: 0"
            text
            v-hasPermi="['school:class:update']"
            @click="handleOpenDialog('update', row.typeId)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            style="padding: 0"
            text
            v-hasPermi="['school:class:delete']"
            @click="handleRemove(row.typeId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="searchForm.pageSize"
      v-model:page="searchForm.pageNo"
      :total="total"
      @pagination="getList"
    />
    <Dialog title="批量修改" v-model="batchStatusDialogShow" width="400px">
      <el-form :model="statusForm" ref="statusRef" label-width="80px">
        <el-form-item label="选择状态" prop="status">
          <el-radio-group v-model="statusForm.status">
            <el-radio :label="0"> 启用 </el-radio>
            <el-radio :label="1"> 禁用 </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="batchStatusDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="handleSureStatus">确 认</el-button>
        </span>
      </template>
    </Dialog>

    <DialogClass ref="ClassDialog" :schoolOption="schoolOption" @success="getList" />
  </div>
</template>

<script setup name="Class">
import * as PlaceApi from '@/api/school/place'
import * as ClassApi from '@/api/school/class'
import DialogClass from './Comp/DialogClass.vue'
import { checkPermi } from '@/utils/permission'

import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { removeNullField } from '@/utils'

const message = useMessage() // 消息弹窗

const loading = ref(false)
const total = ref(0)

const tableList = ref([])

const searchForm = ref({
  schPlace: undefined,
  typeName: undefined,
  licenseType: undefined,
  pageNo: 1,
  pageSize: 20
})

const schoolOption = ref([])
// const selectNodes = ref([])

async function getSchoolList() {
  try {
    const data = await PlaceApi.getPlaceList({
      placeStatus: 0,
      schoolStatus: 0,
      isSearchSchool: true
    })
    schoolOption.value = data.schoolList.map((item) => ({
      value: item.schoolId,
      label: item.schoolName,
      children: data.placeList
        .filter((place) => item.schoolId === place.schoolId)
        .map((place) => ({
          value: place.placeId,
          label: place.name
        }))
    }))
  } catch {}
}

const columns = [
  { props: 'schoolName', label: '驾校', width: '100px' },
  { props: 'placeName', label: '场地' },
  { props: 'typeName', label: '班型名称' },
  { props: 'licenseType', label: '驾照类型', width: '100px' },
  { props: 'guidingPrice', label: '最新报价', width: '100px' }
  // { props: 'remark', label: '备注', width: '100px' }
]

function handleQuery() {
  searchForm.value.pageNo = 1
  getList()
}

async function getList() {
  loading.value = true
  try {
    const params = { ...searchForm.value }
    if (params.schPlace && params.schPlace.length) {
      params.schoolId = params.schPlace[0]
      if (params.schPlace.length == 2) {
        params.placeId = params.schPlace[1]
      }
    }
    delete params.schPlace
    const data = await ClassApi.getClassTypePage(removeNullField(params))
    tableList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const ClassDialog = ref()
function handleOpenDialog(type, id = null) {
  ClassDialog.value.open(type, id, searchForm.value.schPlace)
}

function handleReset() {
  searchForm.value = {
    schPlace: undefined,
    typeName: undefined,
    licenseType: undefined,
    pageNo: 1,
    pageSize: 20
  }
  getList()
}

async function handleBatchDelete(arr = []) {
  if (!arr.length && !selectRows.value.length) {
    message.info('请选择表格行！')
    return
  }
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ClassApi.batchDeleteClassType(arr || selectRows.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const selectRows = ref([])
function handleSelectionChange(selection) {
  selectRows.value = selection.map((item) => item.typeId)
}

function handleRemove(id) {
  handleBatchDelete([id])
}

async function handleChangeStatus(row) {
  try {
    // 删除的二次确认
    await message.confirm('是否确认修改状态')
    // 发起删除
    await ClassApi.updateClassTypeStatus({
      typeId: row.typeId,
      status: row.status
    })
    message.success('修改成功')
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status = row.status === 1 ? 0 : 1
  }
}

const batchStatusDialogShow = ref(false)
const statusForm = ref({ status: 0 })

function handleBatchStatus() {
  if (!selectRows.value.length) {
    message.info('请选择表格行！')
    return
  }
  statusForm.value.typeIdList = selectRows.value
  statusForm.value.status = 0
  batchStatusDialogShow.value = true
}

async function handleSureStatus() {
  try {
    await ClassApi.batchUpdateClassTypeStatus(statusForm.value)
    message.success('修改成功')
    batchStatusDialogShow.value = false
    // 刷新列表
    await getList()
  } catch {}
}

onMounted(() => {
  getSchoolList()
  getList()
})
</script>

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