import Moment from 'moment';
import UserApi from '../../network/api/userApi';
import ActionType from '../actions/types';
import {getMyInfo} from './CommonAction';
import {convertTimeToFloat} from '../../components/common/common';
import AuthApi from '../../network/api/authApi';
import ApiUrl from '../../network/api/apiUrl';
export const postUserLeave = (staff_id, leave, pathImg) => {
  return async (dispatch, getState) => {
    try {
      const arrHourStart = leave.timeStart.split(':');
      const arrHourFinish = leave.timeFinish.split(':');

      var formatStart = Moment(leave.since).utcOffset(0);
      formatStart
        .set({
          hour: parseInt(arrHourStart[0] - 7),
          minute: arrHourStart[1],
          second: 0,
          millisecond: 0,
        })
        .toISOString();
      formatStart.format();
      var formatFinish = Moment(leave.toDate).utcOffset(0);
      formatFinish
        .set({
          hour: parseInt(arrHourFinish[0] - 7),
          minute: arrHourFinish[1],
          second: 0,
          millisecond: 0,
        })
        .toISOString();
      formatFinish.format();

      const payload = {
        start: formatStart,
        finish: formatFinish,
        reason: leave.reason,
        leave_category_id: leave.id,
        approver_id: leave.approver_id,
      };

      // console.log('payload', payload);
      const response = await UserApi.requestPostLeave(payload);

      // console.log('response postUserLeave', response.success);
      if (response.success) {
        const responseGetLatestLeavesDay =
          await UserApi.requestGetLatestLeavesDay();
        //console.log("response GetLatestLeavesDay", response)

        // get latest leave
        if (responseGetLatestLeavesDay.success) {
          const {collection} = responseGetLatestLeavesDay.data;
          if (!pathImg || pathImg.length === 0) {
            dispatch(getUserLeaves('', '', 1, 5));
            // dispatch(
            //   sendNotification(
            //     leave.approver_id,
            //     'Thông báo có yêu nghỉ phép',
            //     'Yêu cầu nghỉ phép mới từ ABC',
            //     203,
            //     200,
            //   ),
            // );
            return true;
          }
          const initPayload = {
            code: collection[0].id,
            file_name: '',
            file_size: '',
            name: '',
            sub_code: '0',
          };
          let payload = initPayload;
          pathImg.forEach(async (item, index) => {
            payload.file_name = item.fileName;
            payload.file_size = item.fileSize;
            payload.name = item.fileName;
            payload.sub_code = '0';
            const responsePostImage = await UserApi.requestPostImage(payload);
            //console.log('payload', payload);
            if (responsePostImage.success) {
              //console.log('responsePostConfirmDay.data.id', responsePostConfirmDay.data.id);
              let uploadImage = new FormData();
              uploadImage.append('file', {
                uri: item.uri,
                name: item.fileName,
                type: item.type,
              });
              // send image to server
              const responsePostUpload = await UserApi.requestPostUpload(
                responsePostImage.data.id,
                uploadImage,
              );
              if (responsePostUpload.success) {
                //console.log('responsePostUpload', responsePostUpload);
              }
            }
            payload = {
              code: collection[0].id,
              file_name: '',
              file_size: '',
              name: '',
              sub_code: '0',
            };
          });
          dispatch(getUserLeaves('', '', 1, 5));
          // dispatch(
          //   sendNotification(
          //     leave.approver_id,
          //     'Thông báo có yêu nghỉ phép',
          //     'Yêu cầu nghỉ phép mới từ ABC',
          //     203,
          //     200,
          //   ),
          // );
          return true;
        }
      } else {
        return response.success;
      }
    } catch (err) {
      console.error(err);
    }
  };
};
export const getRandomQuotation = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetRandomQuotation();
    //console.log("response getRandomQuotation", response);
    if (response.success) {
      dispatch({
        type: ActionType.GET_QUOTES_SUCCESS,
        data: response.data,
      });
      //console.log("getRandomQuotation sucess")
    }
  };
};
export const getBirthDayUserByDate = (mm, yy) => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetBirthdayUser(mm, yy);
    if (response.success) {
      dispatch({
        type: ActionType.GET_BIRTHDAY_USER_SUCCESS,
        data: response.data,
      });
    }
  };
};
export const getUserOTVoucher = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetOtVoucher(
      filter,
      sort,
      page,
      pageSize,
    );
    if (response.success) {
      dispatch({
        type: ActionType.GET_OT_USER_SUCCESS,
        data: response.data.collection,
      });
      return response;
    }
  };
};
export const getUserOtVoucherPending = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetOtVoucherPending();

    //console.log("response GetOtVoucherPending", response);
    if (response.success) {
      dispatch({
        type: ActionType.GET_USER_OT_PENDING_SUCCESS,
        data: response.data.collection,
      });
    }
  };
};
export const getSalariesUser = staff_id => {
  return async (dispatch, getState) => {
    const responseGetBankAccount = await UserApi.requestGetBankAccount(
      staff_id,
    );
    //console.log("response getSalariesUser", responseGetBankAccount.data);
    if (responseGetBankAccount.success) {
      const resGetSaBook = await UserApi.requestGetSaBook();
      //console.log('resGetSaBook', resGetSaBook);
      if (resGetSaBook.success) {
        // const {sheet} = resGetSaBook.data;
        // //console.log("sheet", sheet.id)
        // const resGetSaPayslipSections =
        //   await UserApi.requestGetSaPayslipSections(sheet.id);
        // //console.log("resGetSaPayslipSections", resGetSaPayslipSections)
        // if (resGetSaPayslipSections.success) {
        //   const {collection} = resGetSaPayslipSections.data;
        //   //console.log('collection resGetSaPayslipSections', collection);
        //   const resGetSalary = await UserApi.requestGetSalary(
        //     collection[0].id,
        //     sheet.id,
        //   );
        //   //console.log("resGetSalary", resGetSalary)
        //   if (resGetSalary.success) {
        //     const resGetAllowance = await UserApi.requestGetAllowance(
        //       collection[0].id,
        //       sheet.id,
        //     );
        //     if (resGetAllowance.success) {
        //       //console.log("resGetAllowance", resGetAllowance)
        //       dispatch({
        //         type: ActionType.GET_USER_SALARY_SUCCESS,
        //         data: resGetSalary.data.collection,
        //         bank: responseGetBankAccount.data.collection,
        //         allowance: resGetAllowance.data.collection,
        //         saBooks: resGetSaBook.data.collection,
        //       });
        //     }
        //   }
        // }
        dispatch({
          type: ActionType.GET_USER_SALARY_SUCCESS,
          bank: responseGetBankAccount.data.collection,
          saBooks: resGetSaBook.data.collection,
        });
      }
      //console.log("requestPostLeave success")
    }
  };
};
export const getPaySlipSections = sheetId => {
  return async (dispatch, getState) => {
    const resGetUserSaSheet = await UserApi.requestGetUserPayslipSaBook(
      sheetId,
    );
    //console.log(' resGetUserSaSheet', resGetUserSaSheet);
    if (resGetUserSaSheet.success) {
      const {sheet} = resGetUserSaSheet.data;
      const resGetSaPayslipSections = await UserApi.requestGetSaPayslipSections(
        sheet.id,
      );

      if (resGetSaPayslipSections.success) {
        let arrSalary = [];
        const {collection} = resGetSaPayslipSections.data;
        //console.log('collection', collection);
        for (let i = 0; i < collection.length; i++) {
          const resGetSalary = await UserApi.requestGetSalary(
            collection[i].id,
            collection[i].sheet_id,
          );
          //console.log('resGetSalary', resGetSalary);
          if (resGetSalary.success) {
            const {collection} = resGetSalary.data;
            arrSalary.push(...collection);
          }
        }
        return arrSalary;
      }
    }
  };
};
export const getUserSheet = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetSheet();
    //console.log('response getUserSheet', response.data);
    if (response.success) {
      dispatch({
        type: ActionType.GET_USER_SALARY_SUCCESS,
        data: response.data.collection,
      });
      //console.log("requestPostLeave success")
    }
  };
};
export const getUserDirectManagers = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetMyDirectManagers();
    if (response.success) {
      dispatch({
        type: ActionType.GET_USER_MANAGERS_SUCCESS,
        data: response.data,
      });
      return response.data;
    }
  };
};
// get leader list
export const getManagers = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetMyManagers();
    if (response.success) {
      // dispatch({
      //   type: ActionType.GET_USER_MANAGERS_SUCCESS,
      //   data: response.data,
      // });
      return response;
    }
  };
};
export const getPersonnel = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetPersonnel();
    if (response.success) {
      const {collection} = response.data;
      //console.log(collection);
      return collection;
    }
  };
};

