package com.testor.module.duty.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.testor.biz.file.controller.SysFileController;
import com.testor.biz.file.model.domain.SysFile;
import com.testor.biz.file.model.dto.FileAjaxDTO;
import com.testor.biz.file.service.SysFileService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.duty.model.domain.TSysDutyLog;
import com.testor.module.duty.model.dto.DutyLogDetail;
import com.testor.module.duty.model.dto.ReturnCreateLog;
import com.testor.module.duty.model.dto.TSysDutyLogDelParam;
import com.testor.module.duty.model.dto.TSysDutyLogParam;
import com.testor.module.duty.service.TSysDutyLogService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.constants.IoConstants;
import com.tongtech.tfw.backend.core.helper.codec.Base64Helper;
import com.tongtech.tfw.backend.core.helper.datetime.DatetimeHelper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
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.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;


/**
 * 值班日志Controller
 *
 * @author testor-framework
 * @date 2022-06-08 14:31:30
 */
@RestController
@RequestMapping("/log")
@Api(value = "TSysDutyLog", tags = "值班日志")
@Slf4j
public class TSysDutyLogController extends SuperController {
    @Autowired
    private TSysDutyLogService tSysDutyLogService;

    @Autowired
    private SysFileService sysFileService;

    @Value("${minio.bucket}")
    private String bucketName;

    @Value("${apisix.minioroute.url}")
    private String address;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private SysOrgService sysOrgService;

    /* Generated Method*/
//    @ApiOperation(value = "新增 值班日志", notes = "Add TSysDutyLog")
//    @PostMapping(value = "/add")
    public BaseResponse<Object> addEntity(@RequestBody TSysDutyLogParam addRequest) throws Exception {
        return tSysDutyLogService.addEntity(addRequest);
    }

    @ApiOperation(value = "获取相关方及人员", notes = "Add TSysDutyLog")
    @GetMapping(value = "/interestedPerson")
    public BaseResponse<Object> getInterestedPerson() throws Exception {
        return tSysDutyLogService.getInterestedPerson();
    }

    @ApiOperation(value = "创建日志获取 值班期间作业活动类别 ", notes = "如果返回危险作业，但是在保存的时候没有危险作业，弹窗填写原因")
    @PostMapping(value = "/getActivityClass")
    public BaseResponse<Object> getActivityClass(@RequestBody TSysDutyLogParam addRequest) throws Exception {
        return tSysDutyLogService.getActivityClass(addRequest);
    }

    @ApiOperation(value = "新增 值班日志 作业活动", notes = "Add TSysDutyLog")
    @PostMapping(value = "/add")
    public BaseResponse<Object> addEntityAndTask(@RequestBody TSysDutyLogParam addRequest) throws Exception {
        return tSysDutyLogService.addEntityAndTask(addRequest);
    }

    @ApiOperation(value = "获取创建日志需要信息")
    @PostMapping(value = "/getCreateLogMsg")
    public BaseResponse<ReturnCreateLog> getCreateLogMsg(@RequestBody TSysDutyLogParam addRequest) throws Exception {
        return tSysDutyLogService.getCreateLogMsg(addRequest);
    }

    @ApiOperation(value = "查看详情 值班日志 ", notes = "Get TSysDutyLog By Id")
    @GetMapping(value = "/get")
    public BaseResponse<DutyLogDetail> getByIds(String id) {
        return tSysDutyLogService.getByIds(id);
    }

