package com.mortals.xhx.module.attendance.web;

import cn.hutool.core.util.StrUtil;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.attendance.model.AttendanceExportRecordEntity;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikEntity;
import com.mortals.xhx.module.attendance.service.AttendanceExportRecordService;
import com.mortals.xhx.module.attendance.service.AttendanceRecordHikService;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 海康考勤打卡记录汇总信息
 *
 * @author zxfei
 * @date 2023-04-08
 */
@RestController
@RequestMapping("attendance/record/hik")
public class AttendanceRecordHikController extends BaseCRUDJsonBodyMappingController<AttendanceRecordHikService, AttendanceRecordHikEntity, Long> {

    @Autowired
    private ParamService paramService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private AttendanceExportRecordService attendanceExportRecordService;
    @Autowired
    private AttendanceRecordHikService hikService;

    public AttendanceRecordHikController() {
        super.setModuleDesc("海康考勤打卡记录汇总信息");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        super.init(model, context);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doImportDataBefore(List<AttendanceRecordHikEntity> list, boolean updateSupport, Context context) throws AppException {


        list.forEach(item -> {
            String orgName = item.getOrgName();
            //todo split orgName to deptId and deptName
            String[] split = orgName.split("/");

            String deptName = split[split.length - 1];
            DeptQuery deptQuery = new DeptQuery();
            deptQuery.setDeptName(deptName);
            //通过分解的deptName去获取部门信息
            List<DeptEntity> deptEntities = deptService.find(deptQuery);
            Long deptId = 0L;
            //判断查出来的部门信息是否为一个,是的话直接获取id,不是的话获取部门的父级id,通过父级id和deptName去查部门id
            if (StringUtils.isNotNull(deptEntities) && deptEntities.size() == 1) {
                deptId = deptEntities.get(0).getId();
            } else {
                String parentDeptName = split[split.length - 2];

                deptQuery.setDeptName(parentDeptName);
                DeptEntity deptEntity = deptService.selectOne(deptQuery);

                deptQuery.setDeptName(deptName);
                deptQuery.setParentId(deptEntity.getParentId());
                DeptEntity dept = deptService.selectOne(deptQuery);
                deptId = dept.getId();
            }
            //通过工号去查询员工信息
            String workNum = item.getWorkNum();
            String replace = StrUtil.replace(workNum, "\t", "");
            StaffEntity staffEntity = staffService.selectOne(new StaffQuery().workNum(replace));
            item.setWorkNum(replace);
            item.setStaffId(staffEntity.getId());
            item.setDeptId(deptId);
            item.setDeptName(deptName);
            item.setPositionId(staffEntity.getPositionId());
            item.setPositionName(staffEntity.getPositionName());
        });
        //存入海康打卡原始数据 mortals_xhx_attendance_record_hik
        super.doImportDataBefore(list, updateSupport, context);
    }

    @Override
    protected int batchSaveAfter(List<AttendanceRecordHikEntity> list, Map<String, Object> model, Context context) throws AppException {
        return super.batchSaveAfter(list, model, context);
    }

    @PostMapping(value = "/addAttendanceRecord")
    public Rest<String> addAttendanceRecord(@RequestBody AttendanceRecordHikEntity hikEntity) {
        Rest<String> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询" + this.getModuleDesc();
        int code = 1;
        try {
            if (ObjectUtils.isEmpty(hikEntity.getAttendanceDateStart())) {
                throw new AppException("请选择开始日期");
            }
            hikService.addAttendanceRecordByQuery(hikEntity, getContext());
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = -1;
            this.doException(this.request, busiDesc, model, e);
            model.put("message_info", e.getMessage());
        }

        this.init(model, context);
        ret.setCode(code);
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;

    }


    @Override
    protected void doListBefore(AttendanceRecordHikEntity query, Map<String, Object> model, Context context) throws AppException {
        if (query.getStaffName() != null && !query.getStaffName().equals("")) {
            String staffName = "%" + query.getStaffName() + "%";
            query.setStaffName(staffName);
        }

        if (ObjectUtils.isEmpty(query.getOrderColList())) {
            query.setOrderColList(Arrays.asList(new OrderCol("createTime", OrderCol.DESCENDING)));
        } else {
            query.getOrderColList().add(new OrderCol("createTime", OrderCol.DESCENDING));
        }

        super.doListBefore(query, model, context);
    }

    @Override
    public void doExportFileAfter(byte[] data, AttendanceRecordHikEntity query, Context context) throws AppException {
        InputStream inputStream = new ByteArrayInputStream(data);
        MultipartFile file = ServletUtils.getMultipartFile(inputStream, "kaoqin.xlsx");
        String filePath = uploadService.saveFileUpload(file, "file/fileupload", null);
        AttendanceExportRecordEntity attendanceExportRecordEntity = new AttendanceExportRecordEntity();
        attendanceExportRecordEntity.initAttrValue();
        attendanceExportRecordEntity.setFilePath(filePath);
        if (query.getIdList() != null) {
            List<Long> idList = query.getIdList();
            String recordIdList = "";
            for (Long aLong : idList) {
                if (recordIdList.equals("")) {
                    recordIdList = recordIdList + aLong;
                } else {
                    recordIdList = recordIdList + "、" + aLong;
                }
            }
            attendanceExportRecordEntity.setRecordIdList(recordIdList);
        }
        if (query.getAttendanceDateStart() != null) {
            String attendanceDate = query.getAttendanceDateStart() + "~" + query.getAttendanceDateEnd();
            attendanceExportRecordEntity.setAttendanceDate(attendanceDate);
        }
        attendanceExportRecordEntity.setCreateUserId(context.getUser().getId());
        attendanceExportRecordEntity.setCreateTime(new Date());
        attendanceExportRecordEntity.setType(1);
        attendanceExportRecordEntity.setExportOrImport(1);
        attendanceExportRecordService.save(attendanceExportRecordEntity);
        super.doExportFileAfter(data, query, context);
    }

}