export const getUserLeaves = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    //console.log('getUserLeaves');
    const response = await UserApi.requestGetLeavesDay(
      filter,
      sort,
      page,
      pageSize,
    );
    const resGetDataChartLeft = await UserApi.requestGetRestDay();
    if (response.success && resGetDataChartLeft.success) {
      dispatch({
        type: ActionType.GET_LEAVES_SUCCESS,
        data: response.data.collection,
        rest: resGetDataChartLeft.data.collection,
      });
      return response;
    }
  };
};
export const getUserLeavesPending = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetLeavesDayPending(
      filter,
      sort,
      page,
      pageSize,
    );

    const resGetLeaveCategories = await UserApi.requestGetLeaveCategories();
    //console.log("response ", response);
    if (response.success) {
      if (resGetLeaveCategories.success) {
        dispatch({
          type: ActionType.GET_USER_LEAVES_PENDING_SUCCESS,
          data: response.data.collection,
          category: resGetLeaveCategories.data,
        });
        return response;
      }
    }
  };
};
export const getUserLeaveDayApproveReq = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    // console.log(
    //   ApiUrl.LEAVES_DAY_APPROVE_REQ +
    //     `?Filters=${filter}&Sorts=${sort}&Page=${page}&PageSize=${pageSize}`,
    // );
    const response = await UserApi.requestGetLeaveDayApproveReq(
      filter,
      sort,
      page,
      pageSize,
    );
    const resGetLeaveCategories = await UserApi.requestGetLeaveCategories();
    //console.log("response ", response);
    if (response.success) {
      if (resGetLeaveCategories.success) {
        dispatch({
          type: ActionType.GET_USER_LEAVES_PENDING_SUCCESS,
          data: response.data.collection,
          category: resGetLeaveCategories.data,
        });
        return response;
      }
    }
  };
};
export const deleteLeaveTicket = ticketId => {
  return async (dispatch, getState) => {
    try {
      const resDeleteLeaveTicket = await UserApi.requestDeleteLeaveTicket(
        ticketId,
      );
      //console.log("response ", response);
      if (resDeleteLeaveTicket.success) {
        dispatch(getUserLeaves('', '', 1, 5));
        return true;
      }
      return false;
    } catch (err) {
      console.log('err', err);
    }
  };
};
export const getUserLeavesById = id => {
  return async (dispatch, getState) => {
    //console.log('getUserLeaves');
    const response = await UserApi.requestGetLeavesDayById(id);
    if (response.success) {
      return response.data;
    }
  };
};

