import React from 'react';
import Taro from '@tarojs/taro';
import { View, ScrollView } from '@tarojs/components';
import { Notify } from '@antmjs/vantui';
import Page from '@/layouts/index';
import { getTaCheckItemById, preCheck, getTaCheckItemAnswer, putTaCheckItemAnswer } from '@/services/tacheckitem';
import { getTaCheckItemQu } from '@/services/tacheckitemqu';
import VABC from '@/components/VABC';
import { ROLE_INSPECTOR } from '@/utils/user';
import LocForm from './components/LocForm';
import Question from './components/Question';
import Footer from './components/Footer/index';

export default (props) => {

  const router = Taro.useRouter();
  const { id } = router.params;

  const [loading, setLoading] = React.useState(false);
  const [readonly, setReadonly] = React.useState(false);
  const [checkItemInfo, setCheckItemInfo] = React.useState();
  const [quList, setQuList] = React.useState([]);
  const [index, setIndex] = React.useState(-1);
  const [answer, setAnswer] = React.useState();

  const onIndexChange = (n) => {
    if (index == -1 && n != -1) {
      if (!readonly) {
        if (!answer?.addr) {
          Notify.show({
            message: '请填写地址',
            type: 'warning',
          })
          return;
        }
        if (!answer?.location) {
          Notify.show({
            message: '未能获取定位信息, 请重试',
            type: 'warning',
          })
          return;
        }
      }
    }

    setIndex(n);
  }

  const onAnswerItemChange = (answerItem, quInfo) => {
    if (!answerItem) return;

    const an = { ...(answer || {}) }
    const answerItemList = an.answerItemList || []

    if ((answerItem.answerCode || answerItem.answer) &&
      answerItem.attachList?.length) {
      // 说明这一题已经回答完毕
      quInfo.finished = true
    } else {
      quInfo.finished = false
    }

    // 更新问题列表中是否作答的标志位
    setQuList(quList.map(x => x.quId == quInfo.quId ? quInfo : x));

    if (answerItemList.length) {
      let found = false;
      an.answerItemList = answerItemList.map(x => {
        if (x.quId == answerItem.quId) {
          found = true;
          return answerItem;
        } else {
          return x;
        }
      });

      if (!found) {
        answerItemList.push(answerItem);
        an.answerItemList = answerItemList;
      }
    } else {
      answerItemList.push(answerItem);
      an.answerItemList = answerItemList;
    }

    setAnswer(an);
  }

  // 作答
  const onSubmit = () => {
    if (readonly) return;

    const finished = quList.filter(x => x.finished).length == quList.length;
    if (!answer || !answer.answerItemList || !finished) {
      Notify.show({
        message: '请作答完成所有题目',
        type: 'warning',
      })
      return;
    }

    setLoading(true);
    putTaCheckItemAnswer(id, answer).then(() => {
      setLoading(false);
      const t = setTimeout(() => {
        clearTimeout(t);
        Taro.navigateBack({ delta: 1 });
      }, 1000);
    }).catch(() => {
      setLoading(false);
    });
  }

  React.useEffect(() => {
    setLoading(true);
    preCheck(id, { noSuccesTip: true }).then((checkRes) => {
      if (checkRes.errorCode < 0) {
        Notify.show({
          message: checkRes.message,
          type: 'warning',
        })

        Taro.navigateBack({ delta: 1 })
        return;
      }

      if (checkRes.errorCode > 0) {
        setReadonly(true);
        // Notify.show({
        //   message: checkRes.message,
        //   type: 'warning',
        // })
      }

      // 查询当前测评点位(问卷)主记录
      getTaCheckItemById(id).then(res => {
        setCheckItemInfo(res);
      });

      // 查询我的答案
      getTaCheckItemAnswer(id).then(setAnswer);

      // 查询当前测评主记录的所有问题
      getTaCheckItemQu({ pageSize: 200, itemId: id }).then(res => {
        console.log('---------->res------------->', res);
        setLoading(false);
        setQuList(res.records || []);
      }).catch(() => {
        setLoading(false);
      });
    }).catch(() => {
      setLoading(false);
    });
  }, [id]);
  // console.log('--------id---------->', id);
  // console.log('--------方方--quList------>>>>>>>', quList);
  return (
    <Page loading={loading} roles={[ROLE_INSPECTOR]}>
      <VABC
        footer={(
          <Footer
            value={index}
            readonly={readonly}
            list={quList}
            onChange={onIndexChange}
            onSubmit={onSubmit}
          />
        )}
      >
        <ScrollView scrollY style={{ height: '100%' }}>
          {
            index == -1 && (
              <LocForm
                readonly={readonly}
                checkItemInfo={checkItemInfo}
                answer={answer}
                onChange={setAnswer}
                onLoadingChange={setLoading}
              />
            )
          }
          {
            quList.map((x, inx) => {
              const answerItem = answer?.answerItemList?.filter(y => y.quId == x.quId)[0];
              return (
                index == inx && (
                  <Question
                    key={x.quId}
                    cursor={inx}
                    readonly={readonly}
                    quInfo={x}
                    answerItem={answerItem}
                    total={quList?.length}
                    onChange={e => onAnswerItemChange(e, x)}
                    onPrev={() => onIndexChange(null, -1)}
                    onNext={() => onIndexChange(null, 1)}
                    onLoadingChange={setLoading}
                  />
                )
              )
            })
          }

        </ScrollView>
      </VABC>
    </Page>
  )
}