    @ApiOperation(value = "值班日志审批修改 ", notes = "Update TSysDutyLog By Id")
    @PutMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TSysDutyLog updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            TSysDutyLog data = tSysDutyLogService.getById(updateRequest.getId());
            data.setProcessStatus(updateRequest.getProcessStatus());
            data.setHandoverRejectOpinion(updateRequest.getHandoverRejectOpinion());
            data.setSuccessionRejectOpinion(updateRequest.getSuccessionRejectOpinion());
            // 交班领导签字
            String handoverSign = updateRequest.getHandoverSign();
            // 接班领导签字
            String successionSign = updateRequest.getSuccessionSign();
            String base = "data:image/png;base64,";
            String baseSvg = "data:image/svg+xml;base64,";
            if (StringHelper.isNotEmpty(handoverSign)) {
                if (handoverSign.contains(base) || handoverSign.contains(baseSvg)) {
                    String str = "交班领导签字_";
                    String filePath = uploadBase64Image(handoverSign, str);
                    data.setHandoverSign(filePath);
                }
            }
            if (StringHelper.isNotEmpty(successionSign)) {
                if (successionSign.contains(base) || successionSign.contains(baseSvg)) {
                    String str = "接班领导签字_";
                    String filePath = uploadBase64Image(successionSign, str);
                    data.setSuccessionSign(filePath);
                }
            }
            boolean result = tSysDutyLogService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }
/*    @ApiOperation(value = "测试图片", notes = "测试图片")
    @GetMapping(value = "/testPicture")
    public BaseResponse<String> testPicture(String handoverSign) {
        String str = "交班领导签字_";
        String filePath = uploadBase64Image(handoverSign, str);
        BaseResponse<String> objectBaseResponse = new BaseResponse<>();
        objectBaseResponse.setData(filePath);
        return objectBaseResponse;
    }*/

    /**
     * 上传 base64图片
     *
     * @param handoverSign
     * @return
     */
    private String uploadBase64Image(String handoverSign, String name) {
        String fileName = "";
        String base = "data:image/png;base64,";
        String baseSvg = "data:image/svg+xml;base64,";
        if (StringHelper.isNotEmpty(handoverSign) && handoverSign.contains(base)) {
            fileName = name + System.currentTimeMillis() + ".png";
        } else {
            fileName = name + System.currentTimeMillis() + ".svg";
        }
        FileAjaxDTO fileAjaxDTO = new FileAjaxDTO();
        fileAjaxDTO.setFile(handoverSign);
        fileAjaxDTO.setFileName(fileName);
        String str = handoverSign.replace("data:image/png;base64,", "");
        int i = str.indexOf("=");
        if (str.indexOf("=") > 0) {
            str = str.substring(0, i);
        }
        int length = str.length();
        int i1 = length - (length / 8) * 2;
        String s = String.valueOf(i1);
        fileAjaxDTO.setFileSize(s);
        return upload(fileAjaxDTO);
    }

    public String upload(FileAjaxDTO fileAjaxDTO) {
        String userId = getUserId();
        if (!ObjectHelper.isEmpty(fileAjaxDTO) && !StringHelper.isEmpty(fileAjaxDTO.getFile()) && fileAjaxDTO.getFile().split(",").length >= 2) {
            String fileName = fileAjaxDTO.getFileName();
            long size = Long.parseLong(fileAjaxDTO.getFileSize());
            int beginIndex = fileName.indexOf(".") + 1;
            String ext = StringHelper.substring(fileName, beginIndex, fileName.length());
            String filePath = DatetimeHelper.getDateTime8Length();
            String saveName = IdHelper.getId32bitTime();
            byte[] fileContent = Base64Helper.decode(fileAjaxDTO.getFile().split(",")[1]);
            InputStream input = new ByteArrayInputStream(fileContent);
            String contentType = ((MediaType) MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM)).toString();
            this.uploadMinio(input, fileName, contentType);
            log.info("保存成功：FileId：" + saveName + ", ext: " + ext + ", path:" + filePath + ", name:" + fileName + ", user: " + userId);
            SysFile sysFile = ((SysFile.SysFileBuilder) ((SysFile.SysFileBuilder) SysFile.builder().fileId(saveName).fileName(fileName).fileSize(BigDecimal.valueOf(size)).fileExt(ext).filePath(filePath + IoConstants.PATH_SLASH + saveName).createBy(userId)).updateBy(userId)).build();
            boolean result = sysFileService.save(sysFile);
            if (result) {
                String Path = this.address + "/" + this.bucketName + "/" + fileName;
                return Path;
            }
        }
        return null;

    }

    private void uploadMinio(InputStream input, String fileName, String contentType) {
        try {
            this.minioClient.putObject(
                    (PutObjectArgs) ((PutObjectArgs.Builder) ((PutObjectArgs.Builder)
                            PutObjectArgs.builder().bucket(this.bucketName))
                            .object(fileName))
                            .stream(input, (long) input.available(), -1L)
                            .contentType(contentType).build());
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException var12) {
                    var12.printStackTrace();
                }
            }

        }

    }


    //    @ApiOperation(value = "删除 值班日志 ", notes = "delete TSysDutyLog By Id")
