<template>
  <el-dialog
    v-model="showDialog"
    :title="t('addBindingPersonnel')"
    width="50%"
    class="diy-dialog-wrap"
    :destroy-on-close="true"
  >
    <el-form
      :inline="true"
      :model="lessonCourseTeachingTable.searchParam"
      ref="searchFormRef"
    >
      <el-form-item :label="t('userName')" prop="title">
        <el-input
          v-model="lessonCourseTeachingTable.searchParam.name"
          :placeholder="t('userName')"
        />
      </el-form-item>
      <el-form-item :label="t('userPhone')" prop="status">
        <el-input
          v-model="lessonCourseTeachingTable.searchParam.phone"
          :placeholder="t('userPhone')"
        />
      </el-form-item>
	  
	  
	  
	  <el-form-item label="角色" prop="role_id">
	        <el-select
	          class="input-width"
	          v-model="lessonCourseTeachingTable.searchParam.role_id"
	          clearable
	          placeholder="请选择角色"
	        >
	          <el-option label="请选择" value=""></el-option>
	          <el-option
	            v-for="(item, index) in roleIdList"
	            :key="index"
	            :label="item['role_name']"
	            :value="item['role_id']"
	          />
	        </el-select>
	      </el-form-item>
	  
	     <el-form-item label="部门">
	        <el-select
	          class="input-width"
	          v-model="lessonCourseTeachingTable.searchParam.dept_id"
	          clearable
	          placeholder="请选择部门"
	        >
	          <el-option label="请选择" value=""></el-option>
	          <el-option
	            v-for="(item, index) in deptIdList"
	            :key="index"
	            :label="item['department_name']"
	            :value="item['id']"
	          />
	        </el-select>
	      </el-form-item>
		  
		  
      <el-form-item>
        <el-button type="primary" @click="loadLessonCourseTeachingList()">{{
          t('search')
        }}</el-button>
        <el-button @click="resetForm(searchFormRef)">{{
          t('reset')
        }}</el-button>
      </el-form-item>
    </el-form>

    <div class="mt-[10px]">
      <el-table
	    ref="lessonCourseTableRef"
        :data="lessonCourseTeachingTable.data"
        size="large"
        v-loading="lessonCourseTeachingTable.loading"
        @selection-change="handleSelectionChange"
      >
        <template #empty>
          <span>{{
            !lessonCourseTeachingTable.loading ? t('emptyData') : ''
          }}</span>
        </template>
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="name"
          :label="t('userName')"
          min-width="70"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="phone"
          :label="t('userPhone')"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('userStatus')"
          min-width="100"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <div v-if="row.status == 1">待审核</div>
            <div v-if="row.status == 2">已审核</div>
            <div v-if="row.status == 3">已禁用</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          :label="t('userCreateTime')"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="update_time"
          :label="t('userUpdateTime')"
          min-width="150"
          :show-overflow-tooltip="true"
        />


      </el-table>
      <div class="mt-[16px] flex justify-end">
        <el-pagination
          v-model:current-page="lessonCourseTeachingTable.page"
          v-model:page-size="lessonCourseTeachingTable.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="lessonCourseTeachingTable.total"
          @size-change="loadLessonCourseTeachingList()"
          @current-change="loadLessonCourseTeachingList"
        />
      </div>
    </div>

    <!--    <el-form-item :label="t('bindingModule')" style="margin-top: 15px;">-->
    <!--      <el-select class="w-[280px]" v-model="binding_module" clearable :placeholder="t('bindingModule')">-->
    <!--        <el-option label="课程教学大纲" value="1" />-->
    <!--        <el-option label="跳绳教案库" value="2" />-->
    <!--        <el-option label="增高教案库" value="3" />-->
    <!--        <el-option label="篮球教案库" value="4" />-->
    <!--        <el-option label="强化教案库" value="5" />-->
    <!--        <el-option label="空中忍者教案库" value="6" />-->
    <!--        <el-option label="少儿安防教案库" value="7" />-->
    <!--        <el-option label="体能教案库" value="8" />-->
    <!--        <el-option label="热身动作库" value="9" />-->
    <!--        <el-option label="体能动作库" value="10" />-->
    <!--        <el-option label="趣味游戏库" value="11" />-->
    <!--        <el-option label="放松动作库" value="12" />-->
    <!--        <el-option label="训练内容" value="13" />-->
    <!--        <el-option label="训练视频" value="14" />-->
    <!--        <el-option label="课后作业" value="15" />-->
    <!--        <el-option label="优秀一堂课" value="16" />-->
    <!--        <el-option label="空中忍者" value="17" />-->
    <!--        <el-option label="篮球动作" value="18" />-->
    <!--        <el-option label="跳绳动作" value="19" />-->
    <!--        <el-option label="跑酷动作" value="20" />-->
    <!--        <el-option label="安防动作" value="21" />-->
    <!--        <el-option label="标准化动作" value="22" />-->
    <!--        <el-option label="3-6岁体测" value="23" />-->
    <!--        <el-option label="7+体测" value="24" />-->
    <!--        <el-option label="3-6岁体测讲解—解读" value="25" />-->
    <!--        <el-option label="7+岁体测讲解—解读" value="26" />-->
    <!--        <el-option label="互动游戏" value="27" />-->
    <!--        <el-option label="套圈游戏" value="28" />-->
    <!--        <el-option label="鼓励方式" value="29" />-->
    <!--      </el-select>-->
    <!--    </el-form-item>-->

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showDialog = false">{{ t('cancel') }}</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="confirm(formRef)"
          >{{ t('confirm') }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch,nextTick  } from 'vue'