// confirm date
export const getUserConfirmDay = (page, pageSize) => {
  return async (dispatch, getState) => {
    //console.log(ApiUrl.CONFIRM_DAY + `?Page=${page}&PageSize=${pageSize}`);
    const response = await UserApi.requestGetConfirmDay(page, pageSize);

    //console.log('response getUserConfirmDay', response);
    if (response.success) {
      //console.log('response getUserConfirmDay', response);
      dispatch({
        type: ActionType.GET_CONFIRM_DAY_SUCCESS,
        data: response.data.collection,
      });
      return response;
    }
  };
};
export const getApproveConfirmDay = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    // console.log(
    //   ApiUrl.APPROVE_CONFIRM_DAY +
    //     `?Filters=${filter}&Sorts=${sort}&Page=${page}&PageSize=${pageSize}`,
    // );
    const response = await UserApi.requestGetApproveConfirmDay(
      filter,
      sort,
      page,
      pageSize,
    );
    //console.log("response getUserConfirmDay", response);
    if (response.success) {
      dispatch({
        type: ActionType.GET_APPROVE_CONFIRM_DAY_SUCCESS,
        data: response.data.collection,
      });
      return response;
    }
  };
};
export const getAbsentChart = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetAbsentChart();
    //console.log('response ', response);
    if (response.success) {
      return response.data;
    }
  };
};

