import { Toast } from 'antd-mobile';
import { NavigationActions } from 'react-navigation';
import { getData, getMeta } from '../../utils/DataTemplate';
import { datasourceApi } from '../../services/datasource';
import { scan } from '../../services/idcard';

export default {
  namespace: 'DSRInfoDetail',
  state: {
    singularData: {},
    metas: [],
    enableEdit: false,
    DSRID: '',
  },
  reducers: {
    setList(state, { payload }) {
      return { ...state, singularData: payload.singularData };
    },
    setSingularData(state, { payload }) {
      const { singularData } = state;
      if (singularData.dangShiRenXingMing !== undefined) {
        singularData.dangShiRenXingMing = payload.peopleName;
      }
      if (singularData.dangShiRenIdentityCard !== undefined) {
        singularData.dangShiRenIdentityCard = payload.idcard;
      }
      if (singularData.dangShiRenXingBie !== undefined) {
        singularData.dangShiRenXingBie = payload.sex;
      }

      return { ...state, singularData };
    },
    setEnable(state, { payload: enableEdit }) {
      return { ...state, enableEdit };
    },
    setMetas(state, { payload }) {
      return { ...state, metas: payload };
    },
    setDSRID(state, { payload }) {
      return {
        ...state,
        DSRID: payload,
      };
    },
  },
  effects: {
    *getDSRInfoDetail({ payload }, { call, put }) {
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRInfo',
        datasourceName: 'QueryDSRInfoDetails',
      };
      const result = yield call(getData, coordinate, { pst: 0, psz: 10, params: { pID: payload } });
      const singularData = result[0];
      yield put({ type: 'setDSRID', payload });
      yield put({ type: 'setList', payload: { singularData: { ...singularData } } });
      const metas = yield call(getMeta, coordinate);
      yield put({ type: 'setMetas', payload: metas });
    },
    *updateDSRInfoDetail({ payload }, { call, put }) {
      const coordinate = {
        containerType: 'module',
        containerName: 'query-DSRInfo',
        datasourceName: 'QueryDSRInfoDetails',
      };
      const api = datasourceApi(coordinate);
      yield call(api.update, payload.id, payload.singularData);
      Toast.success('修改成功!', 1);
      yield put(NavigationActions.navigate({
        routeName: 'DSRInfoList',
      }));
      yield put({ type: 'setEnable', payload: false });
    },
    *DuKa(ignored, { call, put }) {
      try {
        const result = yield call(scan);
        if (result) {
          yield put({ type: 'setSingularData', payload: result });
        }
      } catch (e) {
        console.log(e);
        throw e;
      }
      //
    },
  },
};
