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,
  getTaCheckItemByCheck,
  preCheck,
  getTaCheckItemAnswer,
  putTaCheckItemAnswer,
} from '@/services/tacheckitem';
import { getTaCheckItemQu } from '@/services/tacheckitemqu';
import VABC from '@/components/VABC';
import { ROLE_INSPECTOR } from '@/utils/user';
import { warn } from '@/utils/message';
import LocForm from './components/LocForm';
import Question from './components/Question';
import Footer from './components/Footer/index';

const isNotEmpty = str => str !== undefined && str !== null && `${str}`.replace(/\s/g, '') !== '';

export default (props) => {

  const router = Taro.useRouter();
  const { id, checkId, typ } = 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();

  React.useMemo(() => {
    if (typ == 'loc') {
      Taro.setNavigationBarTitle({ title: '实地测评' });
    } else {
      Taro.setNavigationBarTitle({ title: '调查问卷' });
    }
  }, [typ]);

  const onIndexChange = (n) => {
    if (index == -1 && n != -1) {
      if (!readonly) {
        try {
          warn(typ == 'survey' && !answer?.communityName, '请填写社区名称');
          warn(!answer?.addr, typ == 'loc' ? '请填写地址' : '请填写小区名称');
          warn(!answer?.location, '未能获取定位信息, 请重试');
          console.log('!answer?.location', !answer?.location);
          warn(typ == 'survey' && !answer?.sex, '请选择性别');
          warn(typ == 'survey' && !answer?.age, '请选择年龄段');
        } catch (error) {
          return;
        }
      }
    }

    setIndex(n);
  }

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

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

    if ((isNotEmpty(answerItem.answerCode) || isNotEmpty(answerItem.answer)) &&
      (typ == 'loc' ? answerItem.attachList?.length : true)) {
      // 说明这一题已经回答完毕
      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(checkItemInfo.itemId, answer).then(() => {
      setLoading(false);
      const t = setTimeout(() => {
        clearTimeout(t);
        Taro.navigateBack({ delta: 1 });
      }, 1000);
    }).catch(() => {
      setLoading(false);
    });
  }

  // 查询当前测评点位主记录
  React.useEffect(() => {
    if (id) {
      setLoading(true);
      getTaCheckItemById(id).then(res => {
        setLoading(false);
        setCheckItemInfo(res);
      }).catch(() => {
        setLoading(false);
      });
    }
  }, [id]);

  // 查询当前测评调查问卷主记录
  React.useEffect(() => {
    if (checkId && typ == 'survey') {
      setLoading(true);
      getTaCheckItemByCheck(checkId, typ).then(res => {
        setLoading(false);
        setCheckItemInfo(res);
      }).catch(() => {
        setLoading(false);
      });
    }
  }, [checkId, typ]);

  // 查询其他信息
  React.useEffect(() => {
    if (checkItemInfo?.itemId) {
      const { itemId } = checkItemInfo;
      setLoading(true);

      preCheck(itemId, { noSuccesTip: true }).then((checkRes) => {
        if (checkRes.errorCode < 0) {
          setLoading(false);
          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',
          // })
        }

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

        // 查询当前测评主记录的所有问题
        getTaCheckItemQu({ pageSize: 200, itemId }).then(res => {
          setLoading(false);
          setQuList(res.records || []);
        }).catch(() => {
          setLoading(false);
        });

      }).catch(() => {
        setLoading(false);
      });
    }
  }, [checkItemInfo]);

  // 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
                checkType={typ}
                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}
                    checkType={typ}
                    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>
  )
}