export const deleteApproveConfirmDay = id => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestDeleteConfirmApprove(id);
    //console.log("response getUserConfirmDay", response);
    if (response.success) {
      dispatch(getUserConfirmDay(1, 5));
      return response;
    }
  };
};
//get confirm histories approve
export const getConfirmDayHistories = id => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetConfirmDayHistories(id);
    if (response.success) {
      return response.data.collection;
    }
  };
};
export const getTimeSheetProject = () => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetTimeSheetProject();
    // console.log("response getTimeSheetProject", response.data.collection);
    if (response.success) {
      const {collection} = response.data;
      dispatch({
        type: ActionType.GET_TIME_SHEET_PROJECT_SUCCESS,
        data: collection,
      });
      return collection;
    }
  };
};
export const getTimeSheetApprovalProject = (
  numberWeekOfYear,
  page,
  searchQuery,
) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetTimeSheetApproval(
        numberWeekOfYear,
        page,
        searchQuery,
      );
      if (response.success) {
        return response.data;
      }
    } catch {
      console.log('Error when getTimeSheetApprovalProject');
    }
  };
};
export const getJobNameProject = projectId => {
  return async (dispatch, getState) => {
    const response = await UserApi.requestGetJobName(projectId);
    //console.log("response getJobNameProject", response);
    if (response.success) {
      const {collection} = response.data;
      // dispatch({
      //     type: ActionType.GET_TIME_SHEET_PROJECT_SUCCESS,
      //     data: collection,
      // })
      return collection;
    }
  };
};
export const postUserConfirmDay = (managerId, confirmInfo, pathImg) => {
  return async (dispatch, getState) => {
    //console.log(confirmInfo);
    const arrHourStart = Moment(confirmInfo.hourSince)
      .format('HH:mm')
      .split(':');
    const arrHourFinish = Moment(confirmInfo.hourFinish)
      .format('HH:mm')
      .split(':');
    let formatStart = Moment(confirmInfo.since)
      .utcOffset(0)
      .set('hour', 0)
      .set('minute', 0)
      .set('second', 0);
    formatStart.toISOString();
    formatStart.format();
    let formatFinish = Moment(confirmInfo.finish)
      .utcOffset(0)
      .set('hour', 0)
      .set('minute', 0)
      .set('second', 0);
    formatFinish.toISOString();
    formatFinish.format();
    if (parseInt(arrHourStart[0] - 7, 10) < 0) {
      formatStart.subtract(1, 'day');
    }
    if (parseInt(arrHourFinish[0] - 7, 10) < 0) {
      formatFinish.subtract(1, 'day');
    }
    formatStart
      .set('hour', parseInt(arrHourStart[0] - 7, 10))
      .set('minute', arrHourStart[1])
      .set('second', 0);
    formatFinish
      .set('hour', parseInt(arrHourFinish[0] - 7, 10))
      .set('minute', arrHourFinish[1])
      .set('second', 0);
    const payload = {
      approver_id: managerId,
      finish: formatFinish,
      reason: confirmInfo.reason,
      start: formatStart,
      timeFinish: Moment(confirmInfo.hourFinish).format('HH:mm'),
      timeStart: Moment(confirmInfo.hourSince).format('HH:mm'),
    };

    //console.log('payload', payload);
    const responsePostConfirmDay = await UserApi.requestPostConfirmDay(payload);

    //console.log('response getUserConfirmDay', responsePostConfirmDay);
    if (responsePostConfirmDay.success) {
      if (pathImg.length > 0) {
        const initPayload = {
          code: responsePostConfirmDay.data.id,
          file_name: '',
          file_size: '',
          name: '',
          sub_code: '0',
        };
        let payload = initPayload;
        pathImg.forEach(async (item, index) => {
          payload.file_name = item.fileName;
          payload.file_size = item.fileSize;
          payload.name = item.fileName;
          payload.sub_code = '0';
          const responsePostImage = await UserApi.requestPostImage(payload);
          //console.log('payload', payload);
          if (responsePostImage.success) {
            //console.log('responsePostConfirmDay.data.id', responsePostConfirmDay.data.id);
            let uploadImage = new FormData();
            uploadImage.append('file', {
              uri: item.uri,
              name: item.fileName,
              type: item.type,
            });
            // send image to server
            const responsePostUpload = await UserApi.requestPostUpload(
              responsePostImage.data.id,
              uploadImage,
            );
            if (responsePostUpload.success) {
              //console.log('responsePostUpload', responsePostUpload);
            }
          }
          payload = {
            code: responsePostConfirmDay.data.id,
            file_name: '',
            file_size: '',
            name: '',
            sub_code: '0',
          };
        });
        //console.log('arrPayload', arrPayload);
      }
      dispatch(getUserConfirmDay(1, 5));
      return responsePostConfirmDay;
      //console.log('responsePostConfirmDay.success');
    }
  };
};
export const postUserOTVoucher = (otVoucher, pathImg) => {
  return async (dispatch, getState) => {
    try {
      const arrHourStart = Moment(otVoucher.timeStart)
        .format('HH:mm')
        .split(':');
      const arrHourFinish = Moment(otVoucher.timeFinish)
        .format('HH:mm')
        .split(':');

      var formatStart = Moment(otVoucher.start).utcOffset(0);
      formatStart
        .set({
          hour: parseInt(arrHourStart[0] - 7),
          minute: arrHourStart[1],
          second: 0,
          millisecond: 0,
        })
        .toISOString();
      formatStart.format();
      var formatFinish = Moment(otVoucher.finish).utcOffset(0);
      formatFinish
        .set({
          hour: parseInt(arrHourFinish[0] - 7),
          minute: arrHourFinish[1],
          second: 0,
          millisecond: 0,
        })
        .toISOString();
      formatFinish.format();
      const payload = {
        approver_id: otVoucher.approver_id,
        start: formatStart,
        finish: formatFinish,
        reason: otVoucher.reason,
        timeFinish: Moment(otVoucher.timeFinish).format('HH:mm'),
        timeStart: Moment(otVoucher.timeStart).format('HH:mm'),
      };
      //console.log('Check payload', payload);
      const response = await UserApi.requestPostOTVoucher(payload);
      //console.log('postUserOTVoucher', response);
      if (response.success) {
        if (pathImg.length > 0) {
          const initPayload = {
            code: response.data.id,
            file_name: '',
            file_size: '',
            name: '',
            sub_code: '0',
          };
          let payload = initPayload;
          pathImg.forEach(async (item, index) => {
            payload.file_name = item.fileName;
            payload.file_size = item.fileSize;
            payload.name = item.fileName;
            payload.sub_code = '0';
            const responsePostImage = await UserApi.requestPostImage(payload);
            //console.log('payload', payload);
            if (responsePostImage.success) {
              //console.log('responsePostConfirmDay.data.id', responsePostConfirmDay.data.id);
              let uploadImage = new FormData();
              uploadImage.append('file', {
                uri: item.uri,
                name: item.fileName,
                type: item.type,
              });
              // send image to server
              const responsePostUpload = await UserApi.requestPostUpload(
                responsePostImage.data.id,
                uploadImage,
              );
              if (responsePostUpload.success) {
                console.log('responsePostUpload success');
              }
            }
            payload = {
              code: response.data.id,
              file_name: '',
              file_size: '',
              name: '',
              sub_code: '0',
            };
          });
          //console.log('arrPayload', arrPayload);
        }
        return true;
      } else {
        return false;
      }
    } catch (err) {
      console.log('Have error when call postUserOTVoucher:', err);
    }
  };
};

