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


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
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.dto.BusinessOutDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
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.entity.AdjustShift;
import com.jpsoft.shinestar.modules.business.entity.AdjustShiftPerson;
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.TypeNameUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/mobile/carryThingsOutFactoryApi")
@Api(description = "携物出厂相关接口")
@Slf4j
public class CarryThingsOutFactoryApiController {

    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 = "CarryThingsList",method = RequestMethod.POST)
    public MessageResult<Object> CarryThingsList(
            @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 {

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

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

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

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            if(personPopedom!=null){
                searchParams.put("personPopedomId", personPopedom.getId());
            }


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

            Page<CarryThingsOutFactory> page = carryThingsOutFactoryService.pageSearch(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.setCreateTime(carryThingsOutFactory.getCreateTime());
                dto.setLeaveFactoryTime(carryThingsOutFactory.getLeaveFactoryTime());
                dto.setAuditStatus(carryThingsOutFactory.getAuditStatus());
                dto.setAuditStatusName(TypeNameUtil.getExamineTypeName(carryThingsOutFactory.getAuditStatus()));

                pageDto.add(dto);
            }

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


            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(pageDto));

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

        return msgResult;
    }


    @ApiOperation(value = "携物出厂数据提交")
    @RequestMapping(value = "submitCarryThings", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "date", value = "出厂日期", required = true, paramType = "form"),
            @ApiImplicitParam(name = "content", value = "申请理由物品清单", required = true, paramType = "form"),
            @ApiImplicitParam(name = "images", value = "图片", required = true, paramType = "form"),
            @ApiImplicitParam(name = "formId", value = "页面路径", required = true, paramType = "form"),
            @ApiImplicitParam(name = "draft", value = "状态（0：草稿，1：提交）", required = true, paramType = "form")
    })
    public MessageResult<Map> submitCarryThings(String ids,String draft,String date, String content, String images,String formId,@RequestAttribute String subject, String token) {
        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            //查询操作人
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            if (personInfo == null) {
                throw new Exception("申请人不存在");
            }

            //申请人角色
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());



            String id = carryThingsOutFactoryService.submitCarryThings(personPopedom,date,images,content,formId,ids,draft);


            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            msgResult.setData(map);
            msgResult.setCode(200);
            msgResult.setResult(true);


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

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value = "携物出厂数据详情")
    @RequestMapping(value = "carryThingsDetail", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> carryThingsDetail(@RequestAttribute String subject, String token, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();
        try {

            PersonInfo person = personInfoService.get(Long.parseLong(subject));
            PersonPopedom personPopedom = personPopedomService.get(person.getPopedom());

            CarryThingsOutFactory carryThingsOutFactory = carryThingsOutFactoryService.get(id);

            //申请人
            PersonPopedom personPopedom1 = personPopedomService.get(carryThingsOutFactory.getPersonPopedomId());
            PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());

            Map<String, Object> map = new HashMap<>();
            map.put("name", personInfo1.getName());
            map.put("date", DateUtil.format(carryThingsOutFactory.getLeaveFactoryTime(),"yyyy-MM-dd"));
            map.put("content", carryThingsOutFactory.getLeaveFactoryReason());
            map.put("images",carryThingsOutFactory.getImage());
            map.put("createTime", DateUtil.format(carryThingsOutFactory.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            map.put("status",carryThingsOutFactory.getAuditStatus());
            map.put("statusName", TypeNameUtil.getExamineTypeName(carryThingsOutFactory.getAuditStatus()));
            String releasePerson = null;
            String releaseTime = null;
            String releaseCompany = null;
            if (StringUtils.isNotBlank(carryThingsOutFactory.getReleaseBy())){
                PersonInfo personInfo = personInfoService.findByIdIgnoreDel(Long.parseLong(carryThingsOutFactory.getReleaseBy()));
                releasePerson = personInfo.getName();
                CompanyInfo companyInfo = companyInfoService.findByIdIgnoreDel(personInfo.getCompanyId());
                releaseCompany = companyInfo.getName();
            }
            if (carryThingsOutFactory.getReleaseTime() != null){
                releaseTime = DateUtil.format(carryThingsOutFactory.getReleaseTime(),"yyyy-MM-dd HH:mm:ss");
            }
            map.put("releaseTime",releaseTime);
            map.put("releasePerson",releasePerson);
            map.put("releaseCompany",releaseCompany);

            messageResult.setData(map);
            messageResult.setCode(200);
            messageResult.setResult(true);

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

        }
        return messageResult;
    }



}
