import {
  NButton,
  NSpace,
  useMessage,
  NForm,
  NFormItem,
  NCascader,
  NScrollbar
} from 'naive-ui';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './resetSubjectList.module.less';
import { getClassSubjects, updateBatchInstrument } from '../api';
export default defineComponent({
  props: {
    activeRow: {
      type: Array,
      default: () => []
    }
  },
  name: 'resetSubjectList',
  emits: ['close', 'getList'],
  setup(props, { emit }) {
    const data = reactive({
      uploading: false
    });
    const message = useMessage();
    const formsRef = ref();
    // const subjectList = ref(toRef(props.activeRow));
    const createClassForm = reactive({
      classList: props.activeRow
      // currentGradeNum: null,
      // gradeYear: null,
      // currentClass: null,
      // instrumentId: null,
      // id: null
    });
    onMounted(() => {
      // createClassForm.currentGradeNum = props.activeRow.currentGradeNum;
      // createClassForm.gradeYear = props.activeRow.gradeYear;
      // createClassForm.currentClass = props.activeRow.currentClass;
      // createClassForm.instrumentId = props.activeRow.instrumentId;
      // createClassForm.id = props.activeRow.id;

      getConfigSubject();
    });
    const submitForms = () => {
      formsRef.value.validate(async (error: any) => {
        if (error) {
          return;
        }

        // console.log(createClassForm.classList);
        data.uploading = true;
        // [{
        //   "id": "1901469499486425089",
        //   "instrumentId": "1002"
        // }]

        try {
          const params: any[] = [];
          createClassForm.classList.forEach((item: any) => {
            params.push({
              id: item.classGroupId,
              instrumentId: item.instrumentId
            });
          });
          // console.log(params, 'params');
          await updateBatchInstrument(params);
          message.success('修改成功');
          emit('close');
          emit('getList');
          data.uploading = false;
        } catch (e) {
          console.log(e);
        }
        data.uploading = false;
      });
    };

    const getConfigSubject = async () => {
      try {
        const ids = props.activeRow.map((item: any) => {
          return item.classGroupId;
        });
        const { data } = await getClassSubjects(ids);
        // const temp = data || [];
        if (Array.isArray(data)) {
          createClassForm.classList.forEach((item: any) => {
            const classSubject = data.find(
              (subject: any) => subject.classGroupId === item.classGroupId
            );
            if (classSubject) {
              item.subjectList = classSubject.subjectList || [];
            }
          });
        }

        // console.log(data, 'data', createClassForm.classList);
        // subjectList.value = temp;
      } catch {
        //
      }
    };

    return () => (
      <div class={[styles.addClass]}>
        <NForm label-placement="top" model={createClassForm} ref={formsRef}>
          <NScrollbar style="max-height: 360px; padding: 0 30px">
            {createClassForm.classList.map((item: any, index: number) => (
              <NFormItem
                path={`classList[${index}].instrumentId`}
                label={item.classGroupName}
                showRequireMark={false}
                rule={[
                  {
                    required: true,
                    message: '请选择乐器',
                    trigger: 'change'
                  }
                ]}>
                <NCascader
                  placeholder="请选择乐器"
                  v-model:value={item.instrumentId}
                  options={item.subjectList}
                  checkStrategy="child"
                  showPath={false}
                  childrenField="instruments"
                  expandTrigger="hover"
                  labelField="name"
                  valueField="id"
                  clearable
                  filterable
                  style={{ width: '400px' }}
                />
              </NFormItem>
            ))}
          </NScrollbar>
        </NForm>
        <NSpace class={styles.btnGroup} justify="end">
          <NButton secondary onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            loading={data.uploading}
            onClick={() => submitForms()}
            type="primary">
            确认
          </NButton>
        </NSpace>
      </div>
    );
  }
});
