package com.jpsoft.shinestar.modules.workflow;

import cn.hutool.core.util.StrUtil;
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.PersonRoleInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonInfoService;
import com.jpsoft.shinestar.modules.base.service.PersonRoleInfoService;
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.sys.entity.DataDictionary;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.workflow.dto.MoveDTO;
import com.jpsoft.shinestar.modules.workflow.dto.ProcessActivityDTO;
import com.jpsoft.shinestar.modules.workflow.entity.ProcessActUser;
import com.jpsoft.shinestar.modules.workflow.entity.ProcessActivity;
import com.jpsoft.shinestar.modules.workflow.entity.ProcessTemplate;
import com.jpsoft.shinestar.modules.workflow.service.ProcessActUserService;
import com.jpsoft.shinestar.modules.workflow.service.ProcessActivityService;
import com.jpsoft.shinestar.modules.workflow.service.ProcessTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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("/workflow/processActivity")
@Api(description = "processActivity")
public class ProcessActivityController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProcessActivityService processActivityService;

    @Autowired
    private ProcessActUserService processActUserService;

    @Autowired
    private ProcessTemplateService processTemplateService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

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

        ProcessActivity processActivity = new ProcessActivity();
        processActivity.setOperation("or");
        processActivity.setSource("1");

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

        return msgResult;
    }

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

        try {
            String condition = processActivity.getCondition();
            processActivity.setId(UUID.randomUUID().toString());
            processActivity.setCreateBy(subject);
            processActivity.setCreateTime(new Date());
            processActivity.setDelFlag(false);
            processActivity.setCondition(StrUtil.replace(condition," ",""));

            String processTemplateId = processActivity.getProcessTemplateId();
            String personRoleId = processActivity.getPersonRoleId();

            int activityOrder = 1;

            List<ProcessActivity> list = processActivityService.findByTemplateIdAndRoleIdAndCondition(processTemplateId,personRoleId,processActivity.getCondition());
            /*if(list.size()>0){
                ProcessActivity item = list.get(0);
                activityOrder = item.getActivityOrder() + 1;
            }*/
            processActivity.setActivityOrder(activityOrder+ list.size());

            int affectCount = processActivityService.insertAndActUser(processActivity);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(processActivity);
            } 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<ProcessActivity> edit(@PathVariable("id") String id){
        MessageResult<ProcessActivity> msgResult = new MessageResult<>();

        try {
            ProcessActivity processActivity = processActivityService.get(id);

            if (processActivity != null) {

                //抄送人
                List<String> list = processActUserService.findByActIdAndUserType(processActivity.getId(),"2");
                processActivity.setCcPersonIdList(list);


                List<ProcessActUser> itemList = processActUserService.findItemByActIdAndUserType(processActivity.getId(),"1");

                List<String> approvedPersonIdList = new ArrayList<>();
                String relativePositionName ="";
                String relativePosition="";
                String source = "";

                for (ProcessActUser processActUser:itemList) {
                    if(processActUser.getSource().equals("3")){
                        relativePosition = processActUser.getRelativePosition();
                        relativePositionName = dataDictionaryService.findNameByCatalogNameAndValue("相对职位",relativePosition);

                    }
                    else if(processActUser.getSource().equals("2")){
                        if(StringUtils.isNotEmpty(processActUser.getDepartmentId())){
                            processActivity.setCompanyId(processActUser.getDepartmentId());
                        }
                        if(StringUtils.isNotEmpty(processActUser.getPersonRoleId())){
                            processActivity.setRoleId(processActUser.getPersonRoleId());
                        }
                    }
                    else{
                        if(StringUtils.isNotEmpty(processActUser.getPersonId())){
                            PersonInfo personInfo = personInfoService.get(Long.parseLong(processActUser.getPersonId()));
                            if(personInfo!=null&&!personInfo.getDelFlag()){
                                approvedPersonIdList.add(processActUser.getPersonId());
                            }
                        }

                    }
                    source = processActUser.getSource();
                }

                processActivity.setSource(source);
                processActivity.setRelativePosition(relativePosition);
                processActivity.setApprovedPersonIdList(approvedPersonIdList);

                msgResult.setResult(true);
                msgResult.setData(processActivity);
            } 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<Integer> update(@RequestBody ProcessActivity processActivity,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            processActivity.setUpdateBy(subject);
            processActivity.setUpdateTime(new Date());

            int affectCount = processActivityService.updateAndActUser(processActivity);

            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="删除用户")
    @PostMapping("delete/{id}")
    public MessageResult<ProcessActivity> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<ProcessActivity> msgResult = new MessageResult<>();

        try {
            ProcessActivity processActivity = processActivityService.get(id);

            processActivity.setUpdateBy(subject);
            processActivity.setUpdateTime(new Date());
            processActivity.setDelFlag(true);

            int affectCount = processActivityService.update(processActivity);

            if (affectCount > 0) {

                ProcessTemplate processTemplate = processTemplateService.get(processActivity.getProcessTemplateId());
                processTemplate.setUpdateBy(processActivity.getUpdateBy());
                processTemplate.setUpdateTime(processActivity.getUpdateTime());
                int OrderNum = processTemplate.getOrderNum();
                processTemplate.setOrderNum(OrderNum - 1);
                int count = processTemplateService.update(processTemplate);

                if(count>0) {
                    msgResult.setResult(true);
                }
                else{
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库删除失败");
                }
            } 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) {
                ProcessActivity processActivity = processActivityService.get(id);
                processActivity.setDelFlag(true);
                processActivity.setUpdateBy(subject);
                processActivity.setUpdateTime(new Date());

                int count = processActivityService.update(processActivity);

                if(count>0) {
                    ProcessTemplate processTemplate = processTemplateService.get(processActivity.getProcessTemplateId());
                    processTemplate.setUpdateBy(processActivity.getUpdateBy());
                    processTemplate.setUpdateTime(processActivity.getUpdateTime());
                    int OrderNum = processTemplate.getOrderNum();
                    processTemplate.setOrderNum(OrderNum - 1);
                    affectCount += processTemplateService.update(processTemplate);
                }
            }

            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 processTemplateId,String name,String personRoleId,
            @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("person_role_id","asc"));
        sortList.add(new Sort("activity_order","asc"));


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

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

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

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

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

        for (ProcessActivity processActivity:page) {
            ProcessActivityDTO dto = new ProcessActivityDTO();
            dto.setId(processActivity.getId());
            dto.setActivityOrder(processActivity.getActivityOrder());
            dto.setName(processActivity.getName());
            dto.setProcessTemplateId(processActivity.getProcessTemplateId());

            List<ProcessActUser> itemList = processActUserService.findItemByActIdAndUserType(processActivity.getId(),"1");

            String personNames = "";
            String relativePositionName="";

            for (ProcessActUser processActUser:itemList) {
                if(processActUser.getSource().equals("3")){
                    String relativePosition = processActUser.getRelativePosition();
                    relativePositionName = dataDictionaryService.findNameByCatalogNameAndValue("相对职位",relativePosition);
                    dto.setRelativePosition(relativePositionName);
                }
                else if(processActUser.getSource().equals("2")){
                    if(StringUtils.isNotEmpty(processActUser.getDepartmentId())){
                        CompanyInfo companyInfo = companyInfoService.get(processActUser.getDepartmentId());
                        if(companyInfo!=null) {
                            dto.setCompanys(companyInfo.getName());
                        }
                    }
                    if(StringUtils.isNotEmpty(processActUser.getPersonRoleId())){
                        PersonRoleInfo personRoleInfo = personRoleInfoService.get(processActUser.getPersonRoleId());
                        if(personRoleInfo!=null) {
                            dto.setRoles(personRoleInfo.getPersonRoleName());
                        }
                    }
                }
                else{
                    //审批人
                    PersonInfo personInfo = personInfoService.get(Long.parseLong(processActUser.getPersonId()));
                    if(personInfo!=null){
                        personNames += personInfo.getName()+"，";
                    }
                }
            }


            if(StringUtils.isNotEmpty(personNames)){
                personNames = personNames.substring(0,personNames.lastIndexOf("，"));
            }
            dto.setApprovedPersons(personNames);

            String curPersonRoleId = processActivity.getPersonRoleId();

            PersonRoleInfo personRoleInfo = personRoleInfoService.get(curPersonRoleId);
            if(personRoleInfo!=null){
                dto.setPersonRoleName(personRoleInfo.getPersonRoleName());
            }

            pageDto.add(dto);
        }

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

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

        return msgResult;
    }


    @ApiOperation(value="移动顺序")
    @PostMapping("moveActivityOrder")
    public MessageResult<Integer> moveActivityOrder(String id,Boolean isUp, @RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            ProcessActivity processActivity = processActivityService.get(id);
            int activityOrder = processActivity.getActivityOrder();
            int swapActivityOrder;
            ProcessActivity swapProcessActivity;

            if(isUp){
                //上移
                swapActivityOrder = activityOrder - 1;
                swapProcessActivity = processActivityService.findByActivityOrder(activityOrder - 1);
            }
            else{
                //下移
                swapActivityOrder = activityOrder + 1;
                swapProcessActivity = processActivityService.findByActivityOrder(activityOrder + 1);
            }

            processActivity.setActivityOrder(swapActivityOrder);
            processActivity.setUpdateBy(subject);
            processActivity.setUpdateTime(new Date());

            if(swapProcessActivity!=null){
                swapProcessActivity.setActivityOrder(activityOrder);
                swapProcessActivity.setUpdateBy(subject);
                swapProcessActivity.setUpdateTime(new Date());
            }

            affectCount += processActivityService.updateMove(processActivity,swapProcessActivity);


            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;
    }




}
