<script setup lang="ts">
import type {
  MjEditFormProps,
  MjFormProps,
  MjGridProps,
} from '#/components/mj/mj-table'

import { useAccessStore, useUserStore } from '@vben/stores'

import { classService } from '#/api/service/class'
import MjTable, {
  mj_form_input,
  mj_form_select,
  mj_form_text,
} from '#/components/mj/mj-table'
import { pattern_phone } from '#/components/mj/mj-table/fmt'
import hud from '#/utils/hud'
import obj from '#/utils/obj'
import { grades } from '#/store/basic-data'

import { useItemRender } from '#/components/mj/mj-table-select'

import SelectUser from '../common/select-user/index.vue'
import { useSearchSchool } from '../hooks/search'

const props = defineProps<{
  // 是否要固定学校，不允许修改？
  fixedSchool?: any
  schoolId?: any
  schoolName?: any
}>()

const gridRef = ref()

const { userInfo } = storeToRefs(useUserStore())
const { accessCodes } = storeToRefs(useAccessStore())
const hasClassAddPermission = computed(() => {
  return accessCodes.value.includes('classAdd')
})
const hasClassEditPermission = computed(() => {
  return accessCodes.value.includes('classEdit')
})

const schoolRender = useSearchSchool({
  prepare: {
    gridRef,
    props,
    fixedName: 'school',
  },
})

const teacherRender = useItemRender({
  prepare: {
    gridRef,
  },
  cmp: SelectUser,
  setData: (data: any, _: any, value: any, label: any) => {
    // data.masterTeacherId = value // 插件会自动设置绑定的字段
    data.masterTeacherName = label
  },
  props: {
    cmpProps: {
      schoolPersonType: 1,
      fixedSchoolPersonType: true,
    },
    modal: { title: '请选择班主任' },
  },
})

// 表单
const addFields = [
  'name',
  'schoolId',
  'contact',
  'phone',
  'currencyFlag',
  'workMode',
  'gradeId',
  'masterTeacherId',
]
const editForm = {
  modal: {
    width: 720,
  },
  form: {
    titleWidth: 100,
    items: obj.joinObjs<any>(
      userInfo.value.isOnlyStaff || {
        required: true,
        field: 'schoolName',
        title: '学校',
        span: 12,
        itemRender: {
          name: mj_form_text,
          props: {
            linkedRender: schoolRender,
          },
        },
      },
      {
        required: true,
        field: 'name',
        title: '班级名称',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        field: 'contact',
        title: '联系人',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        pattern: pattern_phone,
        field: 'phone',
        title: '联系电话',
        span: 12,
        itemRender: {
          name: mj_form_input,
        },
      },
      {
        title: '年级',
        field: 'gradeId',
        span: 12,
        itemRender: {
          name: mj_form_select,
          props: {
            clearable: true,
            disabled: !!userInfo.value.gradeId,
          },
          options: grades,
        },
      },
      {
        field: 'masterTeacherId',
        title: '班主任',
        span: 12,
        itemRender: teacherRender,
      },
      {
        field: 'currencyFlag',
        title: '乐贝权益',
        span: 12,
        itemRender: {
          name: 'VxeSwitch',
        },
      },
      {
        field: 'workMode',
        title: '作业模式',
        span: 12,
        itemRender: {
          name: 'VxeSwitch',
          props: {
            openValue: 1,
            closeValue: 0,
            openLabel: '已开启',
            closeLabel: '未开启',
          },
        },
      },
    ),
    data: {},
  },
  addFields,
  updateFields: ['id', ...addFields],
  beforeSaveOrUpdate(formData: any) {
    formData.workMode ??= 0
    if (userInfo.value.isOnlyStaff) {
      formData.schoolId = userInfo.value.schoolId
    }
    if (userInfo.value.gradeId) {
      formData.gradeId = userInfo.value.gradeId
    }
    return formData
  },
  beforeEditFormShow(data, edit) {
    if (data.masterTeacherId) {
      teacherRender.props.selectedItems = [
        {
          id: data.masterTeacherId,
          name: data.masterTeacherName,
        },
      ]
    } else {
      teacherRender.props.selectedItems = []
    }
    if (userInfo.value.gradeId) {
      data.gradeId = userInfo.value.gradeId
    }
    data.workMode ??= 0
    if (edit) {
      gridRef.value.hideEditFormItems('schoolName')
      return data
    }
    gridRef.value.showEditFormItems('schoolName')
    return data
  },
} as MjEditFormProps