import { useDictionary } from '@/app/api/dict'
import { t } from '@/lang'
import type { FormInstance } from 'element-plus'
import {
  addLessonCourseTeaching,
  editLessonCourseTeaching,
  getLessonCourseTeachingInfo,
  getLessonCourseTeachingList,
  getWithPersonnelDataList,
  setBindingModule,
} from '@/app/api/lesson_course_teaching'

import {
  role_all,
  departments_all,
} from '@/app/api/sys'

import { ElMessage, ElMessageBox } from 'element-plus';
let showDialog = ref(false)
const loading = ref(false)

let lessonCourseTeachingTable = reactive({
  page: 1,
  limit: 10,
  total: 0,
  loading: true,
  data: [],
  searchParam: {
    name: '',
    phone: '',
	dept_id:'',
	role_id:''
  },
})

const lessonCourseTableRef = ref()

watch(
  () => lessonCourseTeachingTable.data,
  async (newData) => {
    if (newData.length > 0) {
      await nextTick()
      newData.forEach((row) => {
		  lessonCourseTableRef.value.toggleRowSelection(row, false)  
		  if(lessonCourseTeachingTable.searchParam.dept_id || lessonCourseTeachingTable.searchParam.role_id){
			lessonCourseTableRef.value.toggleRowSelection(row, true)  
		  }
        
      })
    }
  },
  { deep: true }
)

const roleIdList = ref([] as any[])
const setRoleIdList = async () => {
  roleIdList.value = await (await role_all({})).data
}
setRoleIdList()
const deptIdList = ref([] as any[])
const setDeptIdList = async () => {
  deptIdList.value = await (await departments_all({})).data
}
setDeptIdList()


const multipleSelection = ref<[]>([])
const binding_module = ref('')
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
}

const loadLessonCourseTeachingList = (page: number = 1) => {
  multipleSelection.value = [];
  lessonCourseTeachingTable.loading = true
  lessonCourseTeachingTable.page = page

  getWithPersonnelDataList({
    page: lessonCourseTeachingTable.page,
    limit: lessonCourseTeachingTable.limit,
    ...lessonCourseTeachingTable.searchParam,
  })
    .then((res) => {
      lessonCourseTeachingTable.loading = false
      lessonCourseTeachingTable.data = res.data.data
      lessonCourseTeachingTable.total = res.data.total
    })
    .catch(() => {
      lessonCourseTeachingTable.loading = false
    })
}
loadLessonCourseTeachingList()

const resetForm = (page: number = 1) => {
  lessonCourseTeachingTable.searchParam.name = ''
  lessonCourseTeachingTable.searchParam.phone = ''
  loadLessonCourseTeachingList()
}

/**
 * 表单数据
 */
const initialFormData = {
  id: '',
  title: '',
  image: '',
  type: '',
  content: '',
  status: '',
  // user_permission: [],
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
  return {
    title: [
      { required: true, message: t('titlePlaceholder'), trigger: 'blur' },
    ],
    image: [
      { required: true, message: t('imagePlaceholder'), trigger: 'blur' },
    ],
    type: [{ required: true, message: t('typePlaceholder'), trigger: 'blur' }],
    content: [
      { required: true, message: t('contentPlaceholder'), trigger: 'blur' },
    ],
    status: [
      { required: true, message: t('statusPlaceholder'), trigger: 'blur' },
    ],
  }
})

const emit = defineEmits(['complete'])

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
  if(multipleSelection.value.length == 0) {
    ElMessage.error('请选择数据');
    return;
  }
  let data = {
    id: BindingId.value,
    user_permission: multipleSelection.value
      .map((item) => item.sys_user_id)
      .join(','),
    user_permission_name: multipleSelection.value
      .map((item) => item.name)
      .join(','),
    table_type: binding_module.value,
  }
  setBindingModule(data)
    .then((res) => {
      loading.value = false
      showDialog.value = false
      emit('complete')
    })
    .catch((err) => {
      loading.value = false
    })
}

// 获取字典数据
let typeList = ref([])
const typeDictList = async () => {
  typeList.value = await (await useDictionary('material_type')).data.dictionary
}
typeDictList()
watch(
  () => typeList.value,
  () => {
    formData.type = typeList.value[0].value
  }
)
let statusList = ref([])
const statusDictList = async () => {
  statusList.value = await (
    await useDictionary('course_status')
  ).data.dictionary
}
statusDictList()
watch(
  () => statusList.value,
  () => {
    formData.status = statusList.value[0].value
  }
)

const userPermissionList = ref([] as any[])
const BindingId = ref(undefined)
const setUserPermissionList = async () => {
  userPermissionList.value = await (await getWithPersonnelDataList({})).data
}
setUserPermissionList()
const setFormData = async (row: any = null) => {
  BindingId.value = row.id
  binding_module.value = row.table_type
}

// 验证手机号格式
const mobileVerify = (rule: any, value: any, callback: any) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error(t('generateMobile')))
  } else {
    callback()
  }
}

// 验证身份证号
const idCardVerify = (rule: any, value: any, callback: any) => {
  if (
    value &&
    !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(
      value
    )
  ) {
    callback(new Error(t('generateIdCard')))
  } else {
    callback()
  }
}

// 验证邮箱号
const emailVerify = (rule: any, value: any, callback: any) => {
  if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
    callback(new Error(t('generateEmail')))
  } else {
    callback()
  }
}

// 验证请输入整数
const numberVerify = (rule: any, value: any, callback: any) => {
  if (!Number.isInteger(value)) {
    callback(new Error(t('generateNumber')))
  } else {
    callback()
  }
}

defineExpose({
  showDialog,
  setFormData,
})
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.diy-dialog-wrap .el-form-item__label {
  height: auto !important;
}
</style>
