package com.jpsoft.shinestar.modules.workflow;

import com.github.pagehelper.Page;
import com.jpsoft.shinestar.modules.base.entity.CompanyInfo;
import com.jpsoft.shinestar.modules.base.service.CompanyInfoService;
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.workflow.entity.*;
import com.jpsoft.shinestar.modules.workflow.service.*;
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/processTemplate")
@Api(description = "processTemplate")
public class ProcessTemplateController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProcessTemplateService processTemplateService;

    @Autowired
    private TemplateDepartmentService templateDepartmentService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private ProcessActivityService processActivityService;

    @Autowired
    private ProcessActUserService processActUserService;

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

        ProcessTemplate processTemplate = new ProcessTemplate();

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

        return msgResult;
    }

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

        try {
            processTemplate.setId(UUID.randomUUID().toString());
            processTemplate.setCreateBy(subject);
            processTemplate.setCreateTime(new Date());
            processTemplate.setDelFlag(false);
            processTemplate.setOrderNum(0);

            String processSetId = processTemplate.getProcessSetId();

            ProcessTemplate curItem = processTemplateService.findByProcessSetId(processSetId);

            if(curItem!=null){
                if(curItem.getSort()!=null) {
                    processTemplate.setSort(curItem.getSort() + 1);
                }
            }
            else{
                processTemplate.setSort(0);
            }

            int affectCount = processTemplateService.insert(processTemplate);

            if (affectCount > 0) {
                for (String id:processTemplate.getCompanyArray()) {
                    TemplateDepartment templateDepartment = new TemplateDepartment();
                    templateDepartment.setId(UUID.randomUUID().toString());
                    templateDepartment.setDepartmentId(id);
                    templateDepartment.setProcessTemplateId(processTemplate.getId());
                    templateDepartment.setCreateBy(subject);
                    templateDepartment.setCreateTime(new Date());
                    templateDepartment.setDelFlag(false);
                    templateDepartmentService.insert(templateDepartment);
                }

                msgResult.setResult(true);
                msgResult.setData(processTemplate);
            } 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<ProcessTemplate> edit(@PathVariable("id") String id){
        MessageResult<ProcessTemplate> msgResult = new MessageResult<>();

        try {
            ProcessTemplate processTemplate = processTemplateService.get(id);

            if (processTemplate != null) {
                List<TemplateDepartment> list = templateDepartmentService.findByTemplateId(processTemplate.getId());
                List<CompanyInfo> companyInfoList = new ArrayList<>();
                for (TemplateDepartment templateDepartment:list) {
                    CompanyInfo companyInfo = companyInfoService.get(templateDepartment.getDepartmentId());
                    if(companyInfo!=null){
                        companyInfoList.add(companyInfo);
                    }
                }
                processTemplate.setCompanyNameList(companyInfoList);

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

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

            int affectCount = processTemplateService.update(processTemplate);

            if (affectCount > 0) {
                List<TemplateDepartment> templateDepartmentList = templateDepartmentService.findByTemplateId(processTemplate.getId());
                for (TemplateDepartment templateDepartment:templateDepartmentList) {
                    templateDepartment.setDelFlag(true);
                    templateDepartment.setUpdateBy(subject);
                    templateDepartment.setUpdateTime(new Date());
                    templateDepartmentService.update(templateDepartment);
                }

                for (String id:processTemplate.getCompanyArray()) {
                    TemplateDepartment templateDepartment = new TemplateDepartment();
                    templateDepartment.setId(UUID.randomUUID().toString());
                    templateDepartment.setDepartmentId(id);
                    templateDepartment.setProcessTemplateId(processTemplate.getId());
                    templateDepartment.setCreateBy(subject);
                    templateDepartment.setCreateTime(new Date());
                    templateDepartment.setDelFlag(false);
                    templateDepartmentService.insert(templateDepartment);
                }

                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<ProcessTemplate> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<ProcessTemplate> msgResult = new MessageResult<>();

        try {
            ProcessTemplate processTemplate = processTemplateService.get(id);

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

            int affectCount = processTemplateService.update(processTemplate);

            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) {
                ProcessTemplate processTemplate = processTemplateService.get(id);
                processTemplate.setDelFlag(true);
                processTemplate.setUpdateBy(subject);
                processTemplate.setUpdateTime(new Date());

                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 processSetId,String name,String companyId,
            @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.sort_","asc"));


        searchParams.put("processSetId",processSetId);

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

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

        for (ProcessTemplate processTemplate:page) {
            List<TemplateDepartment> list = templateDepartmentService.findByTemplateId(processTemplate.getId());
            List<CompanyInfo> companyInfoList = new ArrayList<>();
            for (TemplateDepartment templateDepartment:list) {
                CompanyInfo companyInfo = companyInfoService.get(templateDepartment.getDepartmentId());
                if(companyInfo!=null){
                    companyInfoList.add(companyInfo);
                }
            }
            processTemplate.setCompanyNameList(companyInfoList);
        }


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

        return msgResult;
    }


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

        try {
            int affectCount = 0;

            ProcessTemplate processTemplate = processTemplateService.get(id);
            int sort = processTemplate.getSort();
            int swapSort;
            ProcessTemplate swapProcessTemplate;

            if(isUp){
                //上移
                swapSort = sort - 1;
                swapProcessTemplate = processTemplateService.findBySort(sort - 1);
            }
            else{
                //下移
                swapSort = sort + 1;
                swapProcessTemplate = processTemplateService.findBySort(sort + 1);
            }

            processTemplate.setSort(swapSort);
            processTemplate.setUpdateBy(subject);
            processTemplate.setUpdateTime(new Date());

            if(swapProcessTemplate!=null){
                swapProcessTemplate.setSort(sort);
                swapProcessTemplate.setUpdateBy(subject);
                swapProcessTemplate.setUpdateTime(new Date());
            }

            affectCount += processTemplateService.updateMove(processTemplate,swapProcessTemplate);


            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("copy")
    public MessageResult<ProcessTemplate> copy(String processId,String processTemplateId, @RequestAttribute String subject){
        MessageResult<ProcessTemplate> msgResult = new MessageResult<>();

        try {
            //原模版
            ProcessTemplate processTemplate = processTemplateService.get(processTemplateId);

            //复制模版
            ProcessTemplate item = new ProcessTemplate();

            item.setId(UUID.randomUUID().toString());
            item.setCreateBy(subject);
            item.setCreateTime(new Date());
            item.setDelFlag(false);
            item.setOrderNum(0);
            item.setProcessSetId(processId);
            item.setName(processTemplate.getName());
            item.setRemark(processTemplate.getRemark());

            ProcessTemplate curItem = processTemplateService.findByProcessSetId(processId);

            if(curItem!=null){
                if(curItem.getSort()!=null) {
                    item.setSort(curItem.getSort() + 1);
                }
            }
            else{
                item.setSort(0);
            }

            int affectCount = processTemplateService.insert(item);

            if (affectCount > 0) {
                List<TemplateDepartment> templateDepartmentList = templateDepartmentService.findByTemplateId(processTemplate.getId());

                for (TemplateDepartment templateDepartment:templateDepartmentList) {
                    TemplateDepartment curTemplateDepartment = new TemplateDepartment();
                    curTemplateDepartment.setId(UUID.randomUUID().toString());
                    curTemplateDepartment.setDepartmentId(templateDepartment.getDepartmentId());
                    curTemplateDepartment.setProcessTemplateId(item.getId());
                    curTemplateDepartment.setCreateBy(subject);
                    curTemplateDepartment.setCreateTime(new Date());
                    curTemplateDepartment.setDelFlag(false);
                    templateDepartmentService.insert(curTemplateDepartment);
                }

                List<ProcessActivity> processActivityList = processActivityService.findByTemplate(processTemplateId);

                for (ProcessActivity processActivity:processActivityList) {
                    String oldProcessActivityId = processActivity.getId();
                    processActivity.setId(UUID.randomUUID().toString());
                    processActivity.setCreateBy(subject);
                    processActivity.setCreateTime(new Date());
                    processActivity.setProcessTemplateId(item.getId());

                    processActivityService.insert(processActivity);

                    List<ProcessActUser> ProcessActUserList = processActUserService.findByActivityId(oldProcessActivityId);

                    for (ProcessActUser processActUser:ProcessActUserList) {
                        processActUser.setId(UUID.randomUUID().toString());
                        processActUser.setCreateBy(subject);
                        processActUser.setCreateTime(new Date());
                        processActUser.setActivityId(processActivity.getId());

                        processActUserService.insert(processActUser);
                    }
                }

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

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

        return msgResult;
    }



}
