package com.jpsoft.shinestar.modules.mobile.controller;


import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonInfo;
import com.jpsoft.shinestar.modules.base.entity.PersonPopedom;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonPopedomService;
import com.jpsoft.shinestar.modules.business.dto.CarryThingsOutFactoryDTO;
import com.jpsoft.shinestar.modules.business.dto.GuardReleaseDTO;
import com.jpsoft.shinestar.modules.business.entity.CarryThingsOutFactory;
import com.jpsoft.shinestar.modules.business.service.CarryThingsOutFactoryService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/mobile/guardReleaseApi")
@Api(description = "门卫放行相关接口")
public class GuardReleaseApiController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CarryThingsOutFactoryService carryThingsOutFactoryService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @ApiOperation(value="扫码放行")
    @RequestMapping(value = "indexData",method = RequestMethod.POST)
    public MessageResult<Object> indexData(
            String token,String date,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            GuardReleaseDTO  guardReleaseDTO = new GuardReleaseDTO();

            PersonInfo personInfo = personInfoService.get(Long.parseLong(subject));

            if (personInfo == null) {
                throw new Exception("用户不存在！");
            }

            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if(companyInfo==null){
                throw new Exception("公司部门不存在！");
            }

            Map<String, Object> searchParams = new HashMap<>();
            Map<String, Object> searchParams2 = new HashMap<>();

            String[] companyArray = companyInfo.getCode().split(",");

            if(companyArray.length>0){
                String companyId = companyArray[0];
                CompanyInfo companyInfo1 = companyInfoService.get(companyId);
                if(companyInfo1!=null){
                    guardReleaseDTO.setCompanyName(companyInfo1.getName());
                }
                if(StringUtils.isNotEmpty(companyId)) {
                    searchParams.put("companyId", "%" + companyId + "%");
                    searchParams2.put("companyId", "%" + companyId + "%");
                }
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String startTime;
            String endTime;

            if(StringUtils.isNotEmpty(date)){
                startTime = date + " 00:00:00";
                endTime = date + " 23:59:59";
            }
            else{
                Date now = new Date();
                startTime = sdf.format(now)+" 00:00:00";
                endTime = sdf.format(now)+" 23:59:59";
            }

            searchParams.put("startTime", startTime);
            searchParams.put("endTime", endTime);

            searchParams2.put("startTime", startTime);
            searchParams2.put("endTime", endTime);
            searchParams2.put("auditStatus", "1");


            //预约今日放行数
            int appointmentNum = carryThingsOutFactoryService.getAppointmentPassNum(searchParams2);
            guardReleaseDTO.setAppointmentNum(appointmentNum);

            //今日已放行数
            searchParams2.put("releaseStatus", "1");
            int passNum = carryThingsOutFactoryService.getAppointmentPassNum(searchParams2);
            guardReleaseDTO.setPassNum(passNum);

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("a.create_time", "desc"));

            searchParams.put("auditStatus", "1");

            Page<CarryThingsOutFactory> page = carryThingsOutFactoryService.guardSearch(searchParams, pageIndex, pageSize, true, sortList);

            Page<CarryThingsOutFactoryDTO> pageDto = new Page<>();

            for (CarryThingsOutFactory carryThingsOutFactory:page) {
                CarryThingsOutFactoryDTO dto = new CarryThingsOutFactoryDTO();
                dto.setId(carryThingsOutFactory.getId());

                String personPopedomId = carryThingsOutFactory.getPersonPopedomId();

                PersonPopedom personPopedomTemp = personPopedomService.get(personPopedomId);

                if(personPopedomTemp!=null){
                    PersonInfo personTemp = personInfoService.get(personPopedomTemp.getPersonId());
                    if(personTemp!=null){
                        dto.setPersonName(personTemp.getName());
                    }
                }

                dto.setLeaveFactoryTime(carryThingsOutFactory.getLeaveFactoryTime());

                if(carryThingsOutFactory.getReleaseBy()!=null) {
                    PersonInfo releasePerson = personInfoService.get(Long.parseLong(carryThingsOutFactory.getReleaseBy()));
                    if(releasePerson!=null) {
                        dto.setReleasePerson(releasePerson.getName());
                        CompanyInfo releaseCompany = companyInfoService.get(releasePerson.getCompanyId());
                        dto.setReleaseCompany(releaseCompany.getName());
                    }
                }

                dto.setReleaseTime(carryThingsOutFactory.getReleaseTime());

                pageDto.add(dto);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            guardReleaseDTO.setMap(PojoUtils.pageWrapper(pageDto));

            msgResult.setResult(true);
            msgResult.setData(guardReleaseDTO);

        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="确认放行")
    @RequestMapping(value = "savePass",method = RequestMethod.POST)
    public MessageResult<CarryThingsOutFactory> savePass(String token,String id, @RequestAttribute String subject){

        //当前用户ID
        System.out.println(subject);

        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        try {
            Date now = new Date();

            CarryThingsOutFactory carryThingsOutFactory = carryThingsOutFactoryService.get(id);
            if(carryThingsOutFactory!=null){
                carryThingsOutFactory.setReleaseStatus("1");
                carryThingsOutFactory.setReleaseBy(subject);
                carryThingsOutFactory.setReleaseTime(now);
                carryThingsOutFactory.setUpdateBy(subject);
                carryThingsOutFactory.setUpdateTime(now);

                int affectCount = carryThingsOutFactoryService.update(carryThingsOutFactory);

                if (affectCount > 0) {
                    msgResult.setResult(true);
                    msgResult.setData(carryThingsOutFactory);
                } else {
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库更新失败");
                }
            }
            else{
                msgResult.setResult(false);
                msgResult.setMessage("数据库不存在该记录!");
            }
        }
        catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }
}