export const changeAvatar = (userID, pathImg) => {
  return async (dispatch, getState) => {
    let uploadImage = new FormData();
    for (let i = 0; i < pathImg.length; i++) {
      uploadImage.append('file', {
        uri: pathImg[i].uri,
        name: pathImg[i].fileName,
        type: pathImg[i].type,
      });
    }
    const responsePostUpload = await UserApi.requestChangeAvatar(
      userID,
      uploadImage,
    );
    //console.log("responsePostUpload", responsePostUpload)
    if (responsePostUpload.success) {
      //console.log("requestPostLeave success")
      dispatch(getMyInfo());
      return true;
    }
  };
};
export const changeCoverAvatar = (userID, pathImg) => {
  return async (dispatch, getState) => {
    let uploadImage = new FormData();
    for (let i = 0; i < pathImg.length; i++) {
      uploadImage.append('file', {
        uri: pathImg[i].uri,
        name: pathImg[i].fileName,
        type: pathImg[i].type,
      });
    }
    const responseChangeCoverAvatar = await UserApi.requestChangeCoverAvatar(
      userID,
      uploadImage,
    );
    //console.log('responseChangeCoverAvatar', responseChangeCoverAvatar);
    if (responseChangeCoverAvatar.success) {
      //console.log("requestPostLeave success")
      dispatch(getMyInfo());
      return true;
    }
  };
};

export const changeUserInfo = (userID, info) => {
  return async (dispatch, getState) => {
    const responseChangeInfo = await UserApi.requestChangeInfo(userID, info);
    //console.log("responseChangeInfo", responseChangeInfo)
    if (responseChangeInfo.success) {
      //console.log("requestPostLeave success")
      dispatch(getMyInfo());
      return true;
    }
  };
};

//OT
export const getMyOverTimeStatistic = () => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetOtVoucherStatisticChart();
      if (response.success) {
        return response.data;
      } else {
        console.log('Have error when getMyOverTimeStatistic');
      }
    } catch {
      console.log('Have error when getMyOverTimeStatistic');
    }
  };
};

export const getOTbyId = OTId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetOtVoucherById(OTId);
      if (response.success) {
        return response.data;
      }
    } catch {
      console.log('Have error when getOTbyUserId');
    }
  };
};

export const getAttachmentByOTId = OTId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetImageList(OTId);
      if (response.success) {
        return response.data.collection;
      }
    } catch {
      console.log('Have error when getAttachmentByOTId');
    }
  };
};

export const getOTHistoriesByOTId = OTId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetOTHistoriesByID(OTId);
      if (response.success) {
        return response.data.collection;
      }
    } catch {
      console.log('Have error when getAttachmentByOTId');
    }
  };
};

export const postApproveOTVoucher = payload => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostApproveOTVoucher(payload);
      if (response.success) {
        return true;
      } else {
        return false;
      }
    } catch {
      console.log('Have error when postApproveOTVoucher');
    }
  };
};
export const postRejectOTVoucher = (otId, comment) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostRejectOTVoucher(otId, comment);
      if (response.success) {
        dispatch(getApproveReqVoucherList(1, 5));
        return true;
      } else {
        return false;
      }
    } catch {
      console.log('Have error when postApproveOTVoucher');
    }
  };
};
export const deleteOtTicketRequest = OTId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestDeleteOtVoucher(OTId);
      if (response.success) {
        dispatch(getUserOTVoucher('', '', 1, 5));
        return response.success;
      }
    } catch {
      console.log('Have error when getAttachmentByOTId');
    }
  };
};

