import { defineComponent, onMounted, reactive, watch } from 'vue';
import styles from '../index.module.less';
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NModal,
  NNumberAnimation,
  NSpace,
  NTooltip,
  useMessage
} from 'naive-ui';
import SearchInput from '@/components/searchInput';
import CSelect from '@/components/CSelect';
import Pagination from '@/components/pagination';
import { api_studentStat, getStudentList } from '../api';
import { useRoute, useRouter } from 'vue-router';
import TheEmpty from '/src/components/TheEmpty';
import UpdateStudent from '../../studentList/modals/update-student';
import { initCache, setCache } from '/src/hooks/use-async';
import { modalClickMask } from '/src/state';
export default defineComponent({
  name: 'student-studentList',
  props: {
    upgradeFlag: {
      type: Number
    }
  },
  setup(props) {
    const message = useMessage();
    const route = useRoute();
    const router = useRouter();
    const payForm = reactive({
      vipStudentNum: 0,
      studentNum: 0
    });
    const state = reactive({
      upgradeFlag: props.upgradeFlag == 0 ? true : false, // 是否为历史班
      searchForm: { keyword: '', gender: '' as any, membership: '' as any },
      loading: false,
      pagination: {
        page: 1,
        rows: 10,
        pageTotal: 4
      },
      tableList: [] as any,
      editStatus: false,
      activeRow: {} as any
    });

    watch(
      () => props.upgradeFlag,
      () => {
        state.upgradeFlag = props.upgradeFlag == 0 ? true : false;
      }
    );
    const search = () => {
      state.pagination.page = 1;
      getInfo();
      getList();
      setCache({ current: state.searchForm, saveKey: 'classDetailStudent' });
    };

    const onReset = () => {
      state.searchForm = {
        keyword: '',
        gender: '' as any,
        membership: '' as any
      };
      getInfo();
      search();
      setCache({ current: state.searchForm, saveKey: 'classDetailStudent' });
    };
    const getList = async () => {
      state.loading = true;
      try {
        const res = await getStudentList({
          classGroupId: route.query.id,
          ...state.searchForm,
          ...state.pagination
        });

        state.tableList = res.data.rows;

        state.pagination.pageTotal = res.data.total;
        state.loading = false;
      } catch (e) {
        state.loading = false;
        console.log(e);
      }
    };

    initCache({
      current: state.searchForm,
      saveKey: 'classDetailStudent',
      callBack: (active: any) => {
        state.searchForm = active;
      }
    });

    const getInfo = async () => {
      try {
        const { data } = await api_studentStat({
          classGroupId: route.query.id as any,
          ...state.searchForm
        });
        payForm.studentNum = data.studentNum || 0;
        payForm.vipStudentNum = data.vipStudentNum || 0;
      } catch (e) {
        console.log(e);
      }
    };

    onMounted(() => {
      getInfo();
      getList();
    });

    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 gotoDetail = (row: any) => {
      router.push({
        path: '/classStudentDetail',
        query: {
          ...route.query,
          studentId: row.id,
          studentName: row.nickname,
          upgradeFlag: state.upgradeFlag ? 0 : 1
        }
      });
    };
    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: 'vipMember',
          render(row: any) {
            return <>{row.vipMember ? '会员' : '普通'}</>;
          }
        },
        {
          title: '操作',
          key: 'id',
          render(row: any) {
            return (
              <NSpace>
                <NButton text type="primary" onClick={() => gotoDetail(row)}>
                  详情
                </NButton>
                <NButton
                  text
                  type="primary"
                  onClick={() => onUpdate(row)}
                  disabled={row.historyClassStudent}>
                  修改
                </NButton>
              </NSpace>
            );
          }
        }
      ];
    };
    // 修改
    const onUpdate = (row: any) => {
      state.editStatus = true;
      state.activeRow = row;
    };
    return () => (
      <div>
        <div class={styles.searchList}>
          <NForm label-placement="left" inline>
            <NFormItem>
              <SearchInput
                {...{ placeholder: '请输入学生姓名' }}
                class={styles.searchInput}
                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: [
                    {
                      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>
        <div class={['section-container']}>
          <div class={styles.TrainDataTop}>
            <div class={styles.TrainDataTopLeft}>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={payForm.studentNum}></NNumberAnimation>
                    </span>
                    人
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>班级人数</p>
              </div>
              <div class={styles.TrainDataItem}>
                <p class={styles.TrainDataItemTitle}>
                  <div>
                    <span>
                      <NNumberAnimation
                        from={0}
                        to={payForm.vipStudentNum}></NNumberAnimation>
                    </span>
                    人
                  </div>
                </p>
                <p class={styles.TrainDataItemsubTitle}>会员人数</p>
              </div>
            </div>
            <div class={styles.TrainDataTopRight}></div>
          </div>
        </div>
        <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>

        <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>
      </div>
    );
  }
});