//    @PutMapping(value = "/delete")
    public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TSysDutyLogDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TSysDutyLog data = new TSysDutyLog();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = tSysDutyLogService.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    //    @ApiOperation(value = "批量删除值班日志", notes = "delete TSysDutyLog by batch Id")
//    @PutMapping(value = "/batch_delete")
    public BaseResponse<BizGeneralResponse> deleteEntityBatch(
            @RequestBody TSysDutyLogDelParam deleteRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
            List<TSysDutyLog> tSysDutyLogList = new ArrayList<>();
            for (String id : deleteRequest.getIds()) {
                TSysDutyLog data = new TSysDutyLog();
                data.setId(id);
                data.setStatus(BizConstants.STATUS_DELETE);
                tSysDutyLogList.add(data);
            }
            boolean result = tSysDutyLogService.updateBatchById(tSysDutyLogList);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }

    @ApiOperation(value = "获取 现场监护人", notes = "List TSysDutyLog with page")
    @GetMapping(value = "/getGuardian")
    public BaseResponse<Object> getGuardian() {
        return tSysDutyLogService.getGuardian();
    }

    @ApiOperation(value = "获取 值班日志 分页列表", notes = "List TSysDutyLog with page")
    @GetMapping(value = "/list")
    public BaseResponse<BaseResponseList<TSysDutyLog>> listEntity(TSysDutyLogParam param) {
        BaseResponse<BaseResponseList<TSysDutyLog>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysDutyLog> resultPage = new Page<>(page, limit);
        if (!StringUtils.isNotBlank(param.getCompanyId())) {
            UserInfo curUser = ContextUtils.getLoginUser();
            String orgId = curUser.getOrgId();
            List<SysOrg> list = sysOrgService.list(new QueryWrapper<SysOrg>().select("org_id").eq("parent_id", curUser.getOrgId())
                    .eq("is_dept", "0").ne("status", "1"));
            List<String> collect = list.stream().map(SysOrg::getOrgId).collect(Collectors.toList());

            for (String s : collect) {
                orgId=orgId+","+s;
            }
            param.setCompanyId(orgId);

        }
        param.setOrderBy(TSysDutyLog.CREATE_DATE);
        param.setOrderType(BizConstants.DESC);
        QueryWrapper<TSysDutyLog> queryWrapper = this.createQuery(param);
        Page<TSysDutyLog> resultList = tSysDutyLogService.page(resultPage, queryWrapper);
        BaseResponseList<TSysDutyLog> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    //    @ApiOperation(value = "获取 值班日志 列表", notes = "List TSysDutyLog all")
//    @GetMapping(value = "/datas")
    public BaseResponse<BaseResponseList<TSysDutyLog>> listAllEntity(TSysDutyLogParam param) {
        BaseResponse<BaseResponseList<TSysDutyLog>> baseResponse = new BaseResponse<>();
        QueryWrapper<TSysDutyLog> queryWrapper = this.createQuery(param);
        List<TSysDutyLog> resultList = tSysDutyLogService.list(queryWrapper);
        BaseResponseList<TSysDutyLog> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList);
        baseResponseList.setTotal(resultList.size());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSysDutyLog> createQuery(TSysDutyLogParam queryParam) {
        QueryWrapper<TSysDutyLog> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getStartDate()) && StringHelper.isNotEmpty(queryParam.getEndDate())) {
            queryWrapper.between(TSysDutyLog.CREATE_DATE, queryParam.getStartDate() + " 00:00:00", queryParam.getEndDate() + " 23:59:59");
        }
        if (StringHelper.isNotEmpty(queryParam.getCompanyId())) {
            String[] split = queryParam.getCompanyId().split(",");
            queryWrapper.in(TSysDutyLog.COMPANY_ID, split);
        }
        //queryWrapper.orderByDesc(TSysDutyLog.DUTY_DATE);
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TSysDutyLog.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TSysDutyLog.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TSysDutyLog.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TSysDutyLog.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysDutyLog.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getDutyDate())) {
            queryWrapper.eq(TSysDutyLog.DUTY_DATE, queryParam.getDutyDate());
        }
        if (StringHelper.isNotEmpty(queryParam.getDutyLeader())) {
            queryWrapper.eq(TSysDutyLog.DUTY_LEADER, queryParam.getDutyLeader());
        }
        if (StringHelper.isNotEmpty(queryParam.getWeather())) {
            queryWrapper.eq(TSysDutyLog.WEATHER, queryParam.getWeather());
        }
        if (StringHelper.isNotEmpty(queryParam.getTimeSection())) {
            queryWrapper.eq(TSysDutyLog.TIME_SECTION, queryParam.getTimeSection());
        }
        if (StringHelper.isNotEmpty(queryParam.getDefendName())) {
            queryWrapper.like(TSysDutyLog.DEFEND_NAME, queryParam.getDefendName());
        }
        if (StringHelper.isNotEmpty(queryParam.getOtherWork())) {
            queryWrapper.eq(TSysDutyLog.OTHER_WORK, queryParam.getOtherWork());
        }
        if (StringHelper.isNotEmpty(queryParam.getJobId())) {
            queryWrapper.eq(TSysDutyLog.JOB_ID, queryParam.getJobId());
        }
        if (StringHelper.isNotEmpty(queryParam.getOtherStaffs())) {
            queryWrapper.eq(TSysDutyLog.OTHER_STAFFS, queryParam.getOtherStaffs());
        }
        if (StringHelper.isNotEmpty(queryParam.getEmergency())) {
            queryWrapper.eq(TSysDutyLog.EMERGENCY, queryParam.getEmergency());
        }
        if (StringHelper.isNotEmpty(queryParam.getIssueApply())) {
            queryWrapper.eq(TSysDutyLog.ISSUE_APPLY, queryParam.getIssueApply());
        }
        if (StringHelper.isNotEmpty(queryParam.getAttentionMatter())) {
            queryWrapper.eq(TSysDutyLog.ATTENTION_MATTER, queryParam.getAttentionMatter());
        }
        if (StringHelper.isNotEmpty(queryParam.getTakeStep())) {
            queryWrapper.eq(TSysDutyLog.TAKE_STEP, queryParam.getTakeStep());
        }
        if (StringHelper.isNotEmpty(queryParam.getHandoverIssue())) {
            queryWrapper.eq(TSysDutyLog.HANDOVER_ISSUE, queryParam.getHandoverIssue());
        }
        if (StringHelper.isNotEmpty(queryParam.getHandoverSign())) {
            queryWrapper.eq(TSysDutyLog.HANDOVER_SIGN, queryParam.getHandoverSign());
        }
        if (StringHelper.isNotEmpty(queryParam.getUnitBelong())) {
            queryWrapper.eq(TSysDutyLog.UNIT_BELONG, queryParam.getUnitBelong());
        }
        if (StringHelper.isNotEmpty(queryParam.getSuccessionSign())) {
            queryWrapper.eq(TSysDutyLog.SUCCESSION_SIGN, queryParam.getSuccessionSign());
        }
        if (StringHelper.isNotEmpty(queryParam.getIsSpecialTime())) {
            queryWrapper.eq(TSysDutyLog.IS_SPECIAL_TIME, queryParam.getIsSpecialTime());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSysDutyLog.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSysDutyLog.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSysDutyLog.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