// pending need approve
export const getApproveReqVoucherList = (filter, sort, page, pageSize) => {
  return async (dispatch, getState) => {
    try {
      // console.log(
      //   ApiUrl.GET_OT_VOUCHER_PENDING +
      //     `?Filter=${filter}&Sorts=${sort}&Page=${page}&PageSize=${pageSize}`,
      // );
      const response = await UserApi.requestGetOtApproveVoucherList(
        filter,
        sort,
        page,
        pageSize,
      );
      //console.log('getApproveReqVoucherList', response.data.collection);
      if (response.success) {
        dispatch({
          type: ActionType.GET_USER_OT_PENDING_SUCCESS,
          data: response.data.collection,
        });
        return response;
      }
    } catch {
      console.log('Have error when getMyOTVoucherList');
    }
  };
};

export const postNewComment = payload => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostComment(payload);
      if (response.success) {
        //console.log('run 100', response);
        return response.data;
      }
    } catch {
      console.log('Have error when postNewComment');
    }
  };
};

export const getCommentList = payload => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetComment(payload);
      if (response.success) {
        return response.result;
      }
    } catch {
      console.log('Have error when postNewComment');
    }
  };
};

export const postLikeComment = payload => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostCommentLike(payload);
      if (response.success) {
        return response.data;
      }
    } catch {
      console.log('Have error when postLikeComment');
    }
  };
};

export const getCommentByCode = code => {
  return async () => {
    const response = await UserApi.requestGetCommentByCode(code);
    if (response.success) {
      return response.data.collection;
    }
  };
};

export const postUserAddJob = (year, weekNumber, payload) => {
  return async (dispatch, getState) => {
    //console.log('payload', payload);
    try {
      const responsePostAddJob = await UserApi.requestPostAddJob(
        year,
        weekNumber,
        payload,
      );
      //console.log('responsePostAddJob', responsePostAddJob);
      if (responsePostAddJob.success) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('err postUserAddJob:', e);
      dispatch({
        type: ActionType.POST_JOB_OF_USER_FAILED,
      });
    }
  };
};
export const postSubmitUserAddJob = (week_id, approver_id, week_note) => {
  return async (dispatch, getState) => {
    //console.log("week_id", week_id,approver_id,week_note)
    try {
      const payload = {
        approver_id: approver_id,
        week_notes: week_note || null,
      };
      const responsePostSubmitAddJob = await UserApi.requestPostSubmitAddJob(
        week_id,
        payload,
      );
      //console.log("responsePostSubmitAddJob", responsePostSubmitAddJob)
      if (responsePostSubmitAddJob.success) {
        dispatch({
          type: ActionType.POST_JOB_OF_USER_SUCCESS,
        });
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('err postUserAddJob:', e);
      dispatch({
        type: ActionType.POST_JOB_OF_USER_FAILED,
      });
    }
  };
};
export const approveReqTimeSheet = timesheetId => {
  return async (dispatch, getState) => {
    try {
      //console.log('timesheetId', timesheetId);
      const response = await UserApi.requestApproveTimeSheet(timesheetId);
      console.log('approveReqTimeSheet', response);
      if (response.success) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('err approveReqTimeSheet:', e);
    }
  };
};
export const rejectReqTimeSheet = timesheetId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestRejectTimeSheet(timesheetId);
      console.log('rejectReqTimeSheet', response);
      if (response.success) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log('err approveReqTimeSheet:', e);
    }
  };
};
export const getUserJob = (year, weekNumber) => {
  return async (dispatch, getState) => {
    //console.log("weekNumber", weekNumber)
    try {
      dispatch({
        type: ActionType.START_GET_JOB_OF_USER,
      });
      const responseGetMyTimeSheet = await UserApi.requestGetMyTimeSheet(
        year,
        weekNumber,
      );
      //console.log("getUserJob", responseGetMyTimeSheet)
      if (responseGetMyTimeSheet.success) {
        //console.log("requestPostLeave success")
        dispatch({
          type: ActionType.GET_JOB_OF_USER_SUCCESS,
        });
        return responseGetMyTimeSheet.data;
      } else {
        dispatch({
          type: ActionType.GET_JOB_OF_USER_FAILED,
        });
      }
    } catch (e) {
      console.error('err:', e);
      dispatch({
        type: ActionType.GET_JOB_OF_USER_FAILED,
      });
    }
  };
};

