import {
  NButton,
  NSpace,
  useMessage,
  NCheckboxGroup,
  NCheckbox,
  NRow,
  NImage,
  NInput,
  NScrollbar,
  NDropdown
} from 'naive-ui';
import { computed, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../index.module.less';
import SearchInput from '@/components/searchInput';
import smallArrow from '../images/smallArrow.png';
import transArrrow from '../images/transArrrow.png';
import transArrowActive from '../images/transArrowActive.png';
import { getCLassStudent, classGroupList, adjustStudent } from '../api';
export default defineComponent({
  props: {
    activeRow: {
      type: Object,
      default: () => ({ id: '' })
    }
  },
  name: 'RestStudentBox',
  emits: ['close', 'getList'],
  setup(props, { emit }) {
    const message = useMessage();
    const data = reactive({
      uploading: false
    });
    const options = ref([] as any);

    const chioseOptions = ref([] as any);
    const formRef = ref();
    const handleSubmit = async () => {
      data.uploading = true;
    };
    const classList = ref([] as any);
    console.log(props.activeRow, 'activeRow');
    const targetClass = reactive({
      gradeYear: null,
      name: '',
      id: ''
    });
    const currentchioseStudent = ref([] as any);
    const currentStudentList = ref([] as any);
    const currentSearch = ref(null as any);

    const targetchioseStudent = ref([] as any);
    const targetStudentList = ref([] as any);
    const targetSearch = ref(null as any);
    //
    const submitList = ref([] as any);
    /**
     * 这里干3件事  1.获取当前班的学生
     * 2.查询所有的班级列表  并且排查当前班级
     * 3.默认选择第一个班级 并且查出此班的学生
     */
    const chioseStudnet = (val: any) => {
      console.log(val);
    };
    const getAllClassList = async () => {
      try {
        const res = await classGroupList({
          page: 1,
          rows: 9999,
          upgradeFlag: true
        });
        // classList.value = res.data.rows.map((item: any) => {
        //   return {
        //     label: item.name,
        //     key: item.id,
        //     gradeYear: item.gradeYear,
        //     disabled: item.id == props.activeRow.id
        //   };
        // });

        // if (classList.value[0].disabled) {
        //   targetClass.name = classList.value[1].label;
        //   targetClass.id = classList.value[1].key;
        //   targetClass.gradeYear = classList.value[1].gradeYear;
        // } else {
        //   targetClass.name = classList.value[0].label;
        //   targetClass.id = classList.value[0].key;
        //   targetClass.gradeYear = classList.value[0].gradeYear;
        // }

        // const tarRes = await getCLassStudentList(targetClass.id);
        // targetStudentList.value = tarRes.data.rows.map((item: any) => {
        //   return {
        //     label: item.nickname + '（' + item.id + '）',
        //     value: item.id
        //   };
        // });
        const result = res.data.rows || [];
        const currentYearList: any = [];
        const otherYearList: any = [];
        result.forEach((item: any) => {
          const params = {
            label: item.name,
            key: item.id,
            gradeYear: item.gradeYear,
            value: item.id,
            disabled: item.id == props.activeRow.id
          };
          if (props.activeRow.gradeYear === item.gradeYear) {
            currentYearList.push(params);
          } else {
            otherYearList.push(params);
          }
        });

        classList.value = [...currentYearList, ...otherYearList];

        if (classList.value[0].disabled) {
          if (classList.value.length > 1) {
            targetClass.name = classList.value[1].label;
            targetClass.id = classList.value[1].key;
            targetClass.gradeYear = classList.value[1].gradeYear;
          }
        } else {
          targetClass.name = classList.value[0].label;
          targetClass.id = classList.value[0].key;
          targetClass.gradeYear = classList.value[0].gradeYear;
        }
        if (targetClass.id) {
          const tarRes = await getCLassStudentList(targetClass.id);
          targetStudentList.value = tarRes.data.rows.map((item: any) => {
            return {
              label: item.nickname + '（' + item.id + '）',
              value: item.id
            };
          });
        }
      } catch (e) {
        console.log(e);
      }
    };
    const getCLassStudentList = async (id: string | number) => {
      return await getCLassStudent({
        page: 1,
        rows: 999,
        classGroupId: id
      });
    };
    const chioseClass = async (val: any) => {
      classList.value.forEach((item: any) => {
        if (item.key == val) {
          targetClass.name = item.label;
          targetClass.gradeYear = item.gradeYear;
          targetClass.id = item.key;
        }
      });
      const res = await getCLassStudentList(val);
      targetStudentList.value = res.data.rows.map((item: any) => {
        return {
          label: item.nickname + '（' + item.id + '）',
          value: item.id
        };
      });
      console.log(submitList.value, 'submitList.value');
      // 判断一下 targetStudentList.value 和 submitList 对比
      targetStudentList.value = targetStudentList.value.filter(
        (item: any) =>
          !submitList.value.some((ele: any) => ele.value === item.value)
      );
      // 如果 如果submitList 学生的toClassId 和targetClassId相同 则添加
      submitList.value.forEach((ele: any) => {
        if (ele.toClassId == targetClass.id) {
          console.log(ele.toClassId, ele);
          targetStudentList.value.push({
            label: ele.label,
            value: ele.value
          });
        }
      });
      // 有2下 如果submitList 学生 和 targetStudentList 学生id相同 则删除
    };
    const currentFitterList = computed(() => {
      const oraginArr = currentStudentList.value || [];
      const list = oraginArr.filter((item: any) => {
        return item.label.indexOf(currentSearch.value || '') != -1;
      });
      return list;
    });

    const targetFitterList = computed(() => {
      const oraginArr = targetStudentList.value || [];
      const list = oraginArr.filter((item: any) => {
        return item.label.indexOf(targetSearch.value || '') != -1;
      });
      return list;
    });

    const chioseAllCurrentStudent = () => {
      if (
        currentFitterList.value.length === currentchioseStudent.value.length
      ) {
        // 说明要取消全选
        currentchioseStudent.value = [];
      } else {
        currentchioseStudent.value = currentFitterList.value.map(
          (item: any) => {
            return item.value;
          }
        );
        // 全选
      }
    };

    const chioseAllTargetStudent = () => {
      if (targetFitterList.value.length === targetchioseStudent.value.length) {
        // 说明要取消全选
        targetchioseStudent.value = [];
      } else {
        targetchioseStudent.value = targetFitterList.value.map((item: any) => {
          return item.value;
        });
        // 全选
      }
    };
    const toTargetList = () => {
      const subStudetn = currentStudentList.value.filter((item: any) => {
        return currentchioseStudent.value.indexOf(item.value) != -1;
      });
      if (subStudetn.length > 0) {
        const arr = subStudetn.map((item: any) => {
          return {
            ...item,
            studentId: item.value,
            toClassId: targetClass.id
          };
        });
        submitList.value = submitList.value.filter(
          (item: any) => !arr.some((ele: any) => ele.value === item.value)
        );
        submitList.value = submitList.value.concat(arr);
      }
      // 接下来 删除 currentStudentList里的这三个学生
      currentStudentList.value = currentStudentList.value.filter(
        (item: any) => !subStudetn.some((ele: any) => ele.value === item.value)
      );
      subStudetn.forEach((item: any) => {
        targetStudentList.value.push(item);
      });
      currentchioseStudent.value = [];
    };
    const toCurrentList = () => {
      const subStudetn = targetStudentList.value.filter((item: any) => {
        return targetchioseStudent.value.indexOf(item.value) != -1;
      });
      if (subStudetn.length > 0) {
        const arr = subStudetn.map((item: any) => {
          return {
            ...item,
            studentId: item.value,
            toClassId: props.activeRow.id
          };
        });
        submitList.value = submitList.value.filter(
          (item: any) => !arr.some((ele: any) => ele.value === item.value)
        );
        submitList.value = submitList.value.concat(arr);
      }
      targetStudentList.value = targetStudentList.value.filter(
        (item: any) => !subStudetn.some((ele: any) => ele.value === item.value)
      );
      subStudetn.forEach((item: any) => {
        currentStudentList.value.push(item);
      });
      targetchioseStudent.value = [];
      // 过去 所以
      console.log(submitList.value, ' submitList.value===>');
    };

    const submitStudent = async () => {
      if (classList.value.length < 2) {
        message.error('当前只有一个班级,无法调整');
        return;
      }
      if (submitList.value < 1) {
        emit('close');
        return;
      }
      try {
        const res = await adjustStudent(submitList.value);
        emit('close');
        emit('getList');
      } catch (e) {
        console.log(e);
      }
    };
    onMounted(async () => {
      getAllClassList();
      const res = await getCLassStudentList(props.activeRow.id as string);
      currentStudentList.value = res.data.rows.map((item: any) => {
        return {
          label: item.nickname + '（' + item.id + '）',
          value: item.id
        };
      });
    });
    return () => (
      <div class={[styles.container, styles.resetStudentWrap]}>
        <div class={styles.studentTransfer}>
          <div class={styles.studentTransferList}>
            <div class={styles.studentLeft}>
              <div class={styles.listTop}>
                <p>{props.activeRow.name}</p>
                <span>（{props.activeRow.gradeYear}学年）</span>
              </div>
              <div class={styles.listCore}>
                <NRow class={styles.chioseCheckAllBox}>
                  <NCheckbox
                    onUpdateChecked={val => {
                      chioseAllCurrentStudent();
                    }}
                    checked={
                      currentFitterList.value.length ===
                      currentchioseStudent.value.length
                    }
                    indeterminate={
                      currentchioseStudent.value.length > 0 &&
                      currentFitterList.value.length !==
                        currentchioseStudent.value.length
                    }
                    label="全选"></NCheckbox>
                </NRow>
                <NRow>
                  <SearchInput
                    {...{ placeholder: '请输入学生姓名' }}
                    class={styles.searchInput}
                    searchWord={currentSearch.value}
                    onChangeValue={(val: string) =>
                      (currentSearch.value = val)
                    }></SearchInput>
                </NRow>
                <NScrollbar style="max-height: 204px;min-height: 204px;margin-top:14px;">
                  <NCheckboxGroup v-model:value={currentchioseStudent.value}>
                    {currentFitterList.value.map((item: any) => (
                      <NRow class={styles.chioseCheckBox}>
                        <NCheckbox
                          value={item.value}
                          label={item.label}></NCheckbox>
                      </NRow>
                    ))}
                  </NCheckboxGroup>
                </NScrollbar>
              </div>
              <div class={[styles.bottomLeft, styles.bottom]}>
                <div class={styles.bottomWrap}>
                  共{currentStudentList.value.length}名学生
                </div>
              </div>
            </div>
            <div class={styles.chioseBox}>
              <div
                class={[styles.chioseBtn, styles.chioseBtnRight]}
                onClick={() => toTargetList()}></div>
              <div
                class={styles.chioseBtn}
                onClick={() => toCurrentList()}></div>
            </div>
            <div class={styles.studentRight}>
              <div class={styles.listTop}>
                {targetClass.id ? (
                  <NDropdown
                    key="111"
                    v-model:value={targetClass.id}
                    options={classList.value}
                    onSelect={(value: any) => {
                      chioseClass(value);
                    }}
                    renderLabel={(option: any) => (
                      <div style={{ display: 'flex' }}>
                        {option.label}
                        <div style={{ fontSize: '12Px' }}>
                          （{option.gradeYear}学年）
                        </div>
                      </div>
                    )}
                    scrollable>
                    <div class={styles.showGradeSection}>
                      <div>
                        {targetClass.name}
                        {targetClass.gradeYear && (
                          <span>（{targetClass.gradeYear}学年）</span>
                        )}
                      </div>
                      {/* gradeYear */}
                      <NImage
                        class={styles.smallArrow}
                        src={smallArrow}
                        previewDisabled></NImage>
                    </div>
                  </NDropdown>
                ) : null}
              </div>
              <div class={styles.listCore}>
                <NRow class={styles.chioseCheckAllBox}>
                  <NCheckbox
                    onUpdateChecked={val => {
                      chioseAllTargetStudent();
                    }}
                    checked={
                      targetFitterList.value.length ===
                      targetchioseStudent.value.length
                    }
                    indeterminate={
                      targetchioseStudent.value.length > 0 &&
                      targetFitterList.value.length !==
                        targetchioseStudent.value.length
                    }
                    label="全选"></NCheckbox>
                </NRow>
                <NRow>
                  <SearchInput
                    {...{ placeholder: '请输入学生姓名' }}
                    class={styles.searchInput}
                    searchWord={targetSearch.value}
                    onChangeValue={(val: string) =>
                      (targetSearch.value = val)
                    }></SearchInput>
                </NRow>
                <NScrollbar style="max-height: 204px;min-height: 204px;margin-top:14px;">
                  <NCheckboxGroup v-model:value={targetchioseStudent.value}>
                    {targetFitterList.value.map((item: any) => (
                      <NRow class={styles.chioseCheckBox}>
                        <NCheckbox
                          value={item.value}
                          label={item.label}></NCheckbox>
                      </NRow>
                    ))}
                  </NCheckboxGroup>
                </NScrollbar>
              </div>
              <div class={[styles.bottomRight, styles.bottom]}>
                <div class={styles.bottomWrap}>
                  共{targetStudentList.value.length}名学生
                </div>
              </div>
            </div>
          </div>
        </div>

        <NSpace class={styles.btnGroup} justify="center">
          <NButton round onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            round
            loading={data.uploading}
            type="primary"
            onClick={() => {
              submitStudent();
            }}>
            保存
          </NButton>
        </NSpace>
      </div>
    );
  }
});
