import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NModal,
  NSpace,
  NTooltip,
  useMessage
} from 'naive-ui';
import SearchInput from '@/components/searchInput';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
import { useRoute, useRouter } from 'vue-router';
import { getStudentList } from './api';
import { classGroupList } from '@/views/classList/api';
// import Studentguide from '@/custom-plugins/guide-page/student-guide';
import TheEmpty from '/src/components/TheEmpty';
// import NoticeModal from './modals/noticeModal';
import { useUserStore } from '/src/store/modules/users';
import UpdateStudent from './modals/update-student';
import { initCache, setCache } from '/src/hooks/use-async';
import { classArray, getgradeNumList } from '../classList/contants';
import { getGradeLevelList, getGradeYearList } from '../home/api';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'student-studentList',
  setup(props, { emit }) {
    const userStore = useUserStore();
    const state = reactive({
      searchForm: {
        keyword: '',
        gender: '' as any,
        classGroupId: '' as any,
        membership: '' as any,
        currentClass: '' as any,
        currentGradeNum: '' as any,
        gradeYear: '' as any,
        gradeLevel: ''
      },
      gradeNumList: [] as any,
      searchWord: '',
      orchestraType: null,
      courseTypeCode: null,
      subjectId: null,
      classId: null,
      studentType: null,
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      classList: [],
      addStudentVisible: false,
      editStatus: false,
      activeRow: {} as any,
      popSelectYearList: [] as any,
      popSelectLevelList: [] as any
    });
    state.gradeNumList = getgradeNumList();
    const route = useRoute();
    const router = useRouter();
    // const showGuide = ref(false);
    const message = useMessage();
    const search = () => {
      state.pagination.page = 1;
      getList();
      setCache({ current: state.searchForm, saveKey: route.path });
    };
    const getClasslist = async () => {
      try {
        const res = await classGroupList({ page: 1, rows: 999 });
        state.classList = res.data.rows.map((item: any) => {
          return {
            label: item.name,
            value: item.id
          };
        });
      } catch (e) {
        console.log(e);
      }
    };

    const copyTo = (text: string) => {
      const input = document.createElement('input');
      input.value = text;
      document.body.appendChild(input);
      input.select();
      input.setSelectionRange(0, input.value.length);
      document.execCommand('Copy');
      document.body.removeChild(input);
      message.success('复制成功');
    };
    const onReset = () => {
      state.searchForm = {
        keyword: '',
        gender: '' as any,
        classGroupId: '' as any,
        membership: '' as any,
        currentClass: '' as any,
        currentGradeNum: '' as any,
        gradeYear: '' as any,
        gradeLevel: ''
      };
      if (state.popSelectYearList.length > 1) {
        state.searchForm.gradeYear = state.popSelectYearList[1].id;
      }
      search();
      setCache({ current: state.searchForm, saveKey: route.path });
    };

    initCache({
      current: state.searchForm,
      callBack: (active: any) => {
        state.searchForm = active;
      }
    });
    const getList = async () => {
      try {
        const res = await getStudentList({
          ...state.searchForm,
          ...state.pagination
        });
        state.tableList = res.data.rows;
        state.pagination.pageTotal = res.data.total;
        // if (state.tableList.length > 0) {
        //   setTimeout(() => {
        //     showGuide.value = true;
        //   }, 500);
        // }
      } catch (e) {
        console.log(e);
      }
      console.log('getList');
    };

    // 获取学年
    const getYearList = async () => {
      try {
        const { data } = await getGradeYearList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '学年';
        });
        // temp.unshift({
        //   id: '',
        //   name: '全部学年'
        // });
        state.popSelectYearList = temp || [];
        if (temp.length > 1 && !state.searchForm.gradeYear) {
          state.searchForm.gradeYear = temp[1].id;
        }
      } catch {
        //
      }
    };
    // 获取学级
    const getLevelList = async () => {
      try {
        const { data } = await getGradeLevelList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '级';
        });
        temp.unshift({
          id: '',
          name: '全部学级'
        });
        state.popSelectLevelList = temp || [];
        if (temp.length > 0 && !state.searchForm.gradeLevel) {
          state.searchForm.gradeLevel = temp[0].id;
        }
      } catch {
        //
      }
    };

    onMounted(async () => {
      state.loading = true;
      await getYearList();
      await getLevelList();
      await getList();
      await getClasslist();
      state.loading = false;
    });
    const columns = () => {
      return [
        {
          title: '学生姓名',
          key: 'nickname',
          render: (row: any) => {
            return (
              <NTooltip showArrow={false} placement="top-start">
                {{
                  trigger: () => (
                    <div
                      style={{ userSelect: 'all', cursor: 'pointer' }}
                      onClick={() => copyTo(row.nickname)}>
                      {row.nickname}
                    </div>
                  ),
                  default: '点击复制'
                }}
              </NTooltip>
            );
          }
        },
        {
          title: '手机号',
          key: 'phone',
          render: (row: any) => {
            return (
              <NTooltip showArrow={false} placement="top-start">
                {{
                  trigger: () => (
                    <div
                      style={{ userSelect: 'all', cursor: 'pointer' }}
                      onClick={() => copyTo(row.phone)}>
                      {row.phone}
                    </div>
                  ),
                  default: '点击复制'
                }}
              </NTooltip>
            );
          }
        },
        {
          title: '性别',
          key: 'gender',
          render(row: any) {
            return (
              <>
                {row.gender + '' != 'null'
                  ? row.gender == '0'
                    ? '女'
                    : '男'
                  : '--'}
              </>
            );
          }
        },
        {
          title: '年级班级',
          key: 'classGroupName'
        },

        {
          title: '学生类型',
          key: 'vipMember',
          render(row: any) {
            return <>{row.vipMember ? '会员' : '普通'}</>;
          }
        },
        {
          title: '操作',
          key: 'id',
          width: 300,
          render(row: any, index: number) {
            return (
              <NSpace>
                {index == 0 ? (
                  <NButton
                    {...{ id: 'student-1' }}
                    text
                    type="primary"
                    onClick={() => gotoDetail(row)}>
                    详情
                  </NButton>
                ) : (
                  <NButton text type="primary" onClick={() => gotoDetail(row)}>
                    详情
                  </NButton>
                )}
                <NButton
                  text
                  type="primary"
                  onClick={() => onUpdate(row)}
                  disabled={row.historyClassStudent}>
                  修改
                </NButton>
              </NSpace>
            );
          }
        }
      ];
    };

    const gotoDetail = (row: any) => {
      router.push({
        path: '/studentDetail',
        query: { ...route.query, studentId: row.id, studentName: row.nickname }
      });
    };

    // 修改
    const onUpdate = (row: any) => {
      state.editStatus = true;
      state.activeRow = row;
    };
    return () => (
      <div class={styles.listWrap}>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline>
            <NFormItem>
              <SearchInput
                {...{ placeholder: '请输入学生姓名' }}
                class={styles.searchInput}
                style={{ width: '160px' }}
                searchWord={state.searchForm.keyword}
                onChangeValue={(val: string) =>
                  (state.searchForm.keyword = val)
                }></SearchInput>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: [
                    {
                      label: '全部性别',
                      value: ''
                    },
                    {
                      label: '男',
                      value: 1
                    },
                    {
                      label: '女',
                      value: 0
                    }
                  ],
                  placeholder: '性别',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.gender}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: state.popSelectYearList,
                  placeholder: '选择学年',
                  clearable: false,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.gradeYear}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: state.popSelectLevelList,
                  placeholder: '选择学级',
                  clearable: true,
                  inline: true,
                  labelField: 'name',
                  valueField: 'id'
                } as any)}
                v-model:value={state.searchForm.gradeLevel}></CSelect>
            </NFormItem>

            <NFormItem>
              <CSelect
                {...({
                  options: state.gradeNumList,
                  placeholder: '选择年级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentGradeNum}></CSelect>
            </NFormItem>
            <NFormItem>
              <CSelect
                {...({
                  options: classArray,
                  placeholder: '选择班级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.currentClass}></CSelect>
            </NFormItem>
            {/* <NFormItem>
              <CSelect
                {...({
                  options: [
                    { label: '全部年级班级', value: '' },
                    ...state.classList
                  ],
                  placeholder: '年级班级',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.classGroupId}></CSelect>
            </NFormItem> */}
            <NFormItem>
              <CSelect
                {...({
                  options: [
                    {
                      label: '全部类型',
                      value: ''
                    },
                    {
                      label: '会员',
                      value: true
                    },
                    {
                      label: '普通',
                      value: false
                    }
                  ],
                  placeholder: '学生类型',
                  clearable: true,
                  inline: true
                } as any)}
                v-model:value={state.searchForm.membership}></CSelect>
            </NFormItem>
            <NFormItem>
              <NSpace justify="end">
                <NButton type="primary" class="searchBtn" onClick={search}>
                  搜索
                </NButton>
                <NButton
                  type="primary"
                  ghost
                  class="resetBtn"
                  onClick={onReset}>
                  重置
                </NButton>
              </NSpace>
            </NFormItem>
          </NForm>
        </div>
        {/* <NButton
          {...{ id: 'student-0' }}
          onClick={async () => {
            // state.addStudentVisible = true;
            try {
              const { schoolInfos } = userStore.getUserInfo;
              const schoolId =
                schoolInfos.length > 0 ? schoolInfos[0].id : null;
              if (schoolId) {
                const { data } = await schoolDetail({ id: schoolId });
                state.activeRow = data;

                state.addStudentVisible = true;
              }
            } catch {
              //
            }
          }}
          class={styles.addBtn}
          type="primary"
          v-slots={{
            icon: () => (
              <>
                <NImage
                  class={styles.addBtnIcon}
                  previewDisabled
                  src={add}></NImage>
              </>
            )
          }}>
          邀请学生
        </NButton> */}
        <div class={styles.tableWrap}>
          <NDataTable
            v-slots={{
              empty: () => <TheEmpty></TheEmpty>
            }}
            class={styles.classTable}
            loading={state.loading}
            columns={columns()}
            data={state.tableList}></NDataTable>
          <Pagination
            v-model:page={state.pagination.page}
            v-model:pageSize={state.pagination.rows}
            v-model:pageTotal={state.pagination.pageTotal}
            onList={getList}
            sync
          />
        </div>
        {/* {state.addStudentVisible ? (
          <div v-model:show={state.addStudentVisible} class="n-modal-mask">
            <AddStudentModel
              activeRow={state.activeRow}
              onClose={() => {
                state.addStudentVisible = false;
              }}></AddStudentModel>
          </div>
        ) : null} */}
        {/* <NModal
          v-model:show={state.addStudentVisible}
          showIcon={false}
          style={{ width: '400px' }}>
          <NoticeModal
            data={state.activeRow}
            onClose={() => (state.addStudentVisible = false)}
          />
        </NModal> */}

        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.editStatus}
          class={['modalTitle background', styles.updateStudent]}
          preset="card"
          title="修改信息">
          <UpdateStudent
            onClose={() => (state.editStatus = false)}
            onConfirm={() => getList()}
            row={state.activeRow}
          />
        </NModal>
        {/* {showGuide.value ? <Studentguide></Studentguide> : null} */}
      </div>
    );
  }
});