export const getDescriptionTimekeeping = (filter, page, pageSize, sort) => {
  return async (dispatch, getState) => {
    try {
      // console.log(
      //   'options',
      //   ApiUrl.GET_TIME_KEEPING_BY_FILTER +
      //     `?Filters=${filter}&Sorts=${sort}&Page=${page}&PageSize=${pageSize}`,
      // );
      const response = await UserApi.requestGetTimeKeeping(
        filter,
        page,
        pageSize,
        sort,
      );
      //console.log(response)
      if (response.success) {
        //console.log("finish", options)

        return response.data;
      }
    } catch (err) {
      console.error('err getDescriptionTimekeeping', err);
      dispatch({
        type: ActionType.GET_TIME_KEEPING_FAILED,
      });
    }
  };
};
export const getDataChartTimekeeping = (since, finish) => {
  return async (dispatch, getState) => {
    dispatch({
      type: ActionType.START_GET_DATA_CHART,
    });
    const response = await UserApi.requestDataChartTimeKeeping(since, finish);
    //console.log(response)
    if (response.success) {
      //console.log("finish", options)
      dispatch({
        type: ActionType.GET_DATA_CHART_SUCCESS,
      });
      return response.data;
    } else {
      dispatch({
        type: ActionType.GET_DATA_CHART_FAILED,
      });
    }
  };
};

export const postAttachmentToComment = (commentId, payload) => {
  return async (dispatch, getState) => {
    try {
      let uploadImage = new FormData();
      for (let i = 0; i < payload.length; i++) {
        uploadImage.append('file', {
          uri: payload[i].uri,
          name: payload[i].fileName,
          type: payload[i].type,
        });
      }
      console.log('check fomr data', uploadImage);
      console.log('cehck comment id', commentId);
      const response = await UserApi.requestPostAttachmentComment(
        commentId,
        uploadImage,
      );
      if (response.success) {
        return response.data;
      }
    } catch {
      console.log('Have error when postAttachmentToComment');
    }
  };
};

export const getUserLeaveHistories = id => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetLeaveHistories(id);
      if (response.success) {
        return response.data.collection;
      }
    } catch {
      console.log('error when take user leave histories');
    }
  };
};

export const postComment = payload => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostComment(payload);
      if (response.success) {
        return true;
      }
    } catch (error) {
      console.log('error when take comment', error);
    }
  };
};
export const postApproveLeaveDay = (id, comment, nextApproverId) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostLeaveApprove(
        id,
        comment,
        nextApproverId,
      );
      if (response.success) {
        // dispatch(getUserLeavesPending('', '', 1, 5));
        return true;
      }
    } catch (error) {
      console.log('error when take approve leave days', error);
    }
  };
};
export const postRejectLeaveDay = (id, comment) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostLeaveReject(id, comment);
      if (response.success) {
        return true;
      }
    } catch (error) {
      console.log('error when take reject leave day', error);
    }
  };
};
export const getImageByCode = code => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetImage(code);
      //console.log("getImageByCode", code)
      if (response.success) {
        return response.data.collection;
      }
    } catch (error) {
      console.log('error when take image', error);
    }
  };
};
export const getContactUser = userID => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetContactUser(userID);
      //console.log("response", response)
      if (response.success) {
        return response.data.collection;
      }
    } catch (error) {
      console.log('error when take image', error);
    }
  };
};
export const changeContactUser = (itemId, contact_unique_id, type) => {
  return async (dispatch, getState) => {
    try {
      //console.log("itemId", itemId, contact_unique_id, type)
      const payload = {
        contact_unique_id: contact_unique_id,
        type: type,
      };
      const response = await UserApi.requestChangeContactUser(itemId, payload);
      //console.log("response", response)
      return response;
    } catch (error) {
      console.log('error ', error);
    }
  };
};
export const deleteContactUser = itemId => {
  return async (dispatch, getState) => {
    try {
      //console.log("itemId", itemId)
      const response = await UserApi.requestDeleteContactUser(itemId);
      //console.log('response', response);
      return response;
    } catch (error) {
      console.log('error ', error);
    }
  };
};
export const addContactUser = (userId, contact_unique_id, type) => {
  return async (dispatch, getState) => {
    try {
      //console.log("itemId", itemId)
      const payload = {
        contact_unique_id: contact_unique_id,
        type: type,
      };
      const response = await UserApi.requestAddContactUser(userId, payload);
      //console.log("response", response)
      if (response.success) return response;
    } catch (error) {
      console.log('error ', error);
    }
  };
};
export const sendEmail = email => {
  return async (dispatch, getState) => {
    try {
      //console.log("itemId", itemId)

      const response = await AuthApi.requestSendMail(email);
      console.log('response', response);
      return response;
    } catch (error) {
      console.log('error ', error);
    }
  };
};
export const postApproveConfirmDate = (id, comment, nextApproverId) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostConfirmApprove(
        id,
        (comment && comment) || '',
        nextApproverId,
      );
      if (response.success) {
        return true;
      }
    } catch (error) {
      console.log('something error in approve', error);
    }
  };
};
export const postRejectConfirmDate = (id, comment) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestPostRejectApprove(id, comment);
      if (response.success) {
        return true;
      }
    } catch (error) {
      console.log('something error in reject', error);
    }
  };
};
export const getRangeTimeStart = (startDate, userID) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetRangeTimeStart(
        startDate,
        userID,
      );
      if (response.success) {
        //list
        return response.data;
      }
    } catch (error) {
      console.log('something error in get range date start', error);
    }
  };
};
export const getRangeTimeFinish = (startDate, userID) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetRangeTimeFinish(
        startDate,
        userID,
      );
      if (response.success) {
        //list
        return response.data;
      }
    } catch (error) {
      console.log('something error in get range date finish', error);
    }
  };
};

