package com.jpsoft.shinestar.modules.business.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.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.business.entity.CarryThingsOutFactory;
import com.jpsoft.shinestar.modules.business.service.CarryThingsOutFactoryService;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.workflow.entity.ProcessActUser;
import com.jpsoft.shinestar.modules.workflow.entity.ProcessActivity;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActUser;
import com.jpsoft.shinestar.modules.workflow.entity.ProcinstActivity;
import com.jpsoft.shinestar.modules.workflow.service.ProcessActUserService;
import com.jpsoft.shinestar.modules.workflow.service.ProcessActivityService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActUserService;
import com.jpsoft.shinestar.modules.workflow.service.ProcinstActivityService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.ResultMap;
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("/business/carryThingsOutFactory")
public class CarryThingsOutFactoryController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CarryThingsOutFactoryService carryThingsOutFactoryService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private ProcinstActUserService procinstActUserService;

    @Autowired
    private ProcinstActivityService procinstActivityService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<CarryThingsOutFactory> create(){
        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        CarryThingsOutFactory carryThingsOutFactory = new CarryThingsOutFactory();

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

        return msgResult;
    }

    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<CarryThingsOutFactory> add(@RequestBody CarryThingsOutFactory carryThingsOutFactory,@RequestAttribute String subject){
        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        try {
            carryThingsOutFactory.setId(UUID.randomUUID().toString());

            int affectCount = carryThingsOutFactoryService.insert(carryThingsOutFactory);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(carryThingsOutFactory);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<CarryThingsOutFactory> edit(@PathVariable("id") String id){
        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        try {
            CarryThingsOutFactory carryThingsOutFactory = carryThingsOutFactoryService.get(id);

            if (carryThingsOutFactory != null) {
                String images = carryThingsOutFactory.getImage();
                List<String> imageList = new ArrayList<>();

                if(StringUtils.isNotEmpty(images)) {
                    String[] imageArray = carryThingsOutFactory.getImage().split(",");

                    for (String img : imageArray) {
                        imageList.add(img);
                    }
                    carryThingsOutFactory.setImageList(imageList);
                }

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

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

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<CarryThingsOutFactory> update(@RequestBody CarryThingsOutFactory carryThingsOutFactory,@RequestAttribute String subject){
        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        try {
            int affectCount = carryThingsOutFactoryService.update(carryThingsOutFactory);

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

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

        return msgResult;
    }

    @ApiOperation(value="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<CarryThingsOutFactory> delete(@PathVariable("id") String id){
        MessageResult<CarryThingsOutFactory> msgResult = new MessageResult<>();

        try {
            int affectCount = carryThingsOutFactoryService.delete(id);

            if (affectCount > 0) {
                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                CarryThingsOutFactory carryThingsOutFactory = carryThingsOutFactoryService.get(id);
                carryThingsOutFactory.setDelFlag(true);
                carryThingsOutFactory.setUpdateBy(subject);
                carryThingsOutFactory.setUpdateTime(new Date());

                affectCount += carryThingsOutFactoryService.update(carryThingsOutFactory);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            String personName,String companyId,String auditStatus,String releaseStatus,
            String createTimeRange,String auditTimeRange,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            HttpServletRequest request){
        String subject = (String)request.getAttribute("subject");

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

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

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

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

        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("personName","%" + personName + "%");
        }

        if (StringUtils.isNotEmpty(companyId)) {
            searchParams.put("companyId",companyId);
        }

        if (StringUtils.isNotEmpty(auditStatus)) {
            searchParams.put("auditStatus",auditStatus);
        }

        if (StringUtils.isNotEmpty(releaseStatus)) {
            searchParams.put("releaseStatus",releaseStatus);
        }

        if (StringUtils.isNotEmpty(createTimeRange)) {
            String[] timeRangeArray = createTimeRange.split(",");
            String beginTime = "";
            String endTime = "";
            if (timeRangeArray.length == 1) {
                beginTime = timeRangeArray[0];
            } else if (timeRangeArray.length == 2) {
                beginTime = timeRangeArray[0];
                endTime = timeRangeArray[1];
            }

            searchParams.put("beginTime", beginTime);
            searchParams.put("endTime", endTime);
        }

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



        for (CarryThingsOutFactory carryThingsOutFactory:page) {

            PersonPopedom personPopedom = personPopedomService.get(carryThingsOutFactory.getPersonPopedomId());
            PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());

            if(personInfo!=null){
                carryThingsOutFactory.setPersonName(personInfo.getName());
                carryThingsOutFactory.setJobNumber(personInfo.getJobNumber());

                CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                if(companyInfo!=null){
                    carryThingsOutFactory.setCompanyName(companyInfo.getName());
                }

                String auditStatusN = dataDictionaryService.findNameByCatalogNameAndValue("审核状态",carryThingsOutFactory.getAuditStatus());
                carryThingsOutFactory.setAuditStatusN(auditStatusN);

            }

            //如果不是未审核
            if(!"0".equals(carryThingsOutFactory.getAuditStatus())){

                String businessKey = carryThingsOutFactory.getId();

                Map<String,Object> searchParams1 = new HashMap<>();
                searchParams1.put("status","1");
                searchParams1.put("businessKey",businessKey);

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

                Page<ProcinstActUser> procinstActUserPage = procinstActUserService.pageSearch(searchParams1,1,10,true,sortList1);

                String auditByN = "";

                for (ProcinstActUser procinstActUser:procinstActUserPage) {
                    PersonInfo auditPerson = personInfoService.get(Long.parseLong(procinstActUser.getUserId()));
                    if(auditPerson!=null){
                        auditByN += auditPerson.getName()+",";
                    }
                }
                if(StringUtils.isNotEmpty(auditByN)){
                    auditByN = auditByN.substring(0,auditByN.lastIndexOf(","));
                }
                carryThingsOutFactory.setAuditByN(auditByN);

                if(procinstActUserPage.size()>0){
                    ProcinstActivity procinstActivity = procinstActivityService.get(procinstActUserPage.get(0).getProcinstActivityId());
                    if(procinstActivity!=null){
                        carryThingsOutFactory.setAuditTime(procinstActivity.getFinishTime());
                    }
                }

                if(StringUtils.isNotEmpty(carryThingsOutFactory.getReleaseBy())){
                    PersonInfo releasePerson = personInfoService.get(personPopedom.getPersonId());
                    if(releasePerson!=null){
                        carryThingsOutFactory.setReleaseByN(releasePerson.getName());
                    }
                }
            }
        }


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

        return msgResult;
    }



}