// 搜索表单
const searchForm = {
  items: obj.joinObjs(
    userInfo.value.isOnlyStaff || {
      title: '学校',
      field: 'schoolId',
      span: 6,
      itemRender: schoolRender,
    },
  ),
} as MjFormProps

// 表格
const grid = {
  columns: obj.joinObjs<any>(
    {
      title: '操作',
      width: 160,
      slots: {
        default: 'operation',
      },
    },
    { type: 'seq' },
    {
      field: 'name',
      title: '班级名称',
    },
    userInfo.value.isOnlyStaff || { field: 'schoolName', title: '学校' },
    {
      field: 'gradeName',
      title: '年级',
    },
    {
      title: '乐贝权益',
      slots: {
        default: 'currencyFlag',
      },
    },
    {
      title: '作业模式',
      slots: {
        default: 'workMode',
      },
    },
    {
      field: 'contact',
      title: '联系人',
    },
    {
      field: 'phone',
      title: '电话',
    },
  ),
  beforeLoadData(params) {
    if (userInfo.value.isSpStaff) {
      // 如果是服务商人员
      params.providerId = userInfo.value.providerId
    } else if (userInfo.value.isStaff) {
      // 如果是学校人员
      params.schoolId = userInfo.value.schoolId
    }
    return params
  },
} as MjGridProps

// 乐贝权益
function currencyFlagChange(row: any) {
  const oldFlag = !row.currencyFlag
  classService
    .saveOrUpdate({
      id: row.id,
      currencyFlag: row.currencyFlag,
    })
    .catch(() => {
      row.currencyFlag = oldFlag
    })
}

// 作业模式
function workModeChange(row: any) {
  const oldMode = row.workMode === 1 ? 0 : 1
  classService
    .saveOrUpdate({
      id: row.id,
      workMode: row.workMode,
    })
    .catch(() => {
      row.workMode = oldMode
    })
}

function updateScreenLock(row: any, status: 0 | 1) {
  const option = status === 1 ? '锁屏' : '解锁'
  hud.confirmLoad(`确定${option}【${row.name}】吗？`, {
    task: async () => {
      await classService.lockScreen({
        classId: row.id,
        status,
      })
      gridRef.value?.reload()
    },
    hideError: true,
    option,
    hideSuccess: false,
  })
}
</script>

<template>
  <div class="class-mgr g-container">
    <MjTable
      ref="gridRef"
      :search-form="searchForm"
      :edit-form="editForm"
      :grid="grid"
      :hide-add="!hasClassAddPermission"
      :hide-edit="!hasClassEditPermission"
      :service="classService"
      v-bind="$attrs"
    >
      <template #operation="{ row }">
        <el-button
          v-if="row.screenLock === 1"
          type="success"
          @click="updateScreenLock(row, 0)"
        >
          解锁
        </el-button>
        <el-button
          v-else
          type="danger"
          @click="updateScreenLock(row, 1)"
        >
          锁屏
        </el-button>
      </template>
      <template #currencyFlag="{ row }">
        <el-switch
          v-model="row.currencyFlag"
          @click="currencyFlagChange(row)"
        />
      </template>
      <template #workMode="{ row }">
        <vxe-switch
          v-model="row.workMode"
          :close-value="0"
          close-label="未开启"
          :open-value="1"
          open-label="已开启"
          @change="workModeChange(row)"
        />
      </template>
    </MjTable>
  </div>
</template>

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