export const getConfirmSheetDetail = (userId, numberOfWeek, year) => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetConfirmTimeSheetDetail(
        userId,
        year,
        numberOfWeek,
      );
      //console.log('response', response);
      if (response.success) {
        return response.data;
      }
    } catch (error) {
      console.log('something error in getConfirmSheetDetail', error);
    }
  };
};

export const getUserInfoById = userId => {
  return async (dispatch, getState) => {
    try {
      const response = await UserApi.requestGetUserInfoById(userId);
      if (response.success) {
        return response.data;
      }
    } catch (error) {
      console.log('something error in getUserInfoById', error);
    }
  };
};
// notification
export const getNotificationOfUser = queryParams => {
  return async dispatch => {
    try {
      //console.log(ApiUrl.GET_NOTIFICATION + queryParams);
      const response = await UserApi.requestGetNotification(queryParams);
      //console.log("response", response.data);
      if (response.success) {
        const {collection} = response.data;
        return collection;
      } else {
        console.log('Have error when getNotificationOfUser');
      }
    } catch {
      console.log('Have error when getNotificationOfUser');
    }
  };
};
export const readNotificationUser = id => {
  return async dispatch => {
    try {
      const response = await UserApi.requestReadNotification(id);
      //console.log("response", response);
      if (response.success) {
        return response;
      } else {
        console.log('Have error when readNotificationUser');
      }
    } catch {
      console.log('Have error when readNotificationUser');
    }
  };
};
export const deleteNotificationUser = id_noti => {
  return async dispatch => {
    try {
      const response = await UserApi.requestDeleteNotification(id_noti);
      if (response.success) {
        return response;
      } else {
        console.log('Have error when deleteNotificationUser');
      }
    } catch {
      console.log('Have error when deleteNotificationUser');
    }
  };
};
// getCompanyInfo
export const getCompanyInfo = () => {
  return async dispatch => {
    try {
      const response = await UserApi.requestGetCompanyInfo();
      //console.log("response", response.data);
      if (response.success) {
        return response;
      } else {
        console.log('Have error when getCompanyInfo');
      }
    } catch {
      console.log('Have error when getCompanyInfo');
    }
  };
};
// notification
export const sendNotification = (
  approver_id,
  sender_id,
  img,
  title,
  message,
  type,
  code_group,
) => {
  return async dispatch => {
    try {
      //console.log('img', img);
      if (img && img.length > 0) {
        const payloadImg = {
          code: approver_id,
          file_name: img[0].file_name,
          file_size: img[0].file_size,
          name: img[0].file_name,
          sub_code: '0',
        };

        const responsePostImage = await UserApi.requestPostImage(payloadImg);
        //console.log('responsePostImage', responsePostImage);
        if (responsePostImage.success) {
          //console.log('responsePostConfirmDay.data.id', responsePostConfirmDay.data.id);
          let uploadImage = new FormData();
          uploadImage.append('file', {
            uri: img[0].uri,
            name: img[0].fileName,
            type: img[0].type,
          });
          // send image to server
          const responsePostUpload = await UserApi.requestPostPublicUpload(
            responsePostImage.data.id,
            uploadImage,
          );
          if (responsePostUpload.success) {
            const {data} = responsePostUpload;
            const payload = {
              sTitle: title,
              sDetails: message,
              type: type,
              sCodeForGrouping: code_group,
            };
            const response = await UserApi.requestSenNotificationByUserId(
              approver_id,
              sender_id,
              data.physical_path,
              payload,
            );
            //console.log('response', response);
            if (response.success) {
              console.log('requestSenNotificationByUserId with image success');
              return response;
            } else {
              console.log('Have error when sendNotification');
            }
            //console.log('responsePostUpload', responsePostUpload);
          }
        }
      } else {
        const payload = {
          sTitle: title,
          sDetails: message,
          type: type,
          sCodeForGrouping: code_group,
        };
        const response = await UserApi.requestSenNotificationByUserId(
          approver_id,
          sender_id,
          '',
          payload,
        );
        //console.log('response', response);
        if (response.success) {
          console.log('requestSenNotificationByUserId no image success');
          return response;
        } else {
          console.log('Have error when sendNotification');
        }
      }
    } catch {
      console.log('Have error when sendNotification');
    }
  };
};